iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

iterate Cloud: moved from iterate/private, and it may need work to run here

This is the code of iterate Cloud (the Worker iterate-cloud-prd) as it was in
iterate/private at 0070b51df6978af1900dc4fa8e853df61a78b83d, when that repo
was archived on 27 Nov 2026. It has been moved, not released: nothing is
deployed from this repo, and it may need some fiddling to work in its new
home, because its dependencies are not byte-identical to those it had there.

Moved: internal-packages/installer, cloud-ai, cloud-clients, dummy-petshop
(a test fixture), scripts/cloud-rehearsal, scripts/zone-enrollment and the
cloud-rehearsal skill. The history did not move.

Changed for the move: iterate comes from npm at
0.4.1-main.20261126T094512Z-d43677f; the workspace lists internal-packages/*
alone; the vitest configs use the default reporter; core/ is a copy of two
folders of /repos/kernel at 088d9575c, for tests alone.

Checked on beelink: the Worker's build equals the build of iterate/private
at that commit (index.js after the bundler's comments and name counters are
taken out). Tests pass: installer 170, cloud-ai 8, cloud-clients 65,
dummy-petshop 44. Typecheck fails in cloud-clients (1 error) and in
dummy-petshop (its deploy script). README.md lists what is known to be
broken. Do not deploy from here until the Deployer's container is removed.

Session: claude a15dfe2d-2801-47f2-92a2-474375cc8046 on beelink

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Jonas Templestein, 2026-11-27 22:46 UTC · 662bdf013d63a5d5e52d25c245e4f66db0b72bea · the first commit

415 files changed

A .agents/skills/cloud-rehearsal/SKILL.md
@@ -0,0 +1,72 @@
+---
+name: cloud-rehearsal
+description: Set up a rehearsal of iterate Cloud's sign-up chat against a fake Cloudflare. Use when someone asks to set up, start, run or stop a cloud rehearsal ("set up a cloud rehearsal on tthq"), to rehearse, simulate or eval the Cloud sign-up or install chat, or to try the install guide against a Cloudflare condition (a slow card page, an account with no card, an existing domain).
+---
+
+# cloud-rehearsal
+
+"Set up a cloud rehearsal on tthq" is a whole request. Ask nothing. From the repo's root:
+
+```sh
+node scripts/cloud-rehearsal/start.ts --mind tthq.app
+```
+
+It takes about half a minute and makes no commit. Answer with the chat's link, which it prints.
+"tthq" is Misha's test mind, `tthq.app`.
+
+## What they may add
+
+- **How Cloudflare should behave** ("the card is already added", "the card page stays shut for
+  five minutes"): pass their words as they are, `--scenario "<their words>"`. Without it the world
+  is the usual start: an old account with a card and Workers Paid, and a new account named iterate
+  with no card, whose card page opens two minutes after the consent.
+- **A draft of the guide**: `--guide <file>`. Without it the sign-up agent is told the mind's own
+  draft when it has one (`apps/cloud-rehearsal/onboarding.md` in its config repo, which people
+  edit at `https://docs.<mind>/?doc=apps/cloud-rehearsal/onboarding.md`), else iterate Cloud's own
+  guide as it is on GitHub now. A draft must name the agent's tools as that guide does.
+- **Another person** who plays the new person: `--person "First Last <email>"`. Without it, the
+  person the CLI is signed in to the mind as.
+- **Another mind**: `--mind <domain>`.
+
+## The hand-over at the end is real
+
+Everything of Cloudflare is fake. The hand-over is not: when the person picks a domain where a real mind runs, the rehearsal sends that mind a sign-up record through the mind meld, and its onboarding agent gets it once the owner signs the rule at the link the chat gives (`scripts/cloud-rehearsal/README.md`, "The hand-over is real").
+
+- Put a real mind's domain into the scenario only when they ask for a hand-over ("… and hand over to benjerate.com"): `--scenario "The new account already owns benjerate.com, and its zone is active."`
+- Never the domain of a mind that somebody uses: its onboarding agent would get a stranger's record. Ask when you are not sure whose it is.
+- With any other domain the chat's hand-over step never arrives. That is a fine end for a rehearsal of the steps before it.
+
+## When the start refuses
+
+Each refusal says what to do. Do it, then start again.
+
+- **"iterate Cloud's app changed since the rehearsal app was copied"**: the rehearsal app is a copy
+  of iterate Cloud's app, and that has moved on. Bring the changes over
+  (`scripts/cloud-rehearsal/README.md`, "When iterate Cloud's app changes"). It is part of setting
+  up: a rehearsal of yesterday's Cloud misleads. Say in your answer what you brought over. Only
+  when they want the old one as it is: `--stale-app`.
+- **"This mind has no rehearsal app, or not this checkout's"**:
+  `node scripts/cloud-rehearsal/install.ts --mind <domain>`. That is one commit to the mind's
+  config repo: say so in your answer.
+- **"The CLI is not signed in"**: `iterate login <domain>`, which the person approves.
+- **"No agent can be the fake's author"**: neither `claude -p` nor `codex exec` works on this
+  machine. Tell the person which one to sign in to.
+
+## While it runs
+
+The run's folder is `scripts/cloud-rehearsal/runs.ignoreme/fake-cf-<time>/`.
+
+- `run.jsonl` is every call and who answered it. "agent" means that the author wrote a rule for
+  it. "Cloudflare's routes: no such route" means that the chat called something that is not
+  Cloudflare's API.
+- To change the rehearsal under way (a wait, a card, a domain), edit `world.json`. To change an
+  answer, add a rule to `rules.mjs` (`RULES.md` beside it).
+- A rule that every rehearsal should have goes into `scripts/cloud-rehearsal/base-rules.ts`, with a
+  test in `fake-cloudflare.test.ts`.
+
+## Stopping one
+
+`node scripts/cloud-rehearsal/stop.ts fake-cf-<time>`. `pids.json` in a run's folder means that it
+was started; `ps -p <pid>` says whether it still runs. The folder and the chat in the mind stay:
+they are the record. To take the mind's part away, see the README's "Removing a rehearsal from a
+mind".
A .gitignore
@@ -0,0 +1,72 @@
+.DS_Store
+node_modules
+.pnpm-store
+*.tsbuildinfo
+
+# TanStack
+.tanstack
+build
+dist
+
+# Cloudflare
+.mf
+.wrangler
+.dev.vars*
+!.dev.vars.example
+.env*
+!.env.example
+
+.cursor/rules
+.rules
+.clinerules/
+
+.cache
+__pycache__/
+
+# ad-hoc ignored files/paths
+*ignoreme*
+
+# Playwright test artifacts
+test-results/
+playwright-report/
+.last-run.json
+
+*.db
+*.sqlite
+*.db-wal
+
+*.db-shm
+*.db-journal
+*.sqlite-wal
+*.sqlite-shm
+*.sqlite-journal
+.output
+
+# opencode sessions
+session-ses*.md
+_code-review*.md
+
+# local lint-staged config
+lint-staged.local.cjs
+
+# local Claude overrides
+.claude/settings.local.json
+
+playwriter-screenshot-*
+
+# PR video recordings
+pr-videos/
+*.log
+
+# Local dev secrets and miniflare state an older checkout may still hold; never commit.
+.alchemy/
+
+# What `cf` and the Cloudflare Vite plugin build and keep (.cloudflare/output, state, types). A
+# deployment's own iterate config and secrets are core/os/.gitignore's.
+.cloudflare
+
+# core/alchemy: a real config and secrets that an older checkout may still hold; never commit.
+core/alchemy/mind.config*.local.ts
+core/alchemy/.secrets
+# the deploy image's copy of the stack (internal-packages/installer/container/pack-stack.sh)
+internal-packages/installer/container/stack/
A .nvmrc
@@ -0,0 +1,1 @@
+26
A KERNEL_PIN
@@ -0,0 +1,1 @@
+088d9575c87a191edc645ec6bc03bbf0427d6733
A LICENSE
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
A PREDECESSOR
@@ -0,0 +1,1 @@
+0070b51df6978af1900dc4fa8e853df61a78b83d
A README.md
@@ -0,0 +1,46 @@
+# iterate Cloud
+
+The source of iterate Cloud, the Worker `iterate-cloud-prd` at https://cloud.iterate.com.
+
+Moved from `iterate/private` (archived on 27 Nov 2026) at commit
+`0070b51df6978af1900dc4fa8e853df61a78b83d`. The file `PREDECESSOR` names that commit.
+**It may need some work before it runs from here.** Nothing has been deployed from this repo.
+
+## What is here
+
+| Folder | What it holds |
+|---|---|
+| `internal-packages/installer` | the Worker, its pages, its Durable Objects, the production deploy script |
+| `internal-packages/cloud-ai` | AI lending, bundled into the Worker |
+| `internal-packages/cloud-clients` | the provider OAuth clients and webhooks, bundled into the Worker |
+| `internal-packages/dummy-petshop` | a test fixture: a Worker that an install can be tried against |
+| `scripts/cloud-rehearsal`, `scripts/zone-enrollment` | operator scripts |
+| `core/` | a copy of `core/lib/src` and `core/secrets-worker/src` of `/repos/kernel` at the commit in `KERNEL_PIN`. Tests import it; the Worker does not |
+
+## What differs from iterate/private
+
+- `iterate` is the npm package at `0.4.1-main.20261126T094512Z-d43677f`, not a workspace link.
+- The workspace lists `internal-packages/*` alone. The catalog, the patches and the lockfile are
+  iterate/private's.
+- The vitest configs use vitest's default reporter.
+
+## Checks
+
+    pnpm install
+    pnpm -r typecheck
+    pnpm -r test
+
+## Known to be broken
+
+- **Do not deploy from here yet.** The Deployer's image (`internal-packages/installer/container`)
+  builds from the platform's `core/` packages, which this repo does not have. The container is to
+  be removed first.
+- `scripts/deploy-prd.mjs` refuses a first release from this repo: the live version names a commit
+  of iterate/private that this repo does not have.
+- `cloud-clients` typecheck: 1 error. The kernel's `secrets.ts` is newer than the pinned npm build
+  of `iterate`.
+- `dummy-petshop` typecheck: `scripts/deploy.ts` imports `envs.ts` and `scripts/lib/deploy-app.ts`
+  of iterate/private, which did not move.
+- 4 test files of the installer (`platform-host`, `scopes`, `installations`, `stack-config`) import
+  `core/alchemy` and `core/mind-worker`, and no script runs them.
+- `scripts/zone-enrollment`'s test imports `core/alchemy`, which is not here.
A core/lib/src/acts.test.ts
@@ -0,0 +1,349 @@
+import { expect, test } from "vitest";
+import {
+  ActRule,
+  actOfText,
+  actText,
+  mailActOf,
+  mailHeaderRefusal,
+  mailHeadersOf,
+  recipientsRefusal,
+  RUN_ACTS_HEADER,
+  ruleHolds,
+  runApprovedActs,
+  rulesTighten,
+  sha256Hex,
+  verbActOf,
+} from "./acts.ts";
+
+test("a mail is one exact text: the same mail sent again is the same act, with no bytes in it", async () => {
+  const first = await mailActOf(mail({ headers: { "X-Iterate-Cause": "one" } }));
+  const again = await mailActOf(mail({ headers: { "X-Iterate-Cause": "two" } }));
+  expect(actText(first)).toBe(actText(again));
+  expect(first).toEqual({
+    act: "email.send",
+    from: "agent@example.com",
+    fromName: "The agent",
+    replyTo: null,
+    to: ["jo@example.net"],
+    cc: [],
+    subject: "The invoice",
+    text: "Attached.",
+    html: null,
+    inReplyTo: null,
+    references: null,
+    attachments: [
+      {
+        filename: "invoice.pdf",
+        contentType: "application/pdf",
+        size: 3,
+        sha256: await sha256Hex(new Uint8Array([1, 2, 3])),
+        path: "/files/invoice.pdf",
+      },
+    ],
+  });
+  expect(JSON.parse(actText(first))).toEqual(first);
+  // any change a person would see is another act
+  const other = await mailActOf(mail({ subject: "The invoice, again" }));
+  expect(actText(other)).not.toBe(actText(first));
+  const replyTo = await mailActOf(mail({ headers: { "Reply-To": "elsewhere@example.org" } }));
+  expect(replyTo).toMatchObject({ replyTo: "elsewhere@example.org" });
+});
+
+test.for([
+  ["every mail", { verb: "email.send" }, ["jo@example.net"], true],
+  ["a mail to a domain", { verb: "email.send", to: ["*@example.net"] }, ["jo@example.net"], true],
+  ["a mail to another domain", { verb: "email.send", to: ["*@example.net"] }, ["jo@x.org"], false],
+  [
+    "a recipient with a name before its address, which every pattern holds",
+    { verb: "email.send", to: ["jo@x.org"] },
+    ["Jo <JO@x.org>"],
+    true,
+  ],
+  [
+    "a domain that only ends alike",
+    { verb: "email.send", to: ["*@x.org"] },
+    ["jo@notx.org"],
+    false,
+  ],
+  ["a verb's rule", { verb: "itx.whatsapp.sendMessage" }, ["jo@example.net"], false],
+] as const)("a mail rule holds %s", async ([, rule, to, held]) => {
+  const act = await mailActOf(mail({ to: [...to] }));
+  expect(ruleHolds(ActRule.parse(rule), act)).toBe(held);
+});
+
+test("a late approval names its acts by their ids, so the vault's answer stays small whatever the acts hold", async () => {
+  const digests = await Promise.all(
+    Array.from({ length: 50 }, (_unused, index) => sha256Hex(`act ${index}`)),
+  );
+  const named = digests.join(",");
+  // fifty acts, the most the gate holds: far under what a header may carry
+  expect(named.length).toBeLessThan(4096);
+  const ran: string[] = [];
+  const { answer, ran: all } = runApprovedActs(
+    Response.json({ ok: true }, { headers: { [RUN_ACTS_HEADER]: `${named},not-an-id` } }),
+    async (digest) => void ran.push(digest),
+  );
+  await all;
+  expect(ran).toEqual(digests);
+  // the header is the boundary's alone: it does not go on to the browser
+  expect(answer.headers.has(RUN_ACTS_HEADER)).toBe(false);
+  expect(await answer.json()).toEqual({ ok: true });
+});
+
+test("a copy counts as a recipient", async () => {
+  const act = await mailActOf(mail({ to: ["a@x.org"], cc: ["jo@example.net"] }));
+  expect(ruleHolds(ActRule.parse({ verb: "email.send", to: ["*@example.net"] }), act)).toBe(true);
+});
+
+test("a held call may carry the kernel's mark of what its name was, and nothing else beside its name and arguments", () => {
+  const act = { act: "itx.whatsapp.sendMessage", args: ["jo"], resolved: "a".repeat(64) };
+  expect(actOfText(JSON.stringify(act))).toEqual(act);
+  expect(actOfText(JSON.stringify({ ...act, platform: true }))).toBeNull();
+});
+
+test("a held call may name the context whose table read its name, as a path of the mind, and say that loaded code asked", () => {
+  const act = { act: "itx.whatsapp.sendMessage", args: ["jo"], at: "/agents/one" };
+  expect(actOfText(JSON.stringify(act))).toEqual(act);
+  expect(actOfText(JSON.stringify({ ...act, at: "agents/one" }))).toBeNull();
+  expect(actOfText(JSON.stringify({ ...act, byLoadedCode: true }))).toEqual({
+    ...act,
+    byLoadedCode: true,
+  });
+  expect(actOfText(JSON.stringify({ ...act, byLoadedCode: false }))).toBeNull();
+  // and that a stored row's run asked
+  expect(actOfText(JSON.stringify({ ...act, byRow: true }))).toEqual({ ...act, byRow: true });
+  expect(actOfText(JSON.stringify({ ...act, byRow: false }))).toBeNull();
+});
+
+test.for([
+  ["a name before the address", "Jo <jo@example.net>"],
+  // a rule and an approver would read safe@example.org; the mail service sends to the last address
+  ["a name that holds another address", '"<safe@example.org>" <leak@example.net>'],
+  ["two addresses in one", "a@example.org, leak@example.net"],
+  ["an address in angle brackets", "<jo@example.net>"],
+  ["a space", "jo @example.net"],
+  ["no address at all", "undisclosed-recipients:;"],
+])("a recipient with %s is refused: the boundary sends to one address alone", ([, recipient]) => {
+  expect(recipientsRefusal(["a@example.org", recipient])).toContain("its address alone");
+});
+
+test("recipients that are each one address are taken", () => {
+  // a tag, capitals and an apostrophe are parts of real addresses
+  expect(
+    recipientsRefusal(["a@example.org", "Jo.Smith+tag@Sub.Example.net", "o'brien@example.org"]),
+  ).toBeNull();
+  expect(recipientsRefusal([])).toBeNull();
+  expect(recipientsRefusal(["a@example.org", ""])).toContain("its address alone");
+});
+
+test("a recipient that is no single address is held by every rule for mail, whatever its pattern", async () => {
+  // such a mail never leaves the boundary; were one asked about, no pattern would let it by
+  const act = { ...(await mailActOf(mail())), to: ['"<safe@example.org>" <leak@example.net>'] };
+  expect(ruleHolds(ActRule.parse({ verb: "email.send", to: ["*@example.net"] }), act)).toBe(true);
+  expect(ruleHolds(ActRule.parse({ verb: "email.send", to: ["nobody@x.org"] }), act)).toBe(true);
+});
+
+test("a domain with a dot at an end is no address: the same host by another text would pass a rule for the domain", async () => {
+  for (const recipient of ["jo@example.net.", "jo@.example.net", "jo@example..net"])
+    expect(recipientsRefusal([recipient])).toContain("its address alone");
+  // such a mail never leaves the boundary; were one asked about, the rule for its domain holds it
+  const act = { ...(await mailActOf(mail())), to: ["jo@example.net."] };
+  expect(ruleHolds(ActRule.parse({ verb: "email.send", to: ["*@example.net"] }), act)).toBe(true);
+});
+
+test("a rule that names an address holds the same mailbox with a tag, and no other mailbox", async () => {
+  const tagged = await mailActOf(mail({ to: ["Jo+bills@example.net"] }));
+  const to = (address: string) => ActRule.parse({ verb: "email.send", to: [address] });
+  expect([
+    ruleHolds(to("jo@example.net"), tagged),
+    ruleHolds(to("joe@example.net"), tagged),
+    ruleHolds(to("jo@example.org"), tagged),
+    // a rule that names the tag holds that tag
+    ruleHolds(to("jo+bills@example.net"), tagged),
+    ruleHolds(to("jo+other@example.net"), tagged),
+  ]).toEqual([true, false, false, true, false]);
+});
+
+test.for([
+  ["the subject", { subject: "The invoice\r\nBcc: leak@example.net" }],
+  [
+    "the sender's name",
+    { from: { email: "agent@example.com", name: "The agent\nBcc: leak@example.net" } },
+  ],
+  ["Reply-To", { headers: { "Reply-To": "jo@example.com\r\nBcc: leak@example.net" } }],
+  ["In-Reply-To", { headers: { "In-Reply-To": "<m1@example.org>\nBcc: leak@example.net" } }],
+  ["References", { headers: { References: "<m0@example.org>\r<m1@example.org>" } }],
+] as const)(
+  "a mail with a line break in %s is refused: what follows it would be a header that nobody read",
+  async ([field, change]) => {
+    expect(mailHeaderRefusal(await mailActOf(mail(change)))).toContain(field);
+  },
+);
+
+test("a mail whose headers are each one line is taken", async () => {
+  const given = { "Reply-To": "jo@example.com", References: "<m0@example.org> <m1@example.org>" };
+  expect(mailHeaderRefusal(await mailActOf(mail({ headers: given })))).toBeNull();
+  // a body has as many lines as it likes
+  expect(mailHeaderRefusal(await mailActOf(mail({ text: "one\ntwo" })))).toBeNull();
+});
+
+test("the mail that goes has the act's own three headers and no other that its sender gave", async () => {
+  const given = {
+    "reply-to": "alice@example.com",
+    // a second one in another letter case, a blind copy and a resend: no approver saw them
+    "Reply-To": "attacker@example.net",
+    Bcc: "leak@example.net",
+    "Resent-To": "leak@example.net",
+    "In-Reply-To": "<m1@example.org>",
+    References: "<m0@example.org> <m1@example.org>",
+    "Auto-Submitted": "auto-generated",
+    "X-Iterate-Cause": "one",
+  };
+  const act = await mailActOf(mail({ headers: given }));
+  expect(mailHeadersOf(act, given)).toEqual({
+    "Reply-To": "alice@example.com",
+    "In-Reply-To": "<m1@example.org>",
+    References: "<m0@example.org> <m1@example.org>",
+    "Auto-Submitted": "auto-generated",
+  });
+  // what the act holds is what the approver's page shows as "Replies go to"
+  expect(act).toMatchObject({ replyTo: "alice@example.com" });
+  expect(mailHeadersOf(await mailActOf(mail()), { "Auto-Submitted": "no; Bcc: x@y.z" })).toEqual(
+    {},
+  );
+});
+
+test("the mail that goes keeps its hop count between minds, and only a number", async () => {
+  const act = await mailActOf(mail());
+  expect({
+    number: mailHeadersOf(act, { "X-Iterate-Mail-Hops": "4" }),
+    text: mailHeadersOf(act, { "X-Iterate-Mail-Hops": "4\r\nBcc: leak@example.net" }),
+    zero: mailHeadersOf(act, { "X-Iterate-Mail-Hops": "0" }),
+  }).toEqual({ number: { "X-Iterate-Mail-Hops": "4" }, text: {}, zero: {} });
+});
+
+test("a verb's rule holds that verb, or every verb under a prefix, and no other", () => {
+  const send = { act: "itx.whatsapp.sendMessage", args: ["jo", { text: "hello" }] };
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp.sendMessage" }), send)).toBe(true);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp.*" }), send)).toBe(true);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp.send" }), send)).toBe(false);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whats.*" }), send)).toBe(false);
+  expect(ruleHolds(ActRule.parse({ verb: "email.send" }), send)).toBe(false);
+});
+
+test("the gate reads a verb's rule as the kernel does: the rule's name and every name under it, with .* or without", () => {
+  // the kernel holds these two calls and asks the gate, which must not free them
+  const under = { act: "itx.whatsapp.sendMessage.now", args: ["jo"] };
+  const itself = { act: "itx.whatsapp", args: ["jo"] };
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp.sendMessage" }), under)).toBe(true);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp" }), under)).toBe(true);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp.*" }), itself)).toBe(true);
+  // a name that only begins with the same letters is another name
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whats" }), itself)).toBe(false);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whats.*" }), itself)).toBe(false);
+  expect(ruleHolds(ActRule.parse({ verb: "itx.whatsapp.send" }), under)).toBe(false);
+});
+
+test("a rule is a verb, with recipients for a mail alone", () => {
+  for (const rule of [
+    { verb: "secrets.set" },
+    { verb: "itx" },
+    { verb: "itx.*" },
+    { verb: "itx.whatsapp.*.send" },
+    { verb: "itx.whatsapp.sendMessage", to: ["*"] },
+    { verb: "email.send", to: [] },
+    { verb: "email.send", to: ["example.net"] },
+    { verb: "email.send", extra: true },
+  ])
+    expect(ActRule.safeParse(rule)).toHaveProperty("success", false);
+  expect(ActRule.parse({ verb: "email.send", to: ["*@B.com", "a@b.com", "*@b.com"] })).toEqual({
+    verb: "email.send",
+    to: ["*@b.com", "a@b.com"],
+  });
+});
+
+test("a held verb's arguments are plain JSON", () => {
+  expect(verbActOf("itx.whatsapp.sendMessage", ["jo", { text: "hi", n: [1, null] }])).toEqual({
+    act: "itx.whatsapp.sendMessage",
+    args: ["jo", { text: "hi", n: [1, null] }],
+  });
+  for (const args of [[new Uint8Array(2)], [() => {}], [{ at: new Date(0) }], [undefined]])
+    expect(verbActOf("itx.whatsapp.sendMessage", args)).toHaveProperty("refused");
+});
+
+test.for([
+  [
+    "one more rule",
+    [{ verb: "email.send", to: ["*@a.com"] }],
+    [{ verb: "email.send", to: ["*@a.com"] }, { verb: "itx.x.y" }],
+    true,
+  ],
+  [
+    "one more recipient",
+    [{ verb: "email.send", to: ["*@a.com"] }],
+    [{ verb: "email.send", to: ["*@a.com", "*@b.com"] }],
+    true,
+  ],
+  [
+    "every mail in place of some",
+    [{ verb: "email.send", to: ["*@a.com"] }],
+    [{ verb: "email.send" }],
+    true,
+  ],
+  ["a prefix in place of a verb", [{ verb: "itx.x.y" }], [{ verb: "itx.x.*" }], true],
+  [
+    "a rule removed",
+    [{ verb: "email.send" }, { verb: "itx.x.y" }],
+    [{ verb: "email.send" }],
+    false,
+  ],
+  [
+    "a recipient removed",
+    [{ verb: "email.send", to: ["*@a.com", "*@b.com"] }],
+    [{ verb: "email.send", to: ["*@a.com"] }],
+    false,
+  ],
+  [
+    "some mail in place of every mail",
+    [{ verb: "email.send" }],
+    [{ verb: "email.send", to: ["*@a.com"] }],
+    false,
+  ],
+  ["a verb in place of a prefix", [{ verb: "itx.x.*" }], [{ verb: "itx.x.y" }], false],
+  // with .* or without, a rule holds its name and every name under it
+  ["a name in place of every verb under it", [{ verb: "itx.x.*" }], [{ verb: "itx.x" }], true],
+  [
+    "every verb under a name in place of the name",
+    [{ verb: "itx.x" }],
+    [{ verb: "itx.x.*" }],
+    true,
+  ],
+  ["a name above in place of a verb", [{ verb: "itx.x.y" }], [{ verb: "itx.x" }], true],
+  ["a verb under a name in place of the name", [{ verb: "itx.x" }], [{ verb: "itx.x.y" }], false],
+  ["a name that only begins the same", [{ verb: "itx.xy" }], [{ verb: "itx.x" }], false],
+] as const)("%s: tighter is %s", ([, before, after, tighter]) => {
+  const parsed = (rules: readonly unknown[]) => rules.map((rule) => ActRule.parse(rule));
+  expect(rulesTighten(parsed(before), parsed(after))).toBe(tighter);
+});
+
+function mail(
+  change: Partial<Parameters<typeof mailActOf>[0]> = {},
+): Parameters<typeof mailActOf>[0] {
+  return {
+    from: { email: "Agent@example.com", name: "The agent" },
+    to: ["jo@example.net"],
+    cc: [],
+    subject: "The invoice",
+    text: "Attached.",
+    headers: {},
+    attachments: [
+      {
+        filename: "invoice.pdf",
+        contentType: "application/pdf",
+        content: new Uint8Array([1, 2, 3]),
+        path: "/files/invoice.pdf",
+      },
+    ],
+    ...change,
+  };
+}
A core/lib/src/acts.ts
@@ -0,0 +1,343 @@
+// acts.ts — AN ACT THAT WAITS FOR A MEMBER'S YES (tasks/signed-events.md). A mail, or a call of a
+// named verb, that a rule names is held in the vault's gate (core/secrets-worker/src/acts-gate.ts)
+// as one exact text. Its SHA-256 is its id. A member reads that text on `/secrets/approvals` and
+// signs a statement that names the id. A request sent with a secret is held the same way by its
+// secret (core/secrets-worker/src/approval.ts): this module is everything else.
+import { z } from "zod";
+import { MAIL_HOPS_HEADER, mailHopsOf, reportIssue } from "./lib.ts";
+
+/** The context that holds the gate's facts. */
+export const APPROVALS_CONTEXT = "/approvals";
+
+/** The gate's facts. An approval and a rejection are also the types of the statements a member signs. */
+export const ACT_HELD = "events.iterate.com/approval/act-held";
+export const ACT_APPROVED = "events.iterate.com/approval/act-approved";
+export const ACT_REJECTED = "events.iterate.com/approval/act-rejected";
+export const ACT_HOLD_EXPIRED = "events.iterate.com/approval/hold-expired";
+/** On the caller's context: what became of an act that a member approved after its caller stopped waiting. */
+export const ACT_DONE = "events.iterate.com/approval/act-done";
+export const RULE_SET = "events.iterate.com/approval/rule-set";
+export const RULE_PROPOSED = "events.iterate.com/approval/rule-proposed";
+export const RULE_PROPOSAL_REJECTED = "events.iterate.com/approval/rule-proposal-rejected";
+/** A member signed a proposed rule for a request with a secret into that secret's rule. A proposed
+ *  rule for an act ends with `rule-set`, whose payload names the proposal. */
+export const RULE_PROPOSAL_SIGNED = "events.iterate.com/approval/rule-proposal-signed";
+export const GATE_LOCKED = "events.iterate.com/approval/locked";
+export const GATE_UNLOCKED = "events.iterate.com/approval/unlocked";
+
+/** On the vault's answer to an approval, for the boundary alone, which removes it: the ids of the
+ *  acts that a member approved after their caller stopped waiting, with commas between. An id is
+ *  64 characters, and an act's text may be 1 MiB, which no header carries: the boundary reads each
+ *  act from the gate by its id, and hands it to the mind, which does it then. */
+export const RUN_ACTS_HEADER = "x-iterate-run-acts";
+
+/** The vault's answer with RUN_ACTS_HEADER read and removed: `run` gets the id of each act it
+ *  names. The boundary's, on what the secrets Worker answers. Never rejects. */
+export function runApprovedActs(
+  answer: Response,
+  run: (digest: string) => Promise<unknown>,
+): { answer: Response; ran: Promise<void> } {
+  const header = answer.headers.get(RUN_ACTS_HEADER);
+  if (!header) return { answer, ran: Promise.resolve() };
+  const headers = new Headers(answer.headers);
+  headers.delete(RUN_ACTS_HEADER);
+  const digests = header.split(",").filter((digest) => /^[0-9a-f]{64}$/.test(digest));
+  if (digests.length !== header.split(",").length)
+    reportIssue("approval.run-unreadable", new Error("the vault named an act by no id"));
+  const ran = Promise.all(
+    digests.map((digest) =>
+      run(digest).catch((error: unknown) => reportIssue("approval.act-not-run", error, { digest })),
+    ),
+  ).then(() => {});
+  return {
+    answer: new Response(answer.body, {
+      status: answer.status,
+      statusText: answer.statusText,
+      headers,
+    }),
+    ran,
+  };
+}
+
+/** The one verb of the platform's own that a rule may name. Every other is `itx.<name>…`. */
+export const EMAIL_SEND = "email.send";
+
+/** A RULE names a verb. `email.send` is a mail; with `to`, only a mail to a recipient that matches
+ *  one of its patterns (`*@example.com`, `jo@example.com`, `*`). `itx.whatsapp.sendMessage` is a
+ *  call of that verb, and `itx.whatsapp.*` of every verb under it. Each holds the calls under its
+ *  name too, and a call of the name itself (`heldNameOf`). */
+export const ActRule = z
+  .object({
+    verb: z
+      .string()
+      .regex(
+        /^(?:email\.send|itx(?:\.[a-zA-Z][a-zA-Z0-9]*)+(?:\.\*)?)$/,
+        "a rule names email.send, a verb such as itx.whatsapp.sendMessage, or itx.whatsapp.*",
+      ),
+    to: z
+      .array(
+        z
+          .string()
+          .regex(
+            /^(?:\*|(?:\*|[^@\s*]+)@[^@\s*]+)$/,
+            "a recipient is jo@example.com, *@example.com or *",
+          ),
+      )
+      .min(1)
+      .optional(),
+  })
+  .strict()
+  .refine(
+    (rule) => !rule.to || rule.verb === EMAIL_SEND,
+    "only a rule for email.send names recipients",
+  )
+  .transform(({ verb, to }) => ({
+    verb,
+    ...(to && { to: [...new Set(to.map((pattern) => pattern.toLowerCase()))].sort() }),
+  }));
+export type ActRule = z.infer<typeof ActRule>;
+
+/** A mail as its approver reads it. Attachments are named by their bytes' hash, never carried.
+ *  `inReplyTo` and `references` are the headers as they are sent; an attachment's `path` is where
+ *  the file is in the mind's files, when the mind said. */
+const MailAct = z.strictObject({
+  act: z.literal(EMAIL_SEND),
+  from: z.string(),
+  fromName: z.string(),
+  replyTo: z.string().nullable(),
+  to: z.array(z.string()),
+  cc: z.array(z.string()),
+  subject: z.string(),
+  text: z.string().nullable(),
+  html: z.string().nullable(),
+  inReplyTo: z.string().nullable(),
+  references: z.string().nullable(),
+  attachments: z.array(
+    z.strictObject({
+      filename: z.string(),
+      contentType: z.string(),
+      size: z.number(),
+      sha256: z.string(),
+      path: z.string().nullable(),
+    }),
+  ),
+});
+export type MailAct = z.infer<typeof MailAct>;
+
+/** A call of a verb: its name and its arguments, which are plain JSON. `at` is the context whose
+ *  table read the name when the act was held: a caller in another context may read the same name
+ *  as another function, so an approval that comes late is done at `at`. `byLoadedCode` says that
+ *  the mind's loaded code asked: an approval that comes late is done as loaded code is, with its
+ *  limits. `byRow` says that a stored row's run asked (a subscription's delivery, the ingress
+ *  row for a request): an approval that comes late is done as a row's run is, and what it writes
+ *  is checked as loaded code's is. `resolved` is the kernel's mark of what the name was then (a hash): the same name on
+ *  another function is another act. */
+const VerbAct = z.strictObject({
+  act: z.string().startsWith("itx."),
+  args: z.array(z.unknown()),
+  at: z.string().startsWith("/").optional(),
+  byLoadedCode: z.literal(true).optional(),
+  byRow: z.literal(true).optional(),
+  resolved: z.string().optional(),
+});
+export type VerbAct = z.infer<typeof VerbAct>;
+
+const Act = z.union([MailAct, VerbAct]);
+export type Act = z.infer<typeof Act>;
+
+/** Whether the act is a mail: the one verb that is no `itx.` name. */
+export const isMailAct = (act: Act): act is MailAct => act.act === EMAIL_SEND;
+
+/** The act a text is, or null when it is none: the gate keeps, and the mind does, only this. */
+export function actOfText(text: string): Act | null {
+  try {
+    return Act.parse(JSON.parse(text));
+  } catch {
+    return null;
+  }
+}
+
+/** The exact text of an act: what the gate keeps, the approver hashes and the statement names. */
+export const actText = (act: Act): string => JSON.stringify(act);
+
+/** A mail as the boundary is asked to send it: the shape of ./workers.ts `OutboundEmail`. Written
+ *  again here because ./api.ts names a rule's type from this module, and must not bring the
+ *  Workers' own types into a program that has none (a script, a client). */
+type MailToSend = {
+  from: { email: string; name: string };
+  to: string[];
+  cc: string[];
+  subject: string;
+  text?: string;
+  html?: string;
+  headers: Record<string, string>;
+  attachments: { filename: string; contentType: string; content: Uint8Array; path?: string }[];
+};
+
+/** The mail the boundary is asked to send, as an act. Headers that differ between two tries of one
+ *  mail (our mark) are left out, so a retry is the same act. */
+export async function mailActOf(message: MailToSend): Promise<MailAct> {
+  const header = (name: string) =>
+    Object.entries(message.headers).find(([key]) => key.toLowerCase() === name)?.[1] || null;
+  return {
+    act: EMAIL_SEND,
+    from: message.from.email.toLowerCase(),
+    fromName: message.from.name,
+    replyTo: header("reply-to"),
+    to: message.to,
+    cc: message.cc,
+    subject: message.subject,
+    text: message.text || null,
+    html: message.html || null,
+    inReplyTo: header("in-reply-to"),
+    references: header("references"),
+    attachments: await Promise.all(
+      message.attachments.map(async ({ filename, contentType, content, path }) => ({
+        filename,
+        contentType,
+        size: content.byteLength,
+        sha256: await sha256Hex(content),
+        path: path || null,
+      })),
+    ),
+  };
+}
+
+/** One address and nothing else: no name before it, no angle brackets, no second address. Its
+ *  domain is names with one dot between them: `example.net.` is the same host to the mail service
+ *  and another text to a rule for `*@example.net`. */
+const BARE_ADDRESS = /^[^\s<>",;:()[\]\\@]+@(?:[A-Za-z0-9-]+\.)*[A-Za-z0-9-]+$/;
+
+/** WHY THE BOUNDARY DOES NOT SEND TO THESE RECIPIENTS, or null. A recipient is one address alone.
+ *  A name before the address can hold another address in angle brackets
+ *  (`"<safe@x>" <leak@evil>`): a rule and an approver would read the first, and the mail service
+ *  sends to the last. */
+export function recipientsRefusal(recipients: readonly string[]): string | null {
+  // by its place: an empty recipient is odd too
+  const at = recipients.findIndex((recipient) => !BARE_ADDRESS.test(recipient));
+  if (at < 0) return null;
+  return `name each recipient by its address alone, as jo@example.com: ${JSON.stringify(recipients[at]!.slice(0, 80))} is not one`;
+}
+
+/** WHY THE BOUNDARY DOES NOT SEND THIS MAIL, or null: a line break in a field that becomes a
+ *  header. A header is one line. What comes after a line break in its value is a header of its own
+ *  to whatever writes the mail, a Bcc for one, which no rule read and no approver saw as such. */
+export function mailHeaderRefusal(
+  act: Pick<MailAct, "subject" | "fromName" | "replyTo" | "inReplyTo" | "references">,
+): string | null {
+  const odd = Object.entries({
+    "the subject": act.subject,
+    "the sender's name": act.fromName,
+    "Reply-To": act.replyTo,
+    "In-Reply-To": act.inReplyTo,
+    References: act.references,
+  }).find(([, value]) => value && /[\r\n]/.test(value));
+  return odd ? `a mail's header is one line, and ${odd[0]} has a line break` : null;
+}
+
+/** THE HEADERS OF THE MAIL THAT GOES: the three that the act holds, made again from the act,
+ *  whether the mail says that a program wrote it, and its hop count between minds (./lib.ts
+ *  `MAIL_HOPS_HEADER`), a number alone. Every other header that the sender gave is left out, since
+ *  no approver saw it: a Bcc, or a second Reply-To in another letter case. */
+export function mailHeadersOf(act: MailAct, given: Record<string, string>): Record<string, string> {
+  const valueOf = (header: string) =>
+    Object.entries(given).find(([name]) => name.toLowerCase() === header.toLowerCase())?.[1];
+  const automatic = valueOf("auto-submitted");
+  const hops = mailHopsOf(valueOf(MAIL_HOPS_HEADER));
+  return Object.fromEntries(
+    Object.entries({
+      "Reply-To": act.replyTo,
+      "In-Reply-To": act.inReplyTo,
+      References: act.references,
+      "Auto-Submitted": automatic && /^auto-(?:generated|replied)$/.test(automatic) && automatic,
+      [MAIL_HOPS_HEADER]: hops && String(hops),
+    }).filter((header): header is [string, string] => Boolean(header[1])),
+  );
+}
+
+/** A call of `verb` as an act, or why it cannot wait: only plain JSON can be shown and signed. */
+export function verbActOf(verb: string, args: unknown[]): VerbAct | { refused: string } {
+  if (args.every(isPlainJson)) return { act: verb, args };
+  return {
+    refused: `${verb} waits for a member's approval, and its arguments must be plain JSON to be shown and signed: no stub, stream, bytes, date or function`,
+  };
+}
+
+function isPlainJson(value: unknown): boolean {
+  if (typeof value === "string" || typeof value === "boolean") return true;
+  if (typeof value === "number") return Number.isFinite(value);
+  if (typeof value !== "object") return false;
+  // JSON's null
+  if (!value) return true;
+  if (Array.isArray(value)) return value.every(isPlainJson);
+  const prototype: unknown = Object.getPrototypeOf(value);
+  return (
+    (prototype === Object.prototype || prototype === null) &&
+    Object.values(value).every(isPlainJson)
+  );
+}
+
+/** THE NAME A RULE HOLDS: its verb, without the `.*` of "every verb under it". A rule holds a call
+ *  of that name and of every name under it, with `.*` or without. The kernel reads a rule so
+ *  (core/itx/src/context/held-verbs.ts `heldVerbOf`), and the gate reads it here: were the gate
+ *  narrower, it would answer `free` for an act that the kernel held and asked it about. */
+const heldNameOf = (rule: ActRule): string =>
+  rule.verb.endsWith(".*") ? rule.verb.slice(0, -2) : rule.verb;
+const atOrUnder = (name: string, held: string): boolean =>
+  name === held || name.startsWith(`${held}.`);
+
+/** Whether a rule holds the act. */
+export function ruleHolds(rule: ActRule, act: Act): boolean {
+  if (isMailAct(act)) {
+    if (rule.verb !== EMAIL_SEND) return false;
+    if (!rule.to) return true;
+    return [...act.to, ...act.cc].some((address) =>
+      rule.to!.some((pattern) => addressMatches(pattern, address)),
+    );
+  }
+  return atOrUnder(act.act, heldNameOf(rule));
+}
+
+/** Whether a rule's pattern names the recipient. The boundary sends to one address alone
+ *  (`recipientsRefusal`); a recipient that is anything else is held by every pattern. */
+function addressMatches(pattern: string, recipient: string): boolean {
+  if (pattern === "*" || !BARE_ADDRESS.test(recipient)) return true;
+  const address = recipient.toLowerCase();
+  if (pattern.startsWith("*@")) return address.endsWith(pattern.slice(1));
+  // a tag is the same mailbox: mail to `jo+bills@example.com` is mail to jo
+  return address === pattern || address.replace(/\+[^@]*@/, "@") === pattern;
+}
+
+/** Whether `after` holds everything `before` held: a change that needs no signature once locked. */
+export function rulesTighten(before: readonly ActRule[], after: readonly ActRule[]): boolean {
+  return before.every((old) =>
+    after.some(
+      (now) =>
+        atOrUnder(heldNameOf(old), heldNameOf(now)) &&
+        (!now.to ||
+          (old.to &&
+            old.to.every((pattern) => now.to!.includes(pattern) || now.to!.includes("*")))),
+    ),
+  );
+}
+
+/** What the gate says of an act.
+ *  - `free`: no rule names it. Do it.
+ *  - `held`: it waits from now. Record the facts, then ask again with `wait`.
+ *  - `go`: a member approved it and the gate has marked it done: do it now, once.
+ *  - `rejected`: a member said no.
+ *  - `waiting`: nobody answered within the wait. It stays approvable for a day.
+ *  - `done`: it was done before. The same act is done once for one approval. */
+export type GateAnswer = (
+  | { state: "free" }
+  | { state: "held" | "go" | "waiting" | "done"; digest: string }
+  | { state: "rejected"; digest: string; reason: string; by: string }
+) & { facts: { path: string; events: { type: string; payload: Record<string, unknown> }[] }[] };
+
+export async function sha256Hex(data: string | Uint8Array): Promise<string> {
+  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
+  // WebCrypto's types ask for a view on an ArrayBuffer; a view made by TextEncoder, R2 or a mail's
+  // attachment is one, and the general `Uint8Array` type cannot say so
+  const digest = await crypto.subtle.digest("SHA-256", bytes as Uint8Array<ArrayBuffer>);
+  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
+}
A core/lib/src/agents/README.md
@@ -0,0 +1,149 @@
+# iterate/agents
+
+The agents app for Iterate minds: the collection of a mind's agents, `itx.agents`, and the catalog
+of them on `/agents`. A mind installs it; the platform ships its code as `iterate/agents`, so a
+mind runs the deployment's own build and upgrades with it, like `iterate/sdk`.
+
+**The platform runs no agent.** The mind's own agent is code in the mind's config repo
+(`core/configs/default/agent/`: its processor, its request makers and its tests). The config
+tells the collection how to start one, and the collection appends those facts. Any other kind of
+agent (a coding session that a bridge appends to) is its kind's business.
+
+## Install
+
+A mind's config repo re-exports the collection's class from its root `agents.ts`, tells it which
+agent `create` starts, and installs the app from its init case (core/configs/default does all
+three). It lists no dependency: `iterate/*` comes from the platform.
+
+```ts
+// agents.ts
+import { AgentCollectionDurableObject } from "iterate/agents";
+import { startEvents } from "./agent-start.ts";
+
+AgentCollectionDurableObject.agent = { kind: "agent", startEvents };
+
+export { AgentCollectionDurableObject };
+```
+
+```ts
+import { installAgents } from "iterate/agents/install";
+
+// in processEvent, the init case
+case "events.iterate.com/mind/worker-updated":
+  await installAgents(itx);
+```
+
+- `kind` is what the agent's own start writes on `/agents` as its kind.
+- `startEvents(path, { parent })` answers the facts that make the context at `path` run the agent.
+  Each has an idempotency key, so appending them again writes nothing. With `parent` they hold the
+  link from the context's `itx` to that context; without, they hold none (`collection.ts`
+  `OwnAgent`).
+- A config with no `agent` has no agent to start: `create` refuses with words that say so.
+
+A config whose class is in another module names it: `installAgents(itx, { module })`.
+
+`installAgents` enables the catalog processor on `/agents` and writes the `itx.agents` rewrite rule
+on the root to the collection facet there; it does the same every time, and disables the catalog
+the root held before it moved. The collection's facet names its class in that module of the mind's
+published config (`{ className, mainModule: "agents.ts", source: itx.cd('/').config }`), so
+nothing is copied into the mind.
+
+Importing `iterate/agents` registers `itx.agents` on iterate/api's `InstalledAppRoots`:
+`itx as IterateContextApiWith<"agents">` types `create`, `get(path).message`, `get(path).recent`,
+`list` and `delete`.
+
+## What an agent is
+
+An agent is any context under `/agents`, at any depth. The mind's own agents live there
+(`/agents/people/<person>/web/<moment>` for one that a member starts on the Dash,
+`/agents/email/t<thread>`), and so can anything else that is a conversation with a title, a status
+and a way to message it, such as a coding session a bridge appends to (`/agents/claude/<session>`,
+its subagents beneath it). Every context announces itself to each of its ancestors when it first
+wakes (`itx/child-created`), and the catalog on `/agents` folds those announcements, so it lists
+every context below it with no registration step. Anything appended under `/agents` is listed,
+whether or not it is an agent: that is the rule. A row's `parent` is the nearest row above it, so
+`/agents/people/<person>/web`, which only holds that person's web agents, is the parent of each of
+them.
+
+`/agents/people` holds a folder for each person, named by the local part of the address they
+sign in with. It is a name that no long-lived agent may take: `/agents/<name>` is such an
+agent's place. Two members with the same local part at two domains share one folder.
+
+`itx.agents.list()` reads a whole list from `/agents` in one go, so showing a list of agents wakes
+none of them. Each row is small and the same for every kind of agent: `kind` (what runs it:
+`agent` for the mind's own, `claude`, …), `host`, `status` (`working`, `idle`, `waiting`,
+`ended`), `activity` (one line), `description` (a few sentences), `title` and `lastActivityAt`.
+`title` is the name the agent gave itself (a title a person writes in the Dash's About is such a
+name too: About appends `agent/summary-updated` beside the context's `itx/described`). With no
+name it is the first line a person sent, and `titleFromWords` is then true: words are no name,
+and any name replaces them. A script that writes `metadata.title` of the context alone names
+nothing in this list: it appends `agent/summary-updated { title }` on the agent's log.
+Everything but `createdAt` and `parent` comes from copies of the agent's own events onto `/agents`
+as `agent/listing-updated` (`itx.subscribe` with `target: { path: "/agents", … }`): copies only,
+since only the platform can set `source.copiedFrom`, and an older copy never undoes a newer one,
+field by field. Each kind of agent configures its own copy rows. Those of the mind's own agent are
+in its start facts (`core/configs/default/agent-start.ts` `CATALOG_ROWS`): its kind, its summary
+(title, activity, description), the first line a person sends it, and each answer request
+(`working`, then `idle`).
+
+AT WORK: the row of the mind's own agent says `idle` from the moment a model's answer settles,
+before the script of that answer runs. Readers decide with one rule, `agentAtWork`
+(`iterate/agents/at-work`): `working` or `waiting`, or `idle` with an activity line from the last
+ten minutes (a script runs at most that long). The Dash's agent rows use it.
+
+## The verbs
+
+`create(path)` starts the mind's own agent at `path`: its start facts and the collection's own row
+for it, in ONE append. Nothing is waited for but the listing, and a second create writes nothing.
+A deleted agent is not re-creatable.
+
+`get(path).message(input)` appends ONE `agent/message-received` to the agent's context, for every
+kind of agent. No verb calls a facet of an agent. The mind's own agent gets its start facts in the
+same append, before the words, so a publish of new agent code reaches an agent at its next
+message. The mind's config transcribes the fact into the agent's input
+(`core/configs/default/agent-kinds/agent.ts`). Another kind's own subscription delivers it to
+whatever runs it.
+
+`get(path).recent({ minutes, limit })` answers what one agent did lately, from its own log
+(`recent.ts`): its row's title, status, activity and description, one line per status, summary,
+words in, words out and script in the window, oldest first, and the newest script whole
+(`lastScript`, with its error if it failed). The log has no read from its end, so it reads forward
+from a few thousand offsets before the newest offset the catalog copied, at most 4,000 events. It
+wakes the agent's context alone.
+
+`delete(path)` records the death on `/agents` first, so a verb that follows refuses. Then, for the
+mind's own agent, every row that its start enables goes, and each facet with its storage. The death
+of another kind of agent is the certificate alone.
+
+A CONTEXT OF THE KIND `iterate` was run by an agent that the platform no longer has. The mind's own
+agent takes it over at its next `create` or message: the start facts replace the row named `agent`,
+and the four copy rows of the former agent are switched off. The agent reads nothing of the log
+that stands before its start (`core/configs/default/agent/contract.ts`), so its conversation
+begins there.
+
+A MESSAGE THAT LANDS ONCE. `get(path).message(input, { key })` gives the message a key of the
+sender's choice. Sent again with the same key and the same words, it lands once, and the call
+answers the event the log holds, also when two sends race. The same key with other words is
+refused (`IDEMPOTENCY_CONFLICT`). A page that cannot know whether its first try arrived sends again
+with the same key.
+
+- A file of a keyed message is never replaced: its path is made from the key, its place in the
+  list and the SHA-256 of its content. The same key and words with other file content is refused,
+  and the first event's file stays as it was. The refused send leaves its own file behind.
+- The key is the context's, not the sender's: one name space per agent. A second sender with the
+  same key and the same words gets the first sender's event, and the log names the first sender
+  alone. So a sender makes keys that nobody else would make.
+
+WHO SPOKE is the platform's stamp on a fact (`source.principal`, `source.onBehalfOf`, or a mind's
+`source.signer`). No payload names a speaker. The mind's config words the sender for the model
+when it transcribes a message (`core/configs/default/agent-ui.ts`).
+
+## The files
+
+- `contract.ts` — the three facts that every kind of agent shares: `agent/message-received`,
+  `agent/summary-updated`, `agent/deleted`.
+- `catalog.ts` — the catalog on `/agents`, and the collection's facet class.
+- `collection.ts` — `itx.agents`: `list`, `create`, `delete`, `get(path)`.
+- `message.ts` — what `message()` appends; `recent.ts` — `get(path).recent()`.
+- `install.ts` — `installAgents`; `kinds.ts` — kinds of agent; `at-work.ts` — `agentAtWork`.
+- `api.ts` — the published types.
A core/lib/src/agents/api.ts
@@ -0,0 +1,114 @@
+// api.ts — `itx.agents`, the agents app's published type. A mind installs the app (install.ts
+// mounts the collection facet as the `itx.agents` rewrite rule), so iterate/api does not name it.
+// Importing `iterate/agents` registers the root on iterate/api's `InstalledAppRoots`, and a caller
+// that knows agents are installed writes `itx as IterateContextApiWith<"agents">`. catalog.ts and
+// collection.ts implement it.
+import type { StreamEvent } from "../stream/processor.ts";
+
+/** What `agents.get(path).message(input)` takes: the words, or the words with attachments (each
+ *  stored under the agent's path in `itx.files` and named on the event). */
+export type AgentMessageInput =
+  | string
+  | {
+      message: string;
+      files?: { contentType: string; filename: string; data: Uint8Array | ArrayBuffer | string }[];
+    };
+
+/** How `message` delivers the words. `trigger: false` makes them context only: the agent reads
+ *  them on its next turn but does not wake for them (an FYI that needs nothing now). The default,
+ *  `trigger: true`, starts a turn, unless the mind gates words between agents (message.ts).
+ *  `key` names this one message, by the sender's choice (at most 200 characters): sent again with the
+ *  same key and the same words, it lands once, and the call answers the event the log already
+ *  holds. A sender that cannot know whether its first try arrived (a page after a lost
+ *  connection) sends again with the key it used. The key's name space is the agent's context,
+ *  whoever sends: make keys that nobody else would make. A file of a keyed message is never
+ *  replaced; the same key with other words or other file content is refused (message.ts). */
+export type AgentMessageOptions = { trigger?: boolean; key?: string };
+
+/** `itx.agents.get(path)`: one agent. Anything else on its context is a plain
+ *  `itx.cd(path).append(…)`, stamped with where it came from. */
+export interface AgentHandleApi {
+  /** Words for the agent: ONE `events.iterate.com/agent/message-received` on its context, the
+   *  input every kind of agent reads, answered so a caller can wait for what follows it. The
+   *  mind's config transcribes it into the input of the mind's own agent, and that input starts
+   *  the agent's next request (or, with `{ trigger: false }`, is context that it reads then). The
+   *  fact names the sender when another agent sent it: the collection's base, which the sender's
+   *  own `itx.agents` row pins (collection.ts). An agent of another kind gets the same fact, for
+   *  its own subscription to deliver. A deleted agent refuses, and so does one never created
+   *  (NOT_CREATED). */
+  message(input: AgentMessageInput, options?: AgentMessageOptions): Promise<StreamEvent>;
+  /** What the agent did lately, from its own durable log: the last `minutes` (5 by default, at
+   *  most 1,440), at most `limit` lines (30 by default, at most 200), oldest first, beside its
+   *  catalog row. It wakes no agent: it reads the log, which wakes only the agent's context. The
+   *  read starts a few thousand offsets before the newest event the catalog has copied from that
+   *  log and reads at most 4,000 events, so a window older than that is cut short. */
+  recent(options?: { minutes?: number; limit?: number }): Promise<AgentRecent>;
+}
+
+/** What `itx.agents.get(path).recent()` answers. */
+export type AgentRecent = Pick<
+  AgentListing,
+  "path" | "title" | "status" | "activity" | "description"
+> & {
+  /** One line per thing it did in the window, oldest first: `status` its run's status label,
+   *  `summary` what it said about itself (`setSummary`), `message-in` words it received,
+   *  `message-out` words it sent, `script` the first line of a script it ran. Each `text` is one
+   *  line, cut to 300 characters. */
+  did: { at: string; what: AgentDidKind; text: string }[];
+  /** The newest script it ran in the window: its status label, its whole source and, when it
+   *  failed, the error. */
+  lastScript: { at: string; status: string; script: string; error?: string } | null;
+};
+export type AgentDidKind = "status" | "summary" | "message-in" | "message-out" | "script";
+
+/** One row of `itx.agents.list()`. */
+export type AgentListing = {
+  path: string;
+  createdAt: string;
+  parent: string | null;
+  kind: string | null;
+  host: string | null;
+  status: "working" | "idle" | "waiting" | "ended" | null;
+  activity: string | null;
+  description: string | null;
+  title: string | null;
+  /** True when `title` is only the first line a person sent, and no name the agent has. */
+  titleFromWords: boolean;
+  lastActivityAt: string | null;
+};
+
+/** `itx.agents` — installed by rewrite rule on the mind's root and on each agent's context.
+ *  `create` starts the mind's own agent, whose code is in the mind's config repo. A deleted agent
+ *  is not re-creatable, and a `delete` of an agent never created refuses (NOT_CREATED). `delete`
+ *  of an agent of another kind only records its death on `/agents`. */
+export interface AgentsApi {
+  /** Every agent, with what a list shows about it. An agent is any context under `/agents`, at any
+   *  depth: an agent `create` made, a coding session a bridge appends to, anything. `parent`
+   *  is the nearest agent above it (null at the top). `kind` is what runs it (`"agent"`,
+   *  `"claude"`, …) and `host` the machine it runs on. `status` is `working`, `idle`, `waiting` (on
+   *  someone) or `ended`; `activity` one line on what it is doing now, and `description` a few
+   *  sentences on its purpose or conclusions. `title` is the name it gave itself, or else the first
+   *  line a person sent it, and then `titleFromWords` is true. `lastActivityAt` is when it was last active. Each is null until the
+   *  agent has said it. It reads only `/agents` and wakes no agent, so use it to show many agents
+   *  rather than reading each one. */
+  list(): Promise<AgentListing[]>;
+  get(path: string): AgentHandleApi;
+  create(path: string): Promise<{ path: string }>;
+  delete(path: string): Promise<{ path: string }>;
+}
+
+/** The root's own `itx.agents` (catalog.ts `AgentCollectionDurableObject`), as code holding the
+ *  root's scope reaches it. */
+export interface AgentsRootApi extends AgentsApi {
+  /** The collection as the context `base` sees it: what it creates is linked to `base`, and a
+   *  relative path means `base`'s (collection.ts). Each agent's own `itx.agents` row is the root's
+   *  `at(<agent>)`; root code acting for another context passes that context, as voice's
+   *  `setupVoiceAgent` does. */
+  at(base: string): AgentsApi;
+}
+
+declare module "iterate/api" {
+  interface InstalledAppRoots {
+    agents: AgentsApi;
+  }
+}
A core/lib/src/agents/at-work.test.ts
@@ -0,0 +1,27 @@
+// at-work.test.ts — whether a catalog row's agent is at work.
+import { expect, test } from "vitest";
+import { agentAtWork } from "./at-work.ts";
+
+const NOW = Date.parse("2026-11-16T10:42:00Z");
+
+test("at work: working or waiting within a day, or idle with a line from the last ten minutes (a script runs then, though the row says idle)", () => {
+  const atWork = (row: {
+    status: "working" | "idle" | "waiting" | "ended";
+    activity?: string;
+    minutesAgo: number;
+  }) =>
+    agentAtWork(
+      {
+        status: row.status,
+        activity: row.activity || null,
+        lastActivityAt: new Date(NOW - row.minutesAgo * 60_000).toISOString(),
+      },
+      NOW,
+    );
+  expect(atWork({ status: "working", minutesAgo: 600 })).toBe(true);
+  expect(atWork({ status: "waiting", minutesAgo: 25 * 60 })).toBe(false);
+  expect(atWork({ status: "idle", activity: "Fetching it", minutesAgo: 3 })).toBe(true);
+  expect(atWork({ status: "idle", activity: "Fetching it", minutesAgo: 11 })).toBe(false);
+  expect(atWork({ status: "idle", minutesAgo: 1 })).toBe(false);
+  expect(atWork({ status: "ended", activity: "Done", minutesAgo: 1 })).toBe(false);
+});
A core/lib/src/agents/at-work.ts
@@ -0,0 +1,22 @@
+// at-work.ts — WHETHER AN AGENT IS AT WORK, by its catalog row: the one rule that the Dash's rows
+// share. Nothing here needs a Worker: a browser imports it as `iterate/agents/at-work`.
+import { RUN_DEADLINE_MS } from "../stream/run.ts";
+import type { AgentListing } from "./api.ts";
+
+/** A row still says `working` or `waiting` this long after its last activity; older, it is stale
+ *  (an agent that stopped without saying so, a thread nobody answered) and counts as idle. */
+const LIVE_STATUS_MS = 24 * 3_600_000;
+
+/** The row says `working` or `waiting` (within a day), or it says `idle` with an `activity` line
+ *  from the last RUN_DEADLINE_MS. The second case is a script at work: the row of the mind's own
+ *  agent says `idle` once a model's answer settles, before the script of that answer runs, and its
+ *  activity is what that script says it does. A script runs at most RUN_DEADLINE_MS. So an agent
+ *  that stopped a moment ago also counts, with its last line, for up to that long. */
+export function agentAtWork(
+  row: Pick<AgentListing, "status" | "activity" | "lastActivityAt">,
+  now: number,
+): boolean {
+  const since = now - (row.lastActivityAt ? Date.parse(row.lastActivityAt) : 0);
+  if (row.status === "working" || row.status === "waiting") return since < LIVE_STATUS_MS;
+  return row.status === "idle" && Boolean(row.activity) && since < RUN_DEADLINE_MS;
+}
A core/lib/src/agents/catalog.test.ts
@@ -0,0 +1,818 @@
+// catalog.test.ts — how the agents catalog on `/agents` folds the contexts that announce themselves
+// below it, death certificates from any context and the copies of each agent's events, as
+// declarative `{ events → state }` rows on the shared harness (iterate/stream/test-support
+// `reduceProcessor`), and which `itx/described` line and title each copy puts on the agent's own
+// log.
+
+import { expect, test, vi } from "vitest";
+import type { StreamEvent } from "../stream/processor.ts";
+import { committedEvent, reduceProcessor } from "../stream/test-support.ts";
+import { AgentCatalogProcessor, type AgentCatalogState, describedKey } from "./catalog.ts";
+
+const path = "/agents/support";
+
+const born = { createdAt: new Date(1000).toISOString() };
+
+type Fact = { type: string; payload: Record<string, unknown>; source: Record<string, unknown> };
+
+test.for<{ name: string; events: Fact[]; state: AgentCatalogState }>([
+  {
+    name: "a context under /agents that announces itself: a row",
+    events: [announced(path)],
+    state: { agents: { [path]: born }, deleted: {} },
+  },
+  {
+    name: "an announcement repeated, or of a context outside /agents: nothing new",
+    events: [announced(path), announced(path), announced("/elsewhere/a"), announced("/agents")],
+    state: { agents: { [path]: born }, deleted: {} },
+  },
+  {
+    name: "a context below another row: that row is its parent, at any depth",
+    events: [announced(path), announced(`${path}/sub`), announced(`${path}/sub/deeper/still`)],
+    state: {
+      agents: {
+        [path]: born,
+        [`${path}/sub`]: { ...bornAt(2), parent: path },
+        [`${path}/sub/deeper/still`]: { ...bornAt(3), parent: `${path}/sub` },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a parent whose announcement lands after its child's: still the child's parent",
+    events: [announced(`${path}/sub/deeper`), announced(path), announced(`${path}/sub`)],
+    state: {
+      agents: {
+        [path]: bornAt(2),
+        [`${path}/sub`]: { ...bornAt(3), parent: path },
+        [`${path}/sub/deeper`]: { ...born, parent: `${path}/sub` },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a death from any context: dead, terminal, and its children move up to its parent",
+    events: [
+      announced(path),
+      announced(`${path}/sub`),
+      announced(`${path}/sub/deeper`),
+      certificate("deleted", `${path}/sub`, "/agents/other"),
+      announced(`${path}/sub`),
+    ],
+    state: {
+      agents: { [path]: born, [`${path}/sub/deeper`]: { ...bornAt(3), parent: path } },
+      deleted: { [`${path}/sub`]: { deletedAt: new Date(4000).toISOString() } },
+    },
+  },
+  {
+    name: "a name copied from the agent's log becomes its title, and marks it active",
+    events: [announced(path), title("Fix the build", 10)],
+    state: {
+      agents: {
+        [path]: { ...born, title: "Fix the build", titleAtOffset: 10, lastActivityAt: at(10) },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a person's first line is the title until the agent names itself",
+    events: [announced(path), words("Fix the build", 10)],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          title: "Fix the build",
+          titleAtOffset: 10,
+          titleFromWords: true,
+          lastActivityAt: at(10),
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "later words don't change the title",
+    events: [announced(path), words("First", 10), words("Second", 20)],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          title: "First",
+          titleAtOffset: 10,
+          titleFromWords: true,
+          lastActivityAt: at(20),
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "the same words copied again by a changed row give the title anew",
+    events: [
+      announced(path),
+      words("[From the Agents app] Fix the build. Then the docs", 10),
+      words("Fix the build", 10),
+      words("Second", 20),
+    ],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          title: "Fix the build",
+          titleAtOffset: 10,
+          titleFromWords: true,
+          lastActivityAt: at(20),
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a name still beats the same words copied again",
+    events: [announced(path), title("Named", 5), words("Fix the build", 10), words("Fix it", 10)],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          title: "Named",
+          titleAtOffset: 5,
+          lastActivityAt: at(10),
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "the first line a person sent stays the title, even when its copy lands last",
+    events: [announced(path), words("Second", 20), words("First", 10)],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          title: "First",
+          titleAtOffset: 10,
+          titleFromWords: true,
+          lastActivityAt: at(20),
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a name beats words a person sent after it",
+    events: [announced(path), title("Named", 10), words("Said after", 20)],
+    state: {
+      agents: { [path]: { ...born, title: "Named", titleAtOffset: 10, lastActivityAt: at(20) } },
+      deleted: {},
+    },
+  },
+  {
+    name: "a name replaces words, even words sent after it whose copy landed first",
+    events: [announced(path), words("Said after", 20), title("Named", 10)],
+    state: {
+      agents: { [path]: { ...born, title: "Named", titleAtOffset: 10, lastActivityAt: at(20) } },
+      deleted: {},
+    },
+  },
+  {
+    name: "an older name whose copy lands late changes nothing",
+    events: [announced(path), title("Newer", 20), title("Older", 10)],
+    state: {
+      agents: { [path]: { ...born, title: "Newer", titleAtOffset: 20, lastActivityAt: at(20) } },
+      deleted: {},
+    },
+  },
+  {
+    name: "last activity only ever moves forward",
+    events: [announced(path), activity(20), activity(10)],
+    state: { agents: { [path]: { ...born, lastActivityAt: at(20) } }, deleted: {} },
+  },
+  {
+    name: "what runs it, where, and what it is doing: each field copied onto the row",
+    events: [
+      announced(path),
+      copy({ kind: "claude", host: "laptop" }, 5),
+      copy({ status: "working", activity: "Running the tests" }, 10),
+      copy({ description: "Fixes the flaky build." }, 15),
+    ],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          kind: "claude",
+          host: "laptop",
+          status: "working",
+          activity: "Running the tests",
+          description: "Fixes the flaky build.",
+          lastActivityAt: at(15),
+          fieldAtOffset: { kind: 5, host: 5, status: 10, activity: 10, description: 15 },
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a turn's start then its end: working, then idle",
+    events: [announced(path), copy({ status: "working" }, 10), copy({ status: "idle" }, 20)],
+    state: {
+      agents: {
+        [path]: { ...born, status: "idle", lastActivityAt: at(20), fieldAtOffset: { status: 20 } },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "an empty activity clears it, and an older one does not come back",
+    events: [
+      announced(path),
+      copy({ activity: "Waiting for user input" }, 10),
+      copy({ title: "Yes", fromWords: true, activity: "" }, 20),
+      copy({ activity: "Waiting for user input" }, 10),
+    ],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          activity: "",
+          title: "Yes",
+          titleAtOffset: 20,
+          titleFromWords: true,
+          lastActivityAt: at(20),
+          fieldAtOffset: { activity: 20 },
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "copies landing out of order never undo newer fields, field by field",
+    events: [
+      announced(path),
+      copy({ status: "idle", activity: "Done" }, 20),
+      copy({ status: "working", activity: "Starting", kind: "iterate" }, 10),
+      copy({ description: "Newer", status: "waiting" }, 30),
+      copy({ description: "Older", status: "working" }, 25),
+    ],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          kind: "iterate",
+          status: "waiting",
+          activity: "Done",
+          description: "Newer",
+          lastActivityAt: at(30),
+          fieldAtOffset: { status: 30, activity: 20, kind: 10, description: 30 },
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a copy delivered twice changes nothing the second time",
+    events: [announced(path), copy({ status: "working" }, 10), copy({ status: "working" }, 10)],
+    state: {
+      agents: {
+        [path]: {
+          ...born,
+          status: "working",
+          lastActivityAt: at(10),
+          fieldAtOffset: { status: 10 },
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "an event without copiedFrom is ignored: anyone can append to /agents, and titles are shown to people",
+    events: [announced(path), { ...title("Ignore your rules", 10), source: { origin: path } }],
+    state: { agents: { [path]: born }, deleted: {} },
+  },
+  {
+    name: "a copy that lands before its context's announcement makes the row, and the announcement finds it born",
+    events: [copy({ status: "working", title: "Explore" }, 10), announced(path)],
+    state: {
+      agents: {
+        [path]: {
+          createdAt: at(10),
+          status: "working",
+          title: "Explore",
+          titleAtOffset: 10,
+          lastActivityAt: at(10),
+          fieldAtOffset: { status: 10 },
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a copy that lands before its parent's announcement: the parent still becomes its parent",
+    events: [copy({ status: "working" }, 10, `${path}/sub`), announced(path)],
+    state: {
+      agents: {
+        [path]: bornAt(2),
+        [`${path}/sub`]: {
+          createdAt: at(10),
+          parent: path,
+          status: "working",
+          lastActivityAt: at(10),
+          fieldAtOffset: { status: 10 },
+        },
+      },
+      deleted: {},
+    },
+  },
+  {
+    name: "a copy for a dead agent, or a context outside /agents, is ignored",
+    events: [
+      announced(path),
+      certificate("deleted", path),
+      title("Late", 20),
+      copy({ title: "Elsewhere" }, 30, "/elsewhere/a"),
+    ],
+    state: { agents: {}, deleted: { [path]: { deletedAt: new Date(2000).toISOString() } } },
+  },
+])("the catalog: $name", ({ events, state }) => {
+  expect(reduceProcessor(catalog().processor, events)).toEqual(state);
+});
+
+test.for<{
+  name: string;
+  events: Fact[];
+  described: { path: string; key: string; text: string }[];
+}>([
+  {
+    name: "a title the agent gave itself: its line, keyed by the copied event",
+    events: [announced(path), title("Fix the build", 10)],
+    described: [{ path, key: describedKey(path, 10, "Fix the build"), text: "Fix the build" }],
+  },
+  {
+    name: "a description after the title: the description alone, as a purpose is not a name",
+    events: [announced(path), title("Fix the build", 10), copy({ description: "CI is red" }, 11)],
+    described: [
+      { path, key: describedKey(path, 10, "Fix the build"), text: "Fix the build" },
+      { path, key: describedKey(path, 11, "CI is red"), text: "CI is red" },
+    ],
+  },
+  {
+    name: "a person's first line, then the agent's own name: each once, later words nothing",
+    events: [
+      announced(path),
+      words("Please fix the build", 10),
+      words("And the docs", 20),
+      title("Fix the build", 30),
+    ],
+    described: [
+      { path, key: describedKey(path, 10, "Please fix the build"), text: "Please fix the build" },
+      { path, key: describedKey(path, 30, "Fix the build"), text: "Fix the build" },
+    ],
+  },
+  {
+    name: "the same words copied again with another line: that line once more, and once only",
+    events: [
+      announced(path),
+      words("[From the Agents app] Fix the build", 10),
+      words("Fix the build", 10),
+      words("Fix the build", 10),
+    ],
+    described: [
+      {
+        path,
+        key: describedKey(path, 10, "[From the Agents app] Fix the build"),
+        text: "[From the Agents app] Fix the build",
+      },
+      { path, key: describedKey(path, 10, "Fix the build"), text: "Fix the build" },
+    ],
+  },
+  {
+    name: "a status, an activity, an older title landing late or a copy without copiedFrom: nothing",
+    events: [
+      announced(path),
+      title("Newer", 20),
+      copy({ status: "working", activity: "Reading" }, 21),
+      title("Older", 10),
+      { ...title("Forged", 30), source: { origin: "/elsewhere" } },
+    ],
+    described: [{ path, key: describedKey(path, 20, "Newer"), text: "Newer" }],
+  },
+])("an agent's line in the mind's catalog: $name", async ({ events, described }) => {
+  const { processor, appended } = catalog();
+  await processAll(processor, events);
+  expect(
+    appended.filter(({ event }) => event.idempotencyKey.startsWith("agents/described:")),
+  ).toEqual(
+    described.map(({ path, key, text }) => ({
+      path,
+      event: {
+        type: "events.iterate.com/itx/described",
+        idempotencyKey: key,
+        payload: { description: text },
+      },
+    })),
+  );
+});
+
+test.for<{
+  name: string;
+  events: Fact[];
+  listed?: { path: string; metadata?: Record<string, unknown> }[];
+  titled: { key: string; metadata: Record<string, unknown> }[];
+}>([
+  {
+    name: "a title the agent gave itself: metadata.title, keyed by the copied event",
+    events: [announced(path), title("Fix the build", 10)],
+    titled: [{ key: `agents/titled:${path}@10`, metadata: { title: "Fix the build" } }],
+  },
+  {
+    name: "a title over 80 characters: its first 80",
+    events: [announced(path), title("x".repeat(100), 10)],
+    titled: [{ key: `agents/titled:${path}@10`, metadata: { title: "x".repeat(80) } }],
+  },
+  {
+    name: "a person's first line: no title",
+    events: [announced(path), words("Please fix the build", 10)],
+    titled: [],
+  },
+  {
+    name: "a second, newer title of its own: written once more",
+    events: [announced(path), title("Fix the build", 10), title("Fix the docs", 20)],
+    titled: [
+      { key: `agents/titled:${path}@10`, metadata: { title: "Fix the build" } },
+      { key: `agents/titled:${path}@20`, metadata: { title: "Fix the docs" } },
+    ],
+  },
+  {
+    name: "a description, an activity or the same title again: no title",
+    events: [
+      announced(path),
+      title("Fix the build", 10),
+      copy({ description: "CI is red" }, 11),
+      activity(12),
+      title("Fix the build", 13),
+    ],
+    titled: [{ key: `agents/titled:${path}@10`, metadata: { title: "Fix the build" } }],
+  },
+  {
+    // About appends `agent/summary-updated` beside `itx/described`; the catalog's own
+    // `itx/described` never comes back (no copy row takes an `itx/*` event), so it goes round once
+    name: "a title set in About, then the same title of the agent's: written once",
+    events: [
+      announced(path),
+      title("Coding chief of staff", 20),
+      title("Coding chief of staff", 30),
+    ],
+    titled: [{ key: `agents/titled:${path}@20`, metadata: { title: "Coding chief of staff" } }],
+  },
+  {
+    name: "the same, landing in the other order: written once",
+    events: [
+      announced(path),
+      title("Coding chief of staff", 30),
+      title("Coding chief of staff", 20),
+    ],
+    titled: [{ key: `agents/titled:${path}@30`, metadata: { title: "Coding chief of staff" } }],
+  },
+  {
+    name: "a batch delivered again: nothing more",
+    events: [announced(path), title("Fix the build", 10), title("Fix the build", 10)],
+    titled: [{ key: `agents/titled:${path}@10`, metadata: { title: "Fix the build" } }],
+  },
+  {
+    name: "the context's listed metadata: kept, its title replaced, a child's row not read",
+    events: [announced(path), title("Fix the build", 10)],
+    listed: [
+      { path: `${path}/sub`, metadata: { child: true } },
+      { path, metadata: { pinned: true, title: "A person's title" } },
+    ],
+    titled: [
+      { key: `agents/titled:${path}@10`, metadata: { pinned: true, title: "Fix the build" } },
+    ],
+  },
+])("an agent's title in the mind's catalog: $name", async ({ events, listed, titled }) => {
+  const { processor, appended } = catalog(listed);
+  await processAll(processor, events);
+  expect(appended.filter(({ event }) => event.idempotencyKey.startsWith("agents/titled:"))).toEqual(
+    titled.map(({ key, metadata }) => ({
+      path,
+      event: {
+        type: "events.iterate.com/itx/described",
+        idempotencyKey: key,
+        payload: { metadata },
+      },
+    })),
+  );
+});
+
+test("a copy that says another kind starts the row over: the first agent's title, lines and status go, and the new agent's first words title it", () => {
+  const { processor } = catalog();
+  const state = reduceProcessor(processor, [
+    announced(path),
+    copy({ kind: "iterate" }, 3),
+    words("Say the single word MANGO", 5),
+    copy({ status: "idle", activity: "Answering", description: "Fruit" }, 9),
+    // the path started over, and the mind's own agent runs there now
+    copy({ kind: "agent" }, 40),
+    words("Say KIWI", 44),
+    // a copy of the first agent that lands late changes nothing
+    copy({ activity: "an old line" }, 12),
+    words("An older first line", 2),
+  ]);
+  expect(state.agents[path]).toEqual({
+    ...born,
+    kind: "agent",
+    title: "Say KIWI",
+    titleAtOffset: 44,
+    titleFromWords: true,
+    startedOverAtOffset: 40,
+    fieldAtOffset: { kind: 40 },
+    lastActivityAt: at(44),
+  });
+});
+
+test("a copy of a later version of the context starts the row over, also when the kind stays the same", () => {
+  const { processor } = catalog();
+  const state = reduceProcessor(processor, [
+    announced(path),
+    copy({ kind: "agent" }, 3),
+    words("Say the single word MANGO", 5),
+    title("The fruit agent", 8),
+    // `itx.newVersion`: the platform writes the version on every copy from version 2 on
+    ofVersion(copy({ kind: "agent" }, 40), 2),
+    ofVersion(words("Say KIWI", 44), 2),
+    // the same version again starts nothing over
+    ofVersion(copy({ status: "idle" }, 50), 2),
+  ]);
+  expect(state.agents[path]).toEqual({
+    ...born,
+    kind: "agent",
+    status: "idle",
+    title: "Say KIWI",
+    titleAtOffset: 44,
+    titleFromWords: true,
+    startedOverAtOffset: 40,
+    version: 2,
+    versionSeenAt: at(40),
+    fieldAtOffset: { kind: 40, status: 50 },
+    lastActivityAt: at(50),
+  });
+});
+
+test("the same kind again starts nothing over, and neither does a row's first kind", () => {
+  const { processor } = catalog();
+  const state = reduceProcessor(processor, [
+    announced(path),
+    words("Hello", 5),
+    copy({ kind: "agent" }, 6),
+    copy({ kind: "agent" }, 30),
+  ]);
+  expect(state.agents[path]).toMatchObject({ title: "Hello", kind: "agent" });
+  expect(state.agents[path]).not.toHaveProperty("startedOverAtOffset");
+});
+
+test.for<{ name: string; lastEventAt: string; events: Fact[]; titled: unknown[] }>([
+  {
+    // the mind's catalog of contexts is one wake behind: its row is still the first version's
+    name: "a later version, listed as before it: the title alone, as the listed metadata is the earlier version's",
+    lastEventAt: at(30),
+    events: [
+      announced(path),
+      copy({ kind: "agent" }, 3),
+      ofVersion(copy({ kind: "agent" }, 40), 2),
+      ofVersion(title("The new agent", 50), 2),
+    ],
+    titled: [{ metadata: { title: "The new agent" } }],
+  },
+  {
+    // an agent that a person pinned a day after its path started over, and that names itself then
+    name: "a later version, listed since it started: the listed metadata is that version's own, and its pin stays",
+    lastEventAt: at(45),
+    events: [
+      announced(path),
+      copy({ kind: "agent" }, 3),
+      ofVersion(copy({ kind: "agent" }, 40), 2),
+      ofVersion(words("Say KIWI", 44), 2),
+      ofVersion(title("The new agent", 50), 2),
+      ofVersion(title("Its second title", 60), 2),
+    ],
+    titled: [
+      { metadata: { tags: ["pinned-in-dash"], title: "The new agent" } },
+      { metadata: { tags: ["pinned-in-dash"], title: "Its second title" } },
+    ],
+  },
+  {
+    // a take-over in place: the context is the same one, whatever its listed row has seen
+    name: "another kind at the same path: the context's metadata is its own, and its pin stays",
+    lastEventAt: at(30),
+    events: [
+      announced(path),
+      copy({ kind: "iterate" }, 3),
+      copy({ kind: "agent" }, 40),
+      title("The new agent", 50),
+    ],
+    titled: [{ metadata: { tags: ["pinned-in-dash"], title: "The new agent" } }],
+  },
+  {
+    name: "another kind at a path of a later version: the version's border still holds",
+    lastEventAt: at(30),
+    events: [
+      announced(path),
+      ofVersion(copy({ kind: "iterate" }, 40), 2),
+      ofVersion(copy({ kind: "agent" }, 45), 2),
+      ofVersion(title("The new agent", 50), 2),
+    ],
+    titled: [{ metadata: { title: "The new agent" } }],
+  },
+])(
+  "the first title after a path started over keeps the context's other metadata: $name",
+  async ({ lastEventAt, events, titled }) => {
+    const { processor, appended } = catalog([
+      { path, lastEventAt, metadata: { tags: ["pinned-in-dash"], title: "Old" } },
+    ]);
+    await processAll(processor, events);
+    expect(
+      appended
+        .filter(({ event }) => event.idempotencyKey.startsWith("agents/titled:"))
+        .map(({ event }) => event.payload),
+    ).toEqual(titled);
+  },
+);
+
+test("a title a person wrote in About is a name: it replaces the first words, later words leave it, and it goes to the context beside the pin", async () => {
+  // About appends `agent/summary-updated { title }` on the agent's log (packages/ui's
+  // `describeContext`), and the kind's summary row copies it here as any name of the agent's
+  const { processor, appended } = catalog([{ path, metadata: { tags: ["pinned-in-dash"] } }]);
+  const events = [
+    announced(path),
+    words("Please fix the build", 10),
+    title("Engineering manager", 20),
+    words("And the docs", 30),
+  ];
+  await processAll(processor, events);
+  expect(reduceProcessor(processor, events).agents[path]).toEqual({
+    ...born,
+    title: "Engineering manager",
+    titleAtOffset: 20,
+    titleFromWords: undefined,
+    lastActivityAt: at(30),
+  });
+  expect(
+    appended
+      .filter(({ event }) => event.idempotencyKey.startsWith("agents/titled:"))
+      .map(({ event }) => event.payload),
+  ).toEqual([{ metadata: { tags: ["pinned-in-dash"], title: "Engineering manager" } }]);
+});
+
+test("the listed row is read once for each change of an agent's own title, and never for the same title, a description or an activity", async () => {
+  const { processor, reads } = catalog();
+  await processAll(processor, [
+    announced(path),
+    title("Fix the build", 10),
+    title("Fix the build", 11),
+    copy({ description: "CI is red" }, 12),
+    activity(13),
+    title("Fix the docs", 20),
+  ]);
+  expect(reads).toEqual(["/", "/"]);
+});
+
+test("a context whose metadata would be too long with a title keeps it: no title is written", async () => {
+  const reported = vi.spyOn(console, "error").mockImplementation(() => {});
+  const { processor, appended } = catalog([{ path, metadata: { notes: "x".repeat(3_990) } }]);
+  await processAll(processor, [announced(path), title("Fix the build", 10)]);
+  expect(appended.filter(({ event }) => event.idempotencyKey.startsWith("agents/titled:"))).toEqual(
+    [],
+  );
+  reported.mockRestore();
+});
+
+test("a mind that refuses the read writes no title, and says so once for each agent", async () => {
+  const reported = vi.spyOn(console, "error").mockImplementation(() => {});
+  const { processor, appended } = catalog([], true);
+  await processAll(processor, [
+    announced(path),
+    title("Fix the build", 10),
+    title("Fix the docs", 20),
+  ]);
+  expect(appended.filter(({ event }) => event.idempotencyKey.startsWith("agents/titled:"))).toEqual(
+    [],
+  );
+  expect(
+    reported.mock.calls.filter((call) => JSON.stringify(call).includes("agents.catalog.titled")),
+  ).toHaveLength(1);
+  reported.mockRestore();
+});
+
+/** The catalog's processor, with a root that records each append it is asked for and lists
+ *  `listed` as the mind's catalog of contexts. */
+function catalog(
+  listed: { path: string; lastEventAt?: string; metadata?: Record<string, unknown> }[] = [],
+  refuse = false,
+) {
+  const appended: { path: string; event: { idempotencyKey: string; payload: unknown } }[] = [];
+  const reads: string[] = [];
+  const itx = {
+    cd: (at: string) => ({
+      append: async (event: { idempotencyKey: string; payload: unknown }) => {
+        appended.push({ path: at, event });
+        return [];
+      },
+      contexts: {
+        list: async () => {
+          reads.push(at);
+          if (refuse) throw new Error("refused");
+          return at === "/" ? listed : [];
+        },
+      },
+    }),
+    [Symbol.dispose]() {},
+  };
+  // The processor reaches only `cd(path).append` and `cd("/").contexts.list`: the fake has nothing else.
+  const processor = new AgentCatalogProcessor(() => itx as never);
+  return { processor, appended, reads };
+}
+
+/** Each of `events` handed to `processEvent` in turn, its work done before the next. */
+async function processAll(processor: AgentCatalogProcessor, events: Fact[]) {
+  for (const [index, fact] of events.entries()) {
+    const blockers: (() => Promise<unknown>)[] = [];
+    processor.processEvent({
+      event: eventAt(index + 1, fact),
+      previousState: reduceProcessor(processor, events.slice(0, index)),
+      state: reduceProcessor(processor, events.slice(0, index + 1)),
+      append: async () => [],
+      blockProcessorWhile: (work) => blockers.push(work),
+      runInBackground: () => {},
+      delivery: { caughtUp: false },
+    });
+    for (const work of blockers) await work();
+  }
+}
+
+/** `fact` as the engine hands it over, at `offset` on `/agents`. */
+function eventAt(offset: number, fact: Fact) {
+  return {
+    ...committedEvent(offset, fact.type, fact.payload),
+    path: "/agents",
+    source: fact.source,
+  } as Parameters<AgentCatalogProcessor["processEvent"]>[0]["event"] & StreamEvent;
+}
+
+/** A row whose announcement was the `n`th event (the harness stamps each a second apart). */
+function bornAt(n: number) {
+  return { createdAt: new Date(n * 1000).toISOString() };
+}
+
+/** When the original event at `offset` happened on the agent's log. */
+function at(offset: number) {
+  return new Date(1_800_000_000_000 + offset).toISOString();
+}
+
+/** `fact` as a copy of version `version` of its context: the platform writes the version on every
+ *  copy from version 2 on (`itx.newVersion`). */
+function ofVersion(fact: ReturnType<typeof copy>, version: number) {
+  return {
+    ...fact,
+    source: { ...fact.source, copiedFrom: { ...fact.source.copiedFrom, version } },
+  };
+}
+
+/** A copy of the event at `offset` on `of`'s log, with `copiedFrom` set as the platform sets it. */
+function copy(payload: Record<string, unknown>, offset: number, of = path) {
+  return {
+    type: "events.iterate.com/agent/listing-updated",
+    payload,
+    source: {
+      origin: of,
+      copiedFrom: {
+        path: of,
+        offset,
+        createdAt: at(offset),
+        type: "test/any",
+        subscription: "row",
+      },
+    },
+  };
+}
+function title(title: string, offset: number) {
+  return copy({ title }, offset);
+}
+function words(title: string, offset: number) {
+  return copy({ title, fromWords: true }, offset);
+}
+function activity(offset: number) {
+  return copy({}, offset);
+}
+
+/** `childPath` announcing itself to `/agents`, as every context does when it first wakes. */
+function announced(childPath: string) {
+  return {
+    type: "events.iterate.com/itx/child-created",
+    payload: { childPath },
+    source: { origin: childPath },
+  };
+}
+
+/** `of`'s death certificate, stamped `origin`. */
+function certificate(kind: "deleted", of: string, origin = of) {
+  return { type: `events.iterate.com/agent/${kind}`, payload: { path: of }, source: { origin } };
+}
A core/lib/src/agents/catalog.ts
@@ -0,0 +1,455 @@
+import { z } from "zod";
+import {
+  defineProcessorContract,
+  StreamProcessor,
+  type ConsumedEvent,
+  type ProcessEventArgs,
+  type ReduceArgs,
+  type ProcessorState,
+} from "../stream/processor.ts";
+import type { IterateContextApi } from "../api.ts";
+import { errorCode, reportIssue } from "../lib.ts";
+import { StreamProcessorDurableObject } from "../sdk/index.ts";
+import type { AgentHandleApi, AgentsRootApi } from "./api.ts";
+import { AgentEventCatalog } from "./contract.ts";
+import { AgentCollectionRpcTarget, type OwnAgent } from "./collection.ts";
+import { AGENTS_PATH } from "./install.ts";
+
+/** The core's announcement that a context exists below this one
+ *  (core/itx/src/iterate-context-durable-object.ts `announceToAncestors`): what makes a row. The
+ *  core owns it, so the catalog names it here, as `RunEventCatalog` names the run events. */
+const ChildCreatedEventCatalog = {
+  events: {
+    "events.iterate.com/itx/child-created": {
+      description:
+        "A context under this one exists: every context appends it to each ancestor up to its root when it first wakes, keyed by the child's path.",
+      payloadSchema: z.object({ childPath: z.string().min(1) }),
+    },
+  },
+};
+
+/** What an agent is doing, the same words for every kind of agent. */
+const AgentStatus = z.enum(["working", "idle", "waiting", "ended"]);
+
+/** The fields a copy sets one by one, each the newest the agent's log has said (`fieldAtOffset`).
+ *  `title` is not one of them: it has rules of its own. */
+const COPIED_FIELDS = ["kind", "host", "status", "activity", "description"] as const;
+
+const AgentCatalogContract = defineProcessorContract({
+  slug: "agents",
+  version: "4",
+  description:
+    "The agents of this mind: every context under /agents, with what a list shows about each.",
+  stateSchema: z.object({
+    /** Every live agent by path: every context under `/agents`, at any depth, from its own
+     *  `itx/child-created` (an agent never posts its birth here). Everything but `createdAt` and
+     *  `parent` comes from copies of the agent's own events, by rows that each kind of agent
+     *  configures on its own context (core/configs/default/agent-start.ts `CATALOG_ROWS` are those
+     *  of the mind's own agent). `parent` is the nearest
+     *  ancestor that is a row too. `title` is the name the agent gave itself or, failing that, the
+     *  first line a person sent it, and then `titleFromWords` is true. Copies can land in any order,
+     *  so `titleAtOffset` and `fieldAtOffset` record which event on the agent's log each field came
+     *  from. */
+    agents: z
+      .record(
+        z.string(),
+        z.object({
+          createdAt: z.string(),
+          parent: z.string().optional(),
+          /** What runs the agent: "agent" (the mind's own), "claude", "codex", "opencode", … */
+          kind: z.string().optional(),
+          /** The machine or sandbox it runs on, for an agent that runs on one. */
+          host: z.string().optional(),
+          status: AgentStatus.optional(),
+          /** One line: what it is doing now. */
+          activity: z.string().optional(),
+          /** A few sentences: its purpose or conclusions. */
+          description: z.string().optional(),
+          title: z.string().optional(),
+          titleAtOffset: z.number().optional(),
+          titleFromWords: z.boolean().optional(),
+          lastActivityAt: z.string().optional(),
+          fieldAtOffset: z.record(z.string(), z.number()).optional(),
+          /** The offset, on the agent's log, of the copy at which the row started over: another
+           *  agent runs at the path from there on (`reduce`). */
+          startedOverAtOffset: z.number().optional(),
+          /** The version of the agent's context that the row is of (`itx.newVersion`): a copy
+           *  says it from version 2 on (`source.copiedFrom.version`). None: the first. */
+          version: z.number().optional(),
+          /** When the agent's log said the event whose copy brought that later version here. What
+           *  the mind's catalog of contexts lists from before then can be the earlier version's
+           *  (`processEvent`). A path that started over in place (another kind) has none: its
+           *  context is the same one, and its metadata stays its own. */
+          versionSeenAt: z.string().optional(),
+        }),
+      )
+      .default({}),
+    /** Every agent that died, by path: its death certificate. Terminal — a deleted agent is not
+     *  re-creatable — so a verb on one answers from this row and its context is not called
+     *  (collection.ts). */
+    deleted: z.record(z.string(), z.object({ deletedAt: z.string() })).default({}),
+  }),
+  events: {
+    "events.iterate.com/agent/listing-updated": {
+      description:
+        "Something a list shows about an agent changed. It's a copy on /agents of one of the agent's own events, and `source.copiedFrom` says which one; that event's `createdAt` is when the agent was last active. `title` is the agent's title. `fromWords` means the title is only the first line a person sent, and any name the agent gives itself replaces it. `kind` is what runs the agent (`iterate`, `claude`, …), `host` the machine it runs on, `status` what it is doing (`working`, `idle`, `waiting` on someone, `ended`), `activity` one line on what it is doing now and `description` a few sentences on its purpose or conclusions. An empty `activity` or `description` clears it.",
+      payloadSchema: z.object({
+        title: z.string().optional(),
+        fromWords: z.literal(true).optional(),
+        kind: z.string().min(1).max(40).optional(),
+        host: z.string().min(1).max(120).optional(),
+        status: AgentStatus.optional(),
+        activity: z.string().max(300).optional(),
+        description: z.string().max(1_000).optional(),
+      }),
+    },
+  },
+  processorDeps: [AgentEventCatalog, ChildCreatedEventCatalog],
+  consumes: [
+    "events.iterate.com/itx/child-created",
+    "events.iterate.com/agent/deleted",
+    "events.iterate.com/agent/listing-updated",
+  ],
+  emits: [],
+});
+export type AgentCatalogState = ProcessorState<typeof AgentCatalogContract>;
+export class AgentCatalogProcessor extends StreamProcessor<
+  AgentCatalogState,
+  ConsumedEvent<typeof AgentCatalogContract>
+> {
+  readonly contract = AgentCatalogContract;
+  readonly #getItx: () => Pick<IterateContextApi, "cd"> & Disposable;
+  /** The agents whose title could not be written, each reported once. */
+  readonly #titleFaults = new Set<string>();
+
+  /** `getItx`: the scope of `/agents`, which reaches each agent's own log (`processEvent`). */
+  constructor(getItx: () => Pick<IterateContextApi, "cd"> & Disposable) {
+    super();
+    this.#getItx = getItx;
+  }
+  /** Folds the contexts under `/agents` (each announces itself, `itx/child-created`) and the
+   *  `agent/deleted` certificates posted here into the live and the dead agents. A birth counts
+   *  once, and a death is terminal.
+   *
+   *  An `agent/listing-updated` copy updates a live agent's row, and makes it when the copy lands
+   *  first. Only the platform can set `source.copiedFrom`, so an event without it is ignored:
+   *  anyone can append to `/agents`, and a title is shown to people. Copies can land in any order, so an older copy never undoes a newer
+   *  one, field by field. */
+  reduce({
+    state,
+    event,
+  }: ReduceArgs<AgentCatalogState, ConsumedEvent<typeof AgentCatalogContract>>) {
+    if (event.type === "events.iterate.com/itx/child-created") {
+      const path = event.payload.childPath;
+      if (!path.startsWith(`${AGENTS_PATH}/`)) return; // the announcement is anyone's to append
+      if (state.agents[path] || state.deleted[path]) return; // born once; dead is terminal
+      return { ...state, agents: withRow(state.agents, path, event.createdAt) };
+    }
+    if (event.type === "events.iterate.com/agent/deleted") {
+      const { path } = event.payload;
+      if (state.deleted[path]) return;
+      return {
+        ...state,
+        agents: withoutRow(state.agents, path),
+        deleted: { ...state.deleted, [path]: { deletedAt: event.createdAt } },
+      };
+    }
+    const from = event.source.copiedFrom;
+    if (!from?.path.startsWith(`${AGENTS_PATH}/`) || state.deleted[from.path]) return;
+    // A copy is proof its context exists (only the platform sets `copiedFrom`), and it can land
+    // before the context's own announcement: the row is made here then, and the announcement
+    // finds it born.
+    const agents = state.agents[from.path]
+      ? state.agents
+      : withRow(state.agents, from.path, from.createdAt);
+    const listed = agents[from.path]!;
+    // A PATH THAT STARTED OVER IS ANOTHER AGENT AT THE SAME PATH. What the list said of the first
+    // agent goes with it: its title, its lines, its status. Two signs say that a path started over:
+    //   - the copy is of a LATER VERSION of the context than the row (`itx.newVersion`: the
+    //     platform writes the version on every copy from version 2 on);
+    //   - the copy says ANOTHER KIND than the row has (a take-over: the mind's own agent for the
+    //     platform's, collection.ts), for a copy that carries no version.
+    // That copy is the border. A copy from before the border that lands after it is the first
+    // agent's, and changes nothing.
+    if (from.offset < (listed.startedOverAtOffset || 0))
+      return agents === state.agents ? undefined : { ...state, agents };
+    const { kind } = event.payload;
+    const version = from.version || 1;
+    const startsOver =
+      version > (listed.version || 1) ||
+      (!!kind &&
+        !!listed.kind &&
+        kind !== listed.kind &&
+        from.offset > (listed.fieldAtOffset?.kind || 0));
+    const row: AgentCatalogState["agents"][string] = startsOver
+      ? {
+          createdAt: listed.createdAt,
+          // oxlint-disable-next-line iterate/simple-truthiness-check -- a row with no parent has no such key, as `withRow` makes it
+          ...(listed.parent && { parent: listed.parent }),
+          lastActivityAt: listed.lastActivityAt,
+          startedOverAtOffset: from.offset,
+          ...(version > 1 && { version }),
+          versionSeenAt: version > (listed.version || 1) ? from.createdAt : listed.versionSeenAt,
+        }
+      : listed;
+    // Copies can land in any order. So each field below is blanked when what the row already has
+    // should win, and the row is left alone when all end up blank.
+    const { fromWords } = event.payload;
+    let title = event.payload.title;
+    if (row.title) {
+      const titleOffset = row.titleAtOffset || 0;
+      // A name the agent gave itself beats a person's words.
+      if (fromWords && !row.titleFromWords) title = "";
+      // Earlier words beat later ones. A copy of the same words again (a kind's row changed how it
+      // makes a title) replaces them.
+      if (fromWords && row.titleFromWords && from.offset > titleOffset) title = "";
+      // A newer name beats an older one.
+      if (!fromWords && !row.titleFromWords && from.offset <= titleOffset) title = "";
+    }
+    // Every other field: the newest event the agent's log has said it in wins.
+    const fields: Partial<AgentCatalogState["agents"][string]> = {};
+    const fieldAtOffset = { ...row.fieldAtOffset };
+    for (const field of COPIED_FIELDS) {
+      const value = event.payload[field];
+      // oxlint-disable-next-line iterate/simple-truthiness-check -- an empty activity or description clears it; absent keeps it
+      if (value === undefined || from.offset <= (fieldAtOffset[field] || 0)) continue;
+      Object.assign(fields, { [field]: value });
+      fieldAtOffset[field] = from.offset;
+    }
+    // Every copy means the agent was active when the original happened, unless the row already
+    // has later activity.
+    let lastActivityAt = from.createdAt;
+    if (lastActivityAt <= (row.lastActivityAt || "")) lastActivityAt = "";
+    if (
+      !title &&
+      !lastActivityAt &&
+      Object.keys(fields).length === 0 &&
+      agents === state.agents &&
+      !startsOver
+    )
+      return;
+    return {
+      ...state,
+      agents: {
+        ...agents,
+        [from.path]: {
+          ...row,
+          ...fields,
+          ...(Object.keys(fields).length > 0 && { fieldAtOffset }),
+          ...(title && { title, titleAtOffset: from.offset, titleFromWords: fromWords }),
+          lastActivityAt: lastActivityAt || row.lastActivityAt,
+        },
+      },
+    };
+  }
+
+  /** EVERY AGENT SAYS WHAT IT IS FOR in the mind's catalog of contexts (`itx.contexts.list`): when
+   *  a copy changes an agent's line (`agentDescription`: its description, or with none its title or
+   *  the first words a person sent it), the line goes onto the agent's own log as
+   *  `events.iterate.com/itx/described`. Every kind of agent gets it, the mind's own or a bridge's, and
+   *  an activity or a status alone appends nothing. A copy row cannot do this: no copy is an
+   *  `itx/*` event. The key is the copied event's, so a batch delivered again appends nothing. An
+   *  agent whose line has not changed since this was deployed gets it at its next change. The
+   *  newest description stands, so a person's own stands until the agent's line changes again. A
+   *  failed append is reported, and waits for the agent's next change: it never holds the catalog.
+   *
+   *  AND ITS TITLE, as `metadata.title` of an `itx/described` of its own (`agentTitle`), when a
+   *  copy changes the title the agent gave itself: the first words a person sent are no title. The
+   *  append carries `metadata` only, so the description stays the purpose alone. `metadata` is one
+   *  record, replaced whole, so the title is merged into the record the mind's catalog lists for
+   *  the agent's context (`listedContext`): a pin and every other key stay. That row can be one
+   *  wake behind the log, so a key a person wrote in the same wake can be lost, and after
+   *  `itx.newVersion` it can still be the earlier version's, which is not merged
+   *  (`ofEarlierVersion`). The newest stands: a title a person wrote in About
+   *  stands until the agent's own title changes again, and then the agent's lands once. The same
+   *  rules as for the description hold: keyed by the copied event, reported when it fails, never
+   *  holding the catalog. */
+  override processEvent({
+    event,
+    state,
+    previousState,
+    blockProcessorWhile,
+  }: ProcessEventArgs<AgentCatalogState, ConsumedEvent<typeof AgentCatalogContract>>): undefined {
+    if (event?.type !== "events.iterate.com/agent/listing-updated") return;
+    const from = event.source.copiedFrom;
+    if (!from) return;
+    const description = agentDescription(state.agents[from.path]);
+    if (description && description !== agentDescription(previousState.agents[from.path]))
+      blockProcessorWhile(async () => {
+        using itx = this.#getItx();
+        await itx
+          .cd(from.path)
+          .append({
+            type: "events.iterate.com/itx/described",
+            idempotencyKey: describedKey(from.path, from.offset, description),
+            payload: { description },
+          })
+          .catch((error: unknown) => {
+            if (errorCode(error) === "IDEMPOTENCY_CONFLICT") return;
+            reportIssue("agents.catalog.described", error, { path: from.path });
+          });
+      });
+    const title = agentTitle(state.agents[from.path]);
+    if (title && title !== agentTitle(previousState.agents[from.path]))
+      blockProcessorWhile(async () => {
+        using itx = this.#getItx();
+        try {
+          const listed = await listedContext(itx, from.path);
+          const metadata = {
+            ...(ofEarlierVersion(listed, state.agents[from.path]) ? {} : listed?.metadata),
+            title,
+          };
+          // The mind's catalog keeps a record only while it prints this short
+          // (core/itx/src/context/context-summary.ts): a longer one is dropped whole, so the
+          // title is not written over metadata that would be lost with it.
+          if (JSON.stringify(metadata).length > 4_000)
+            throw new Error("The context's metadata is too long to take a title.");
+          await itx.cd(from.path).append({
+            type: "events.iterate.com/itx/described",
+            idempotencyKey: `agents/titled:${from.path}@${String(from.offset)}`,
+            payload: { metadata },
+          });
+        } catch (error) {
+          if (errorCode(error) === "IDEMPOTENCY_CONFLICT") return;
+          // once for each context, while this instance lives: a mind that refuses the read or
+          // the write says so, and its issue log is not filled by every agent's every title
+          if (this.#titleFaults.has(from.path)) return;
+          this.#titleFaults.add(from.path);
+          reportIssue("agents.catalog.titled", error, { path: from.path });
+        }
+      });
+  }
+}
+
+/** The key of the `itx/described` that carries the line of the copy at `offset`: the copied event
+ *  and the line's text. The same copy delivered again appends nothing, and the same event copied
+ *  again with another line (a kind's row changed how it makes a title) appends that line once. */
+export function describedKey(path: string, offset: number, text: string): string {
+  let hash = 0x811c9dc5;
+  for (let index = 0; index < text.length; index++)
+    hash = Math.imul(hash ^ text.charCodeAt(index), 0x01000193);
+  return `agents/described:${path}@${String(offset)}:${(hash >>> 0).toString(16).padStart(8, "0")}`;
+}
+
+/** An agent's line in the mind's catalog of contexts: its description, which is its purpose, at
+ *  most 2,000 characters (the schema of `itx/described`). An agent with no description has its
+ *  title there, which may be only the first line a person sent (`titleFromWords`): it is the best
+ *  line there is. A title is never added to a description: a context's purpose is not its name. */
+function agentDescription(
+  row: Pick<AgentCatalogState["agents"][string], "title" | "description"> | undefined,
+): string | undefined {
+  return (row?.description || row?.title)?.slice(0, 2_000);
+}
+
+/** An agent's title in the mind's catalog of contexts: only a title the agent gave itself, as the
+ *  first words a person sent are no title, at most 80 characters (what a list shows). */
+function agentTitle(
+  row: Pick<AgentCatalogState["agents"][string], "title" | "titleFromWords"> | undefined,
+): string | undefined {
+  if (!row?.title || row.titleFromWords) return undefined;
+  return row.title.slice(0, 80);
+}
+
+/** The row the mind's catalog of contexts lists for `path`, read from the first 50 rows under it,
+ *  the most recently active first: one bounded read. A context with no row there has none. */
+async function listedContext(itx: Pick<IterateContextApi, "cd">, path: string) {
+  const listed = await itx.cd("/").contexts.list({ under: path, limit: 50 });
+  return listed.find((context) => context.path === path);
+}
+
+/** Whether what the mind's catalog of contexts lists for an agent can be of an earlier version of
+ *  its context (`itx.newVersion`): the listed row is of the context's summary, which starts empty
+ *  with each version (core/itx's context-summary.ts), and it can be one wake behind. So it is the
+ *  earlier version's only while its newest event is from before the first event this catalog saw
+ *  of the row's version. From then on the listed metadata is that version's own, whenever the
+ *  agent names itself: a pin a person set stays. */
+function ofEarlierVersion(
+  listed: { lastEventAt?: string } | undefined,
+  row: Pick<AgentCatalogState["agents"][string], "versionSeenAt"> | undefined,
+): boolean {
+  return !!row?.versionSeenAt && (listed?.lastEventAt || "") < row.versionSeenAt;
+}
+
+/** The rows with `path` added: its parent the nearest ancestor that is a row, and every row below it
+ *  whose parent is further up (its announcement landed first) now its child. */
+function withRow(agents: AgentCatalogState["agents"], path: string, createdAt: string) {
+  const parent = ancestorsOf(path).find((ancestor) => agents[ancestor]);
+  const next: AgentCatalogState["agents"] = {};
+  for (const [other, row] of Object.entries(agents))
+    next[other] =
+      other.startsWith(`${path}/`) && (row.parent || "").length < path.length
+        ? { ...row, parent: path }
+        : row;
+  next[path] = { createdAt, parent };
+  return next;
+}
+
+/** The rows without `path`: each of its children now the child of its parent. */
+function withoutRow(agents: AgentCatalogState["agents"], path: string) {
+  const { [path]: gone, ...rest } = agents;
+  if (!gone) return rest;
+  const next: AgentCatalogState["agents"] = {};
+  for (const [other, row] of Object.entries(rest)) {
+    if (row.parent !== path) next[other] = row;
+    else {
+      const { parent: _parent, ...orphan } = row;
+      next[other] = gone.parent ? { ...orphan, parent: gone.parent } : orphan;
+    }
+  }
+  return next;
+}
+
+/** `path`'s ancestors below `/agents`, nearest first: `/agents/a/b/c` → `/agents/a/b`, `/agents/a`. */
+function ancestorsOf(path: string): string[] {
+  const ancestors: string[] = [];
+  for (let at = path.lastIndexOf("/"); at > AGENTS_PATH.length; at = path.lastIndexOf("/", at - 1))
+    ancestors.push(path.slice(0, at));
+  return ancestors;
+}
+
+/** The agents app's collection facet — what the `itx.agents` rule names (install.ts): the
+ *  published `AgentsRootApi` (api.ts) at the mind's root, `AgentsApi` plus `at(base)`, the
+ *  collection an agent's own `itx.agents` rule reaches. */
+export class AgentCollectionDurableObject
+  extends StreamProcessorDurableObject<AgentCatalogState>
+  implements AgentsRootApi
+{
+  /** The processor's reads, and `itx.agents`: the collection's verbs and `at(base)` (collection.ts). */
+  static override publicMethods = [...super.publicMethods, "list", "get", "create", "delete", "at"];
+  /** THE MIND'S OWN AGENT, whose code is in the mind's config repo: the kind its start writes on
+   *  `/agents`, and the facts that make a context run it (collection.ts `OwnAgent`). A config sets
+   *  it beside the export, and `create` appends those facts. None: `create` refuses, because the
+   *  platform has no agent of its own to start. */
+  static agent: OwnAgent | undefined;
+
+  processor = new AgentCatalogProcessor(() => this.getItx());
+  at(base: string) {
+    return new AgentCollectionRpcTarget(
+      () => this.getItx(),
+      // THROUGH THE LOG'S HEAD, not the last pushed batch (`snapshot()` alone answers from what the
+      // delivery has pushed so far): a death is on `/agents` before `delete()` returns, so a verb
+      // on the dead agent right after must see it, or it would start the agent again
+      // (collection.ts).
+      async () => {
+        await this.catchUpFromLog();
+        return await this.snapshot();
+      },
+      base,
+      (this.constructor as typeof AgentCollectionDurableObject).agent,
+    );
+  }
+  #collection = this.at("/");
+  list() {
+    return this.#collection.list();
+  }
+  // oxlint-disable-next-line iterate/mechanical-class-impl -- the published declarations name the handle by its interface: the inferred class is collection.ts's own
+  get(path: string): AgentHandleApi {
+    return this.#collection.get(path);
+  }
+  create(path: string) {
+    return this.#collection.create(path);
+  }
+  delete(path: string) {
+    return this.#collection.delete(path);
+  }
+}
A core/lib/src/agents/collection.test.ts
@@ -0,0 +1,237 @@
+// collection.test.ts — `itx.agents` (collection.ts) over a context that holds a log and a list of
+// processor rows: what `create`, `message` and `delete` append and disable for the mind's own
+// agent, for a context that an agent of the platform ran (a take-over), for another kind of agent,
+// and in a mind whose config names no agent.
+import { expect, test } from "vitest";
+import type { StreamEvent, StreamEventInput } from "../stream/processor.ts";
+import { memoryStream } from "../stream/test-support.ts";
+import { AgentCollectionRpcTarget, type OwnAgent } from "./collection.ts";
+
+const PATH = "/agents/a";
+
+test("create starts the mind's own agent with one append, and a second create writes nothing", async () => {
+  // listed with no kind: a context that announced itself and runs no agent yet
+  const { agents, events } = ownCollection(null);
+  expect(await agents.create(PATH)).toEqual({ path: PATH });
+  // the start facts and the collection's own row, and nothing else: nothing is asked for and
+  // nothing is waited for
+  expect(typesOf(events)).toEqual([
+    "itx/rewrite-rule-configured",
+    "agent/configured",
+    "itx/subscription-configured",
+    "itx/subscription-configured",
+    "itx/rewrite-rule-configured",
+  ]);
+  // the birth links the agent's `itx` to its creator, and the collection's own row follows
+  expect(events[0]).toMatchObject({ payload: { match: "itx", target: 'itx.cd("/")' } });
+  expect(events.at(-1)).toMatchObject({
+    payload: { match: "itx.agents", target: `itx.cd('/').agents.at("${PATH}")` },
+  });
+  await agents.create(PATH);
+  expect(events).toHaveLength(5);
+});
+
+test.for(["iterate", "agent"])(
+  "create on a context where a %s agent runs writes no parent link: the link of its birth stands",
+  async (kind) => {
+    const { agents, events } = ownCollection(kind);
+    await agents.create(PATH);
+    expect(typesOf(events)).toContain("agent/configured");
+    expect(events.map((event) => (event.payload as { match?: string }).match)).not.toContain("itx");
+  },
+);
+
+test("create refuses a context where another kind of agent runs, and a deleted agent", async () => {
+  const claude = ownCollection("claude");
+  await expect(claude.agents.create(PATH)).rejects.toThrow(
+    "an agent of the kind claude runs there",
+  );
+  const dead = ownCollection("agent", { deleted: true });
+  await expect(dead.agents.create(PATH)).rejects.toThrow("deleted");
+  expect([claude.events, dead.events]).toEqual([[], []]);
+});
+
+test.for(["iterate", "agent"])(
+  "a message to a %s agent lands after the start facts, in one append",
+  async (kind) => {
+    const { agents, events } = ownCollection(kind);
+    const sent = await agents.get(PATH).message("hello");
+    expect(sent).toMatchObject({
+      type: "events.iterate.com/agent/message-received",
+      payload: { message: "hello" },
+    });
+    // a take-over first takes the former agent's four copy rows off
+    const off = events.filter((event) => (event.payload as { target?: unknown }).target === null);
+    expect(off.map((event) => (event.payload as { name: string }).name)).toEqual(
+      kind === "iterate"
+        ? ["catalog-kind", "catalog-summary", "catalog-first-words", "catalog-status"]
+        : [],
+    );
+    expect(typesOf(events).slice(off.length)).toEqual([
+      "agent/configured",
+      "itx/subscription-configured",
+      "itx/subscription-configured",
+      "itx/rewrite-rule-configured",
+      "agent/message-received",
+    ]);
+  },
+);
+
+test.for(["claude", null])(
+  "a message to an agent of the kind %s is the words alone",
+  async (kind) => {
+    const { agents, events } = ownCollection(kind);
+    await agents.get(PATH).message("hello");
+    expect(typesOf(events)).toEqual(["agent/message-received"]);
+  },
+);
+
+test("delete certifies the death, then disables every row that the start enables and no other", async () => {
+  const first = ownCollection("agent");
+  expect(await first.agents.delete(PATH)).toEqual({ path: PATH });
+  // a second delete, after the catalog folded the death, certifies nothing again
+  const again = ownCollection("agent", { deleted: true });
+  await again.agents.delete(PATH);
+  expect([first, again].map(({ deaths, disabled }) => ({ deaths, disabled }))).toEqual([
+    {
+      deaths: [{ type: "events.iterate.com/agent/deleted", payload: { path: PATH } }],
+      disabled: ["agent", "llm-api-openai-responses"],
+    },
+    { deaths: [], disabled: ["agent", "llm-api-openai-responses"] },
+  ]);
+});
+
+test("delete of another kind's agent certifies its death and disables nothing", async () => {
+  const { agents, disabled, deaths } = ownCollection("claude");
+  await agents.delete(PATH);
+  expect({ deaths: deaths.length, disabled }).toEqual({ deaths: 1, disabled: [] });
+});
+
+test("a mind whose config names no agent: create refuses, a message is the words alone, and delete certifies the death", async () => {
+  const { agents, events, disabled, deaths } = ownCollection("claude", { own: null });
+  await expect(agents.create(PATH)).rejects.toThrow("names no agent to start");
+  await agents.get(PATH).message("hello");
+  await agents.delete(PATH);
+  expect({ types: typesOf(events), deaths: deaths.length, disabled }).toEqual({
+    types: ["agent/message-received"],
+    deaths: 1,
+    disabled: [],
+  });
+});
+
+test("an agent cannot create its own ancestor, and the root is no agent", async () => {
+  const { events } = ownCollection(null);
+  const child = new AgentCollectionRpcTarget(
+    () => ({ cd: () => ({}), [Symbol.dispose]() {} }) as never,
+    async () => ({ offset: 0, state: { agents: {}, deleted: {} } }) as never,
+    `${PATH}/child`,
+    OWN,
+  );
+  await expect(child.create(PATH)).rejects.toThrow("cannot create its own ancestor");
+  await expect(child.create("/")).rejects.toThrow("needs its own context path");
+  expect(events).toEqual([]);
+});
+
+test("list says whether a row's title is a name or only the first words a person sent", async () => {
+  const createdAt = "2026-11-24T00:00:00.000Z";
+  const agents = new AgentCollectionRpcTarget(
+    () => ({ cd: () => ({}), [Symbol.dispose]() {} }) as never,
+    async () =>
+      ({
+        offset: 0,
+        state: {
+          agents: {
+            "/agents/named": { createdAt, title: "Engineering manager" },
+            "/agents/words": { createdAt, title: "Please fix the build", titleFromWords: true },
+            "/agents/silent": { createdAt },
+          },
+          deleted: {},
+        },
+      }) as never,
+    "/",
+    OWN,
+  );
+  expect(
+    (await agents.list()).map(({ path, title, titleFromWords }) => [path, title, titleFromWords]),
+  ).toEqual([
+    ["/agents/named", "Engineering manager", false],
+    ["/agents/words", "Please fix the build", true],
+    ["/agents/silent", null, false],
+  ]);
+});
+
+const typesOf = (events: StreamEvent[]) =>
+  events.map((event) => event.type.replace("events.iterate.com/", ""));
+
+/** A mind's own agent, as a config's agents.ts hands it to the collection. */
+const OWN: OwnAgent = {
+  kind: "agent",
+  startEvents: (path: string, { parent }: { parent?: string }) => [
+    ...(parent
+      ? [
+          {
+            type: "events.iterate.com/itx/rewrite-rule-configured",
+            idempotencyKey: `agent-parent:${path}`,
+            payload: { match: "itx", target: `itx.cd(${JSON.stringify(parent)})` },
+          },
+        ]
+      : []),
+    {
+      type: "events.iterate.com/agent/configured",
+      idempotencyKey: `agent-configured:${path}`,
+      payload: { kind: "agent", config: {} },
+    },
+    ...["agent", "llm-api-openai-responses"].map((name) => ({
+      type: "events.iterate.com/itx/subscription-configured",
+      idempotencyKey: `agent-facet:${name}:${path}`,
+      payload: { name, target: ["itx", "facets", ["get", name, {}], "processEventBatch"] },
+    })),
+  ],
+};
+
+/** A context that holds a log and a list of processor rows, and a collection over it whose
+ *  catalog says `kind` of the agent at PATH (null: listed, and it never said what it is). */
+function ownCollection(
+  kind: string | null,
+  { deleted = false, own = OWN }: { deleted?: boolean; own?: OwnAgent | null } = {},
+) {
+  const { stream, events } = memoryStream(PATH);
+  const rows = new Set(["agent", "llm-api-openai-responses", "llm-api-of-another-day", "call"]);
+  const disabled: string[] = [];
+  const deaths: StreamEventInput[] = [];
+  const context = {
+    async append(...inputs: StreamEventInput[]) {
+      return stream.append(...inputs) as StreamEvent[];
+    },
+    processors: {
+      async list() {
+        return [...rows].map((name) => ({ name }));
+      },
+      async disable(name: string) {
+        rows.delete(name);
+        disabled.push(name);
+      },
+    },
+  };
+  const agents = new AgentCollectionRpcTarget(
+    () =>
+      ({
+        cd: (path: string) =>
+          path === "/agents"
+            ? { append: async (...inputs: StreamEventInput[]) => void deaths.push(...inputs) }
+            : context,
+        [Symbol.dispose]() {},
+      }) as never,
+    async () =>
+      ({
+        offset: 0,
+        state: {
+          agents: { [PATH]: { createdAt: "2026-11-24T00:00:00.000Z", kind } },
+          deleted: deleted ? { [PATH]: {} } : {},
+        },
+      }) as never,
+    "/",
+    own || undefined,
+  );
+  return { agents, events, disabled, deaths };
+}
A core/lib/src/agents/collection.ts
@@ -0,0 +1,357 @@
+// collection.ts — `itx.agents` over one base (api.ts `AgentsApi`): `list`, `create`, `delete`, and
+// `get(path)` with `message` and `recent`.
+//
+// AN AGENT IS ANY CONTEXT UNDER `/agents` (catalog.ts), AND THE PLATFORM RUNS NONE OF THEM.
+// - THE MIND'S OWN AGENT is code in the mind's config repo. The config hands this collection the
+//   facts that start it (`OwnAgent`, catalog.ts `AgentCollectionDurableObject.agent`). `create`
+//   appends them to the agent's context, and the facets that they enable are the agent.
+// - ANY OTHER KIND (a coding session that a bridge appends to, say) has nothing here: its own
+//   subscription delivers what lands on its context to whatever runs it.
+// A message to an agent of any kind is ONE `agent/message-received` on its context (message.ts).
+// No verb calls a facet of an agent.
+//
+// A DELETED AGENT IS NOT STARTED AGAIN. Its death is a row of the catalog on `/agents`, and every
+// verb reads the catalog first: a dead agent's context is not even called.
+//
+// A ROW OF THE KIND `iterate` (`FORMER_KIND`) is a context that an agent of the platform ran, which
+// the platform no longer has. The mind's own agent takes such a context over at its next `create`
+// or message: `ownStart` says how.
+import { RpcTarget } from "cloudflare:workers";
+import type { StreamEvent, StreamEventInput } from "../stream/processor.ts";
+import { codedError, errorCode, resolveContextPath } from "../lib.ts";
+import type { IterateContextApi } from "../api.ts";
+import type { AgentHandleApi, AgentsApi } from "./api.ts";
+import type { AgentCatalogState } from "./catalog.ts";
+import { appendMessage } from "./message.ts";
+import { agentRecent } from "./recent.ts";
+import { AGENTS_PATH } from "./install.ts";
+
+/** THE MIND'S OWN AGENT (catalog.ts `AgentCollectionDurableObject.agent`). Its code is in the
+ *  mind's config repo, and the platform runs none of it: the collection only appends its facts.
+ *  - `kind`: what the agent's own start writes on `/agents` as its kind.
+ *  - `startEvents(path, { parent })`: the facts that make the context at `path` run the agent, each
+ *    with an idempotency key, so appending them again writes nothing. With `parent`, they hold the
+ *    link from the context's `itx` to that context; without, they hold none. */
+export type OwnAgent = {
+  kind: string;
+  startEvents(
+    path: string,
+    options: { parent?: string },
+  ): Promise<StreamEventInput[]> | StreamEventInput[];
+};
+
+/** The kind of a context that an agent of the platform ran (the header). */
+const FORMER_KIND = "iterate";
+
+/** The rows that copied such an agent's facts to `/agents`. The mind's own agent has rows of its
+ *  own for that, under other names. */
+const FORMER_ROWS = ["catalog-kind", "catalog-summary", "catalog-first-words", "catalog-status"];
+
+/** The catalog on `/agents` (catalog.ts) through the log's head, and the offset it is folded to. */
+export type CatalogRead = () => Promise<{ offset: number; state: AgentCatalogState }>;
+
+/** How long `create` waits for a new agent to be listed: its context announces itself to
+ *  `/agents` when it first wakes, which `create` has just made it do. */
+const LISTED_WAIT_MS = 10_000;
+
+/** `itx.agents` (api.ts `AgentsApi`) over one base: the root's at `/`, an agent's own at its
+ *  path (`at(base)`, catalog.ts). */
+export class AgentCollectionRpcTarget extends RpcTarget implements AgentsApi {
+  private readonly getItx: () => IterateContextApi & Disposable;
+  private readonly catalogRead: CatalogRead;
+  private readonly base: string;
+  private readonly own: OwnAgent | undefined;
+
+  constructor(
+    getItx: () => IterateContextApi & Disposable,
+    catalog: CatalogRead,
+    base = "/",
+    own?: OwnAgent,
+  ) {
+    super();
+    this.getItx = getItx;
+    this.catalogRead = catalog;
+    this.base = base;
+    this.own = own;
+  }
+
+  private async catalog() {
+    return (await this.catalogRead()).state;
+  }
+
+  get(path: string) {
+    path = resolveContextPath(this.base, path);
+    if (path === "/") throw new Error("An agent needs its own context path");
+    return new AgentReference(this.getItx, path, () => this.catalog(), this.base, this.own);
+  }
+
+  /** Every agent, by path: every context under `/agents`, with what a list shows about it. It reads
+   *  only the catalog on `/agents` (catalog.ts); reading the agents themselves would wake every
+   *  one. */
+  async list() {
+    return Object.entries((await this.catalog()).agents).map(([path, row]) => ({
+      path,
+      createdAt: row.createdAt,
+      parent: row.parent || null,
+      kind: row.kind || null,
+      host: row.host || null,
+      status: row.status || null,
+      activity: row.activity || null,
+      description: row.description || null,
+      title: row.title || null,
+      titleFromWords: !!row.title && !!row.titleFromWords,
+      lastActivityAt: row.lastActivityAt || null,
+    }));
+  }
+
+  /** Until the catalog lists `path`, a context under `/agents`: its own announcement lands there
+   *  when it first wakes, a moment after the call that woke it. Bounded: one that has not landed by
+   *  LISTED_WAIT_MS is logged and left to land on the context's next wake (core/itx's
+   *  `announceToAncestors` retries it then), so the agent `create` made is not refused for it. */
+  async #untilListed(path: string) {
+    if (!path.startsWith(`${AGENTS_PATH}/`)) return;
+    const { offset, state } = await this.catalogRead();
+    if (state.agents[path] || state.deleted[path]) return;
+    using itx = this.getItx();
+    try {
+      await itx.cd(AGENTS_PATH).waitForEvent({
+        type: "events.iterate.com/itx/child-created",
+        payload: { childPath: path },
+        afterOffset: offset,
+        timeoutMs: LISTED_WAIT_MS,
+      });
+    } catch (error) {
+      if (errorCode(error) !== "WAIT_TIMEOUT") throw error;
+      console.warn({
+        event: "agent-collection.not-listed",
+        message: "the agent's context has not announced itself to /agents yet",
+        path,
+        waitedMs: LISTED_WAIT_MS,
+      });
+    }
+  }
+
+  /** START THE MIND'S OWN AGENT at `path`: its start facts and this collection's row for it, in
+   *  ONE append. Every fact has a key, so a second create writes nothing. Nothing is waited for
+   *  but the listing: the agent runs once its facts are in the log. A deleted agent is not
+   *  re-creatable, and a mind whose config names no agent has none to start: both are thrown. Data
+   *  back, never the handle: `itx.agents.get(path)` addresses it. */
+  async create(path: string) {
+    using itx = this.getItx();
+    path = resolveContextPath(this.base, path);
+    if (path === "/") throw new Error("An agent needs its own context path");
+    // The parent link goes to this collection's base — the context whose own `itx.agents` row
+    // reached it — and never to a context `create` names. The base itself is still the caller's
+    // to choose through the public `at(base)`, and the root's is `/` for every context linked to
+    // it. The link does NOT bind the child to the creator's masks: the child's own `cd` and roots
+    // of every context answer from its own table, so only a bare `itx => null` on the child holds
+    // its code (core/itx/src/context/parent-rule-and-child.test.ts).
+    const creator = resolveContextPath("/", this.base);
+    // Writing a parent link on an ancestor would point back down to its child.
+    if (creator.startsWith(`${path}/`))
+      throw codedError("FORBIDDEN", "An agent cannot create its own ancestor");
+    if (!this.own)
+      throw new Error(
+        "this mind's config names no agent to start: its agents.ts sets `AgentCollectionDurableObject.agent = { kind, startEvents }` (core/configs/default/agents.ts)",
+      );
+    const catalog = await this.catalog();
+    if (catalog.deleted[path]) throw new Error(`agent ${path}: deleted — not re-creatable`);
+    const kind = catalog.agents[path]?.kind || null;
+    await itx.cd(path).append(...(await ownStart(this.own, path, kind, creator)));
+    await this.#untilListed(path);
+    return { path };
+  }
+
+  /** Take the agent at `path` out of being. Its death goes on `/agents` first, so a verb that
+   *  follows refuses. Then, for the mind's own agent, every row that its start enables goes, and
+   *  each facet with its storage. An agent of another kind hosts nothing here: its death is the
+   *  certificate alone. Idempotent: a second delete finds the rows that are left. An agent under
+   *  `/agents` that the catalog never listed has nothing to delete: thrown. Terminal: a deleted
+   *  agent is not re-creatable. */
+  async delete(path: string) {
+    using itx = this.getItx();
+    path = resolveContextPath(this.base, path);
+    if (path === "/") throw new Error("An agent needs its own context path");
+    const catalog = await this.catalog();
+    const row = catalog.agents[path];
+    if (!catalog.deleted[path] && !row && path.startsWith(`${AGENTS_PATH}/`))
+      throw codedError("NOT_CREATED", `agent ${path}: not created — nothing to delete`, { path });
+    // Unkeyed: the catalog's fold of a death is idempotent.
+    if (!catalog.deleted[path])
+      await itx
+        .cd(AGENTS_PATH)
+        .append({ type: "events.iterate.com/agent/deleted", payload: { path } });
+    if (!this.own || (row?.kind && row.kind !== this.own.kind && row.kind !== FORMER_KIND))
+      return { path };
+    const context = itx.cd(path);
+    const started = new Set((await this.own.startEvents(path, {})).flatMap(rowNameOf));
+    // Over the loopback stub the list's answer types as an RPC result, not the rows the context
+    // declares; the wire copied it.
+    const hosted = (await context.processors.list()) as unknown as { name: string }[];
+    for (const { name } of hosted) if (started.has(name)) await context.processors.disable(name);
+    return { path };
+  }
+}
+
+/** THE FACTS THAT START THE MIND'S OWN AGENT at `path`, whose row on `/agents` says `kind`, with
+ *  this collection's own row for it: `itx.agents` as that agent sees it, so a message it sends
+ *  names it as the sender.
+ *  - A path with no kind is a birth: the facts hold the link from its `itx` to `parent`.
+ *  - A path with the mind's own kind, or the former kind (a take-over), has its link since its
+ *    birth. None is written, so no later call links an agent to another parent.
+ *  - A path where another kind of agent runs is refused.
+ *
+ *  A TAKE-OVER needs nothing more than the start facts and four rows switched off. The start's
+ *  row for the agent has the name the former agent's row had (`agent`), so it replaces that row.
+ *  The former copy rows have other names than the own agent's: they go, or each summary and each
+ *  first word would be copied to `/agents` twice. The mind's own agent reads nothing of the log
+ *  that stands before its start (core/configs/default/agent/contract.ts). */
+async function ownStart(
+  own: OwnAgent,
+  path: string,
+  kind: string | null,
+  parent?: string,
+): Promise<StreamEventInput[]> {
+  if (kind && kind !== own.kind && kind !== FORMER_KIND)
+    throw codedError("FORBIDDEN", `agent ${path}: an agent of the kind ${kind} runs there`, {
+      path,
+    });
+  return [
+    ...(kind === FORMER_KIND
+      ? FORMER_ROWS.map((name) => ({
+          type: "events.iterate.com/itx/subscription-configured",
+          idempotencyKey: `agent-row-off:${name}:${path}`,
+          payload: { name, target: null },
+        }))
+      : []),
+    ...(await own.startEvents(path, kind ? {} : { parent })),
+    {
+      type: "events.iterate.com/itx/rewrite-rule-configured",
+      idempotencyKey: `agent-collection:${path}`,
+      payload: { match: "itx.agents", target: `itx.cd('/').agents.at(${JSON.stringify(path)})` },
+    },
+  ];
+}
+
+/** The name of the row that a start fact configures, if it configures one. */
+function rowNameOf(event: StreamEventInput): string[] {
+  if (event.type !== "events.iterate.com/itx/subscription-configured") return [];
+  const name = (event.payload as { name?: unknown } | undefined)?.name;
+  return typeof name === "string" ? [name] : [];
+}
+
+/** `recent()`'s window: 5 minutes by default, at most a day. */
+const RECENT_MINUTES = { default: 5, max: 1_440 };
+/** `recent()`'s lines: 30 by default, at most 200. */
+const RECENT_LINES = { default: 30, max: 200 };
+/** `recent()` reads from this many offsets before the newest one the catalog copied from the
+ *  agent's log (an ephemeral frame takes an offset too, and is not read), in pages of 1,000
+ *  durable events, at most four of them. */
+const RECENT_LOOKBACK = 3_000;
+
+/** `itx.agents.get(path)` (api.ts `AgentHandleApi`): the agent at one path, reached from the
+ *  collection's base. */
+class AgentReference extends RpcTarget implements AgentHandleApi {
+  private readonly getItx: () => IterateContextApi & Disposable;
+  private readonly path: string;
+  private readonly catalog: () => Promise<AgentCatalogState>;
+  private readonly base: string;
+  private readonly own: OwnAgent | undefined;
+
+  constructor(
+    getItx: () => IterateContextApi & Disposable,
+    path: string,
+    catalog: () => Promise<AgentCatalogState>,
+    base: string,
+    own?: OwnAgent,
+  ) {
+    super();
+    this.getItx = getItx;
+    this.path = path;
+    this.catalog = catalog;
+    this.base = base;
+    this.own = own;
+  }
+
+  /** Words for the agent: ONE `agent/message-received` appended to its context (message.ts
+   *  `appendMessage`), for every kind. A dead agent refuses from the catalog, and so does a path
+   *  under `/agents` that it does not list: neither context is called. The sender rides in the
+   *  payload as the base, which the sender's own `itx.agents` row pins
+   *  (`itx.cd('/').agents.at(<sender>)`, written by `create`); `/`, every context that reaches the
+   *  root's collection, is no sender. The attachments go to the mind's files by the two rows
+   *  `installAgents` writes on `/agents`.
+   *
+   *  THE MIND'S OWN AGENT GETS ITS START FACTS IN THE SAME APPEND, before the words. So a context
+   *  of the former kind is taken over here, and a publish of new agent code reaches an agent at
+   *  its next message. An agent of another kind gets the words alone, and its own subscription
+   *  delivers them. */
+  async message(...[input, options]: Parameters<AgentHandleApi["message"]>) {
+    const path = this.path;
+    const catalog = await this.catalog();
+    if (catalog.deleted[path]) throw new Error(`agent ${path}: deleted`);
+    const row = catalog.agents[path];
+    if (!row && path.startsWith(`${AGENTS_PATH}/`))
+      throw codedError(
+        "NOT_CREATED",
+        `agent ${path}: not created — itx.agents.create(${JSON.stringify(path)}) first`,
+        { path },
+      );
+    const kind = row?.kind;
+    const start =
+      this.own && (kind === this.own.kind || kind === FORMER_KIND)
+        ? await ownStart(this.own, path, kind)
+        : [];
+    return await appendMessage(
+      this.getItx,
+      path,
+      (itx) => itx.cd(path),
+      input,
+      this.base === "/" ? undefined : this.base,
+      options,
+      start,
+    );
+  }
+
+  /** What the agent did lately (api.ts `AgentRecent`): its catalog row, and a slice of its log
+   *  folded by recent.ts. The log has no read from its end, so the slice starts RECENT_LOOKBACK
+   *  offsets before the newest offset the catalog copied from it (its last status, activity or
+   *  title, near the head for an agent at work) and reads forward to the head, at most four pages
+   *  of 1,000 events. It reads the log alone: no agent wakes, only its context. A dead or unlisted
+   *  agent refuses, as `message` does. */
+  async recent(options: Parameters<AgentHandleApi["recent"]>[0] = {}) {
+    const path = this.path;
+    const catalog = await this.catalog();
+    if (catalog.deleted[path]) throw new Error(`agent ${path}: deleted`);
+    const row = catalog.agents[path];
+    if (!row && path.startsWith(`${AGENTS_PATH}/`))
+      throw codedError("NOT_CREATED", `agent ${path}: not created`, { path });
+    const bounded = (value: number | undefined, { default: fallback, max }: typeof RECENT_LINES) =>
+      Math.min(Math.max(1, Math.floor(value ?? fallback)), max);
+    const minutes = bounded(options.minutes, RECENT_MINUTES);
+    const limit = bounded(options.limit, RECENT_LINES);
+    const newest = Math.max(0, row?.titleAtOffset || 0, ...Object.values(row?.fieldAtOffset || {}));
+    const events: StreamEvent[] = [];
+    let after = Math.max(0, newest - RECENT_LOOKBACK);
+    using itx = this.getItx();
+    for (let page = 0; page < 4; page += 1) {
+      const read = await itx.cd(path).readEvents(after, 1_000);
+      events.push(...read.events);
+      if (read.atHead || read.events.length === 0) break;
+      after = read.scannedThroughOffset;
+    }
+    return {
+      path,
+      title: row?.title || null,
+      status: row?.status || null,
+      activity: row?.activity || null,
+      description: row?.description || null,
+      ...agentRecent(events, {
+        since: new Date(Date.now() - minutes * 60_000).toISOString(),
+        limit,
+        // the mind's own agent reads its words in as `context-added`; a context of the former
+        // kind is its own at the next message
+        own: row?.kind === FORMER_KIND || (!!this.own && row?.kind === this.own.kind),
+      }),
+    };
+  }
+}
A core/lib/src/agents/contract.ts
@@ -0,0 +1,58 @@
+// contract.ts — THE FACTS THAT EVERY KIND OF AGENT SHARES. An agent is a context under `/agents`
+// (catalog.ts). What runs it is its kind's business: the mind's own agent is code in the mind's
+// config repo (core/configs/default/agent/), and a coding session is a bridge's. The platform runs
+// no agent. These three facts are what `itx.agents` and a list need of any of them:
+//
+//   agent/message-received   words someone sent through `itx.agents.get(path).message(…)`
+//   agent/summary-updated    what the agent says about itself, which its rows copy to `/agents`
+//   agent/deleted            the death certificate, on `/agents`
+//
+// A plain catalog, as `RunEventCatalog` is (../stream/run.ts): no processor owns these facts and
+// none of them has a state here. A browser loads this file (the Dash reads these facts by these
+// schemas), so it imports zod alone.
+import { z } from "zod";
+
+/** A file attached to words (an attachment record, minus its signed URL): the mind file it was
+ *  stored as (`itx.files`), its content type, original name and size. */
+const FileAttachment = z.object({
+  contentType: z.string().min(1),
+  filename: z.string().min(1),
+  path: z.string().min(1),
+  size: z.number().int().nonnegative(),
+});
+export type FileAttachment = z.infer<typeof FileAttachment>;
+
+export const AgentEventCatalog = {
+  events: {
+    "events.iterate.com/agent/message-received": {
+      description:
+        "Words someone sent the agent through `itx.agents.get(path).message(…)`: the one input every kind of agent reads. The mind's own agent has it transcribed into its input, `agent/context-added`; another kind's delivery row hands it to whatever runs it.",
+      payloadSchema: z.object({
+        message: z.string(),
+        /** Files stored under the agent's path (`message()` stores them). */
+        files: z.array(FileAttachment).optional(),
+        /** The context that sent the words, as the collection relays it (collection.ts). Absent:
+         *  the words came from the mind's root, a person's or the mind's own code. */
+        from: z.string().optional(),
+        /** `false`: context only, the words wake nothing (`message(…, { trigger: false })`). Each
+         *  kind decides what that means; absent means the words want an answer. */
+        trigger: z.literal(false).optional(),
+      }),
+    },
+    "events.iterate.com/agent/summary-updated": {
+      description:
+        "What the agent says about itself, each field optional and merged: `activity` (what it is doing now), `title` (its own short title), `waitingFor` (what it waits for; null clears it) and `description` (its purpose or conclusions). A row on the agent's context copies it to `/agents`, where a list reads it.",
+      payloadSchema: z.object({
+        activity: z.string().min(1).optional(),
+        title: z.string().min(1).max(200).optional(),
+        waitingFor: z.enum(["user_input", "external_event", "timer"]).nullable().optional(),
+        description: z.string().min(1).max(1_000).optional(),
+      }),
+    },
+    "events.iterate.com/agent/deleted": {
+      description:
+        "The death certificate, on `/agents`: the catalog drops the agent's row and keeps the death, so it names the path. Terminal: a deleted agent is not re-creatable.",
+      payloadSchema: z.object({ path: z.string().min(1) }),
+    },
+  },
+};
A core/lib/src/agents/index.ts
@@ -0,0 +1,16 @@
+// iterate/agents — the agents app: the collection of a mind's agents, `itx.agents`, and the
+// catalog of them on `/agents`. The platform runs no agent: the mind's own agent is code in the
+// mind's config repo (core/configs/default/agent/), and the config tells the collection how to
+// start one. A mind's config repo re-exports this class from its `agents.ts` and installs it from
+// its init case (install.ts); importing this module registers `itx.agents` on iterate/api's
+// `InstalledAppRoots` (api.ts).
+export { AgentCollectionDurableObject } from "./catalog.ts";
+export { appendMessage } from "./message.ts";
+export type {
+  AgentHandleApi,
+  AgentListing,
+  AgentMessageInput,
+  AgentsApi,
+  AgentsRootApi,
+} from "./api.ts";
+export type { OwnAgent } from "./collection.ts";
A core/lib/src/agents/install.test.ts
@@ -0,0 +1,120 @@
+import { expect, test, vi } from "vitest";
+import { installAgents } from "./install.ts";
+
+test("installAgents enables the catalog on /agents, points the root's itx.agents rule at it, and disables the root's old catalog", async () => {
+  const root = fakeRoot({ rows: ["agents"] });
+  await installAgents(root);
+  expect(root).toMatchObject({
+    calls: [
+      [
+        "/agents processors.enable",
+        "agents",
+        {
+          ...published("AgentCollectionDurableObject"),
+          consumes: [
+            "events.iterate.com/itx/child-created",
+            "events.iterate.com/agent/deleted",
+            "events.iterate.com/agent/listing-updated",
+          ],
+        },
+      ],
+      // the two rows the next test reads
+      ["/agents append", expect.anything(), expect.anything()],
+      [
+        "append",
+        {
+          type: "events.iterate.com/itx/rewrite-rule-configured",
+          payload: {
+            match: "itx.agents",
+            target: [
+              "itx",
+              ["cd", "/agents"],
+              "facets",
+              ["get", "agents", published("AgentCollectionDurableObject")],
+            ],
+            description: expect.stringContaining("create(path)"),
+          },
+        },
+      ],
+      ["processors.list"],
+      ["processors.disable", "agents"],
+    ],
+  });
+});
+
+test("installAgents writes the rows on /agents by which the collection stores an attachment in the mind's files", async () => {
+  const root = fakeRoot({ rows: [] });
+  await installAgents(root);
+  expect(root.calls.filter(([call]) => call === "/agents append")).toEqual([
+    [
+      "/agents append",
+      {
+        type: "events.iterate.com/itx/rewrite-rule-configured",
+        payload: {
+          match: "itx.files",
+          target: ["itx", ["cd", "/"], "files"],
+          description: expect.stringContaining("attachments"),
+        },
+      },
+      {
+        type: "events.iterate.com/itx/rewrite-rule-configured",
+        payload: {
+          match: "itx.r2",
+          target: ["itx", ["cd", "/"], "r2"],
+          description: expect.stringContaining("files"),
+        },
+      },
+    ],
+  ]);
+});
+
+test("installAgents disables nothing once the root has no catalog of its own", async () => {
+  const root = fakeRoot({ rows: [] });
+  await installAgents(root);
+  expect(root.calls.map(([call]) => call)).toEqual([
+    "/agents processors.enable",
+    "/agents append",
+    "append",
+    "processors.list",
+  ]);
+});
+
+/** The facet spec every row and rule of the app names: a class of the config repo's `agents.ts`,
+ *  in the mind's published config (the facet restarts by that module's bundle, not a key). */
+function published(className: string) {
+  return { className, mainModule: "agents.ts", source: ["itx", ["cd", "/"], "config"] };
+}
+
+/** A mind root, with processor rows named `rows`, that records the calls installing makes. */
+function fakeRoot({ rows }: { rows: string[] }) {
+  const calls: unknown[][] = [];
+  return {
+    calls,
+    processors: {
+      enable: vi.fn(async (name: string) => ({ name })),
+      list: vi.fn(async () => {
+        calls.push(["processors.list"]);
+        return rows.map((name) => ({ name }));
+      }),
+      disable: vi.fn(async (name: string) => {
+        calls.push(["processors.disable", name]);
+      }),
+    },
+    cd: (path: string) => ({
+      processors: {
+        enable: vi.fn(async (name: string, spec?: object) => {
+          calls.push([`${path} processors.enable`, name, spec]);
+          return { name };
+        }),
+      },
+      append: vi.fn(async (...events: object[]) => {
+        calls.push([`${path} append`, ...events]);
+        return [];
+      }),
+    }),
+    append: vi.fn(async (...events: object[]) => {
+      calls.push(["append", ...events]);
+      return [];
+    }),
+  };
+}
A core/lib/src/agents/install.ts
@@ -0,0 +1,79 @@
+// install.ts — what a config repo's init case calls (README.md). Not the runtime, so importing it
+// loads none.
+import type {} from "./api.ts"; // registers `itx.agents` on InstalledAppRoots
+import type { IterateContextApi } from "../api.ts";
+
+/** Where the catalog lives. Every context under it, at any depth, is an agent (catalog.ts). */
+export const AGENTS_PATH = "/agents";
+
+/** The module of a mind's published config that exports the collection's class, unless the
+ *  config names another to `installAgents`. */
+const AGENTS_MODULE = "agents.ts";
+
+/** The processor verbs installing calls. `list` is read only for each row's name, and answers
+ *  through a promise over the wire. */
+type Processors = Pick<IterateContextApi["processors"], "enable" | "disable"> & {
+  list(): readonly { name: string }[] | PromiseLike<readonly { name: string }[]>;
+};
+
+/** Idempotent: enabling the row again appends nothing, the rules are written back if removed, and a
+ *  catalog row on the root is disabled once. */
+export async function installAgents(
+  itx: Pick<IterateContextApi, "append"> & {
+    processors: Processors;
+    cd(path: string): Pick<IterateContextApi, "append"> & {
+      processors: Pick<Processors, "enable">;
+    };
+  },
+  options: { module?: string } = {},
+) {
+  // the collection's facet: the class of that name in `module` of the mind's published config
+  const spec = {
+    className: "AgentCollectionDurableObject",
+    mainModule: options.module || AGENTS_MODULE,
+    source: ["itx", ["cd", "/"], "config"],
+  };
+  const agents = itx.cd(AGENTS_PATH);
+  await agents.processors.enable("agents", {
+    ...spec,
+    consumes: [
+      "events.iterate.com/itx/child-created",
+      "events.iterate.com/agent/deleted",
+      "events.iterate.com/agent/listing-updated",
+    ],
+  });
+  // `/agents` has no link to the root. The collection stores the attachments of a message
+  // through its own itx (message.ts `appendMessage`), so these two names reach the root's.
+  await agents.append(
+    {
+      type: "events.iterate.com/itx/rewrite-rule-configured",
+      payload: {
+        match: "itx.files",
+        target: ["itx", ["cd", "/"], "files"],
+        description:
+          "The mind's files: the agents collection stores here the attachments of a message to an agent",
+      },
+    },
+    {
+      type: "events.iterate.com/itx/rewrite-rule-configured",
+      payload: {
+        match: "itx.r2",
+        target: ["itx", ["cd", "/"], "r2"],
+        description:
+          "The mind's R2: the mind's files are built on it, and call it through this context's rules",
+      },
+    },
+  );
+  await itx.append({
+    type: "events.iterate.com/itx/rewrite-rule-configured",
+    payload: {
+      match: "itx.agents",
+      target: ["itx", ["cd", AGENTS_PATH], "facets", ["get", "agents", spec]],
+      description:
+        "The mind's installed agents app, every context under /agents: list(), create(path), get(path).message(text), delete(path)",
+    },
+  });
+  // A catalog on the root is read by nothing, and would fold every copy an agent still sends to `/`.
+  const rows = await itx.processors.list();
+  if (rows.some((row) => row.name === "agents")) await itx.processors.disable("agents");
+}
A core/lib/src/agents/kinds.ts
@@ -0,0 +1,66 @@
+// agents/kinds.ts — KINDS OF AGENT. An agent kind is one file in a mind's config repo
+// (`agent-kinds/<kind>.ts` by convention) whose default export is an `AgentKind`: what its agents
+// are called in the catalog, its server half (the shape of an `Integration`'s `processEvent`), what
+// the Dash reads of an agent's log, and its chat view. A config repo names its kinds (core/configs/default/agent-kinds/index.ts),
+//
+//   import { makeAgentKind } from "iterate/agents/kinds";
+//   export const agentKinds = [makeAgentKind(import.meta, () => import("./iterate.ts"))];
+//
+// its worker runs each kind's `processEvent` beside the integrations, and calls `publishAgentKinds` on every
+// publish (core/configs/default/every-event.ts, init.ts). The view is the Agents
+// app's business: it runs in a sandboxed frame there, and `@iterate-com/ui/agent-kind-view` gives
+// `View` its React type. Nothing here needs React or `cloudflare:workers`, so a browser's code can
+// name these types too.
+import type { IterateContextApi } from "../api.ts";
+import type { StreamEvent } from "../stream/processor.ts";
+
+export type AgentKind<View = unknown> = {
+  /** The catalog's `kind` for these agents: the Dash finds this file by it. */
+  kind: string;
+  /** The server half: every durable event of the mind, after the mind's own cases. A kind
+   *  answers its own: sets up an agent's rows when it starts, hands a `message-received` on one of
+   *  its paths to whatever runs it, or does the work itself. Keyed appends: an event can come more
+   *  than once. A kind whose agents need nothing from the mind's worker has none. */
+  processEvent?: (args: { event: StreamEvent; itx: IterateContextApi }) => Promise<void>;
+  /** The ephemeral event types its view reads besides the agent's whole durable log (which the
+   *  Dash always reads: the Events tab shows it), e.g. an answer's streamed frames. A
+   *  wildcard never matches an ephemeral event, so each is named. */
+  ephemeralEvents?: string[];
+  /** The chat, which only the Dash's frame calls. */
+  view: View;
+};
+
+/** A kind file, from a function written exactly `() => import("./path/to/kind.ts")`. `path` is the
+ *  file's place in the config repo: the import, resolved against `meta`, the calling file's
+ *  `import.meta`. The platform gives each module that reads `import.meta` a `url` of
+ *  `file:///<its path in the repo>`, and keeps the import as written but for `.ts` → `.js`
+ *  (`publishAgentKinds` checks which the repo has). Under Vite (a test) both are the checkout's
+ *  absolute paths, so `path` is too. */
+export function makeAgentKind(meta: { url?: string }, load: () => Promise<{ default: AgentKind }>) {
+  const specifier = load
+    .toString()
+    .match(/^\(\)\s*=>\s*[\w$]*import[\w$]*\(\s*(["'])([^"']+)\1\s*\)$/)?.[2];
+  if (!specifier)
+    throw new Error(
+      `makeAgentKind takes () => import("./path/to/kind.ts") and nothing else, not ${load.toString()}`,
+    );
+  if (!meta.url) throw new Error("makeAgentKind takes its file's import.meta, which has no url");
+  const url = new URL(specifier.replace(/^\/@fs\//, "/"), meta.url);
+  return { path: decodeURIComponent(url.pathname).slice(1), load };
+}
+
+/** Writes `{ <kind>: <path> }` to the mind's KV under `agent-kinds`, where the Dash reads
+ *  which file has a kind's chat view. A path the repo doesn't have (`x.js`, as the platform loads
+ *  it) is the `.ts` it was written as. */
+export async function publishAgentKinds(
+  itx: IterateContextApi,
+  agentKinds: ReturnType<typeof makeAgentKind>[],
+) {
+  const repo = itx.repos.get("/repos/config");
+  const paths: Record<string, string> = {};
+  for (const { path, load } of agentKinds) {
+    const { default: kind } = await load();
+    paths[kind.kind] = (await repo.readFile(path)) === null ? path.replace(/\.js$/, ".ts") : path;
+  }
+  await itx.kv.put("agent-kinds", JSON.stringify(paths));
+}
A core/lib/src/agents/message.ts
@@ -0,0 +1,110 @@
+// message.ts — words one context puts in an agent's log: what `itx.agents.get(path).message(text,
+// options)` appends (`appendMessage`): ONE `agent/message-received`, the input every kind of agent
+// reads (contract.ts).
+import { z } from "zod";
+import type { IterateContextApi } from "../api.ts";
+import { codedError } from "../lib.ts";
+import type { StreamEvent, StreamEventInput } from "../stream/processor.ts";
+import type { AgentMessageInput, AgentMessageOptions } from "./api.ts";
+import type { FileAttachment } from "./contract.ts";
+
+/** A sender's key for one message. */
+const MessageKey = z.string().min(1).max(200);
+
+/** The SHA-256 of a text, or of a file's content as the sender gave it, in hex. */
+async function sha256Hex(data: string | Uint8Array | ArrayBuffer): Promise<string> {
+  // a view may stand on a shared buffer, which the digest does not take: its bytes are copied
+  const bytes =
+    typeof data === "string"
+      ? new TextEncoder().encode(data)
+      : data instanceof ArrayBuffer
+        ? new Uint8Array(data)
+        : Uint8Array.from(data);
+  return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (byte) =>
+    byte.toString(16).padStart(2, "0"),
+  ).join("");
+}
+
+/** A message to the agent at `path`: its attachments, each stored first under the agent's path
+ *  (`itx.files`, `<path>/<8 of a uuid>-<name>`), then ONE `message-received` naming them, appended to
+ *  the context `target` picks from a scope: the collection picks the agent's from its own scope
+ *  (collection.ts), and an agent's own facet appends to its own (a person's view of one context
+ *  calls it, core/itx/src/person-context.ts). The collection's itx is that of `/agents`, which
+ *  reaches the mind's files by the `itx.files` and `itx.r2` rows `installAgents` writes there
+ *  (install.ts). Answers the event, so a caller can wait for what follows it.
+ *
+ *  WITH A KEY (`options.key`) THE SAME MESSAGE SENT AGAIN LANDS ONCE: the event's idempotency key
+ *  is the sender's key, so the log answers a repeat with the event it already holds, also when
+ *  two sends race. The same key with other words is refused (IDEMPOTENCY_CONFLICT).
+ *  - A FILE OF A KEYED MESSAGE IS NEVER REPLACED. Its path is made from the key, its place in
+ *    the list, its content type and the SHA-256 of its content. The same content of the same type
+ *    again writes the same bytes to the same path. Other content, or another type, under the same
+ *    key goes to another path, so the event's body differs and the send is refused; the file that the first event names stays as it was. (The refused
+ *    send leaves its own file behind, named by nothing.)
+ *  - THE KEY IS THE CONTEXT'S, NOT THE SENDER'S: one name space per agent. The log compares an
+ *    event's type and payload, never who appended it. So a second sender with the same key and
+ *    the same words gets the first sender's event, and the log names the first sender alone. A
+ *    sender makes keys that nobody else would make (the kit: a random id of the page, then a
+ *    count). */
+export async function appendMessage(
+  getItx: () => IterateContextApi & Disposable,
+  path: string,
+  target: (itx: IterateContextApi) => Pick<IterateContextApi, "append">,
+  input: AgentMessageInput,
+  from: string | undefined,
+  options: AgentMessageOptions | undefined,
+  /** Facts that go into the same append, before the message: the start facts of a mind's own
+   *  agent (collection.ts `ownStart`). The log refuses the whole append when one of their keys
+   *  comes back with another body, so the words never land without them. */
+  first: StreamEventInput[] = [],
+): Promise<StreamEvent> {
+  const { message, files = [] } = typeof input === "string" ? { message: input } : input;
+  // The options crossed RPC unchecked. A key that is no string, an empty one and a longer one
+  // are refused, never cut or dropped: another key could be another message's, and a sender that
+  // gave a key expects the message to land once.
+  const parsedKey = MessageKey.optional().safeParse(options?.key);
+  if (!parsedKey.success)
+    throw codedError(
+      "INVALID_INPUT",
+      "message(…, { key }): a key is a string of 1 to 200 characters",
+    );
+  const key = parsedKey.data;
+  const attachments: FileAttachment[] = [];
+  for (const [index, file] of files.entries()) {
+    const filename = file.filename.replace(/[^A-Za-z0-9._-]+/g, "-");
+    const stem = key
+      ? (
+          await sha256Hex(
+            `${key}\n${String(index)}\n${file.contentType}\n${await sha256Hex(file.data)}`,
+          )
+        ).slice(0, 16)
+      : crypto.randomUUID().slice(0, 8);
+    const storedAt = `${path}/${stem}-${filename}`;
+    using itx = getItx();
+    const stored = await itx.files
+      .get(storedAt)
+      .put({ contentType: file.contentType, data: file.data });
+    attachments.push({
+      contentType: stored.contentType,
+      filename: file.filename,
+      path: stored.path,
+      size: stored.size,
+    });
+  }
+  using itx = getItx();
+  const appended = await target(itx).append(...first, {
+    type: "events.iterate.com/agent/message-received",
+    ...(key && { idempotencyKey: `agent-message:${key}` }),
+    payload: {
+      message,
+      ...(attachments.length > 0 && { files: attachments }),
+      // oxlint-disable-next-line iterate/simple-truthiness-check -- the stored event has no key for an absent sender, and the log compares a repeat of a keyed event with the stored one key by key: `from: undefined` would be another event
+      ...(from && { from }),
+      ...(options?.trigger === false && { trigger: false as const }),
+    },
+  });
+  // Over the loopback stub the append's answer types as an RPC result, not the array the context
+  // declares (`append(...events): Promise<StreamEvent[]>`, context/built-ins.ts); the wire copied it.
+  // The message is the last event of the append: the facts in `first` stand before it.
+  return (appended as unknown as StreamEvent[]).at(-1)!;
+}
A core/lib/src/agents/recent.test.ts
@@ -0,0 +1,131 @@
+// recent.test.ts — `itx.agents.get(path).recent()`'s fold (recent.ts) over a small log of the mind's
+// own agent: the window, one line per thing done, the newest script whole with its error; and
+// another kind's log.
+import { expect, test } from "vitest";
+import type { StreamEvent } from "../stream/processor.ts";
+import { agentRecent } from "./recent.ts";
+
+test("the window's lines, oldest first, and the newest script whole with its error", () => {
+  expect(agentRecent(LOG, { since: at(40), limit: 30, own: true })).toEqual({
+    did: [
+      { at: at(41), what: "message-in", text: "Check the deploy log" },
+      { at: at(41), what: "status", text: "Reading the deploy log" },
+      { at: at(41), what: "script", text: "const files = 1" },
+      { at: at(42), what: "status", text: "Fetching it" },
+      { at: at(42), what: "script", text: "await itx.fetch(url)" },
+      { at: at(43), what: "summary", text: "Deploy check — waiting for user input" },
+      { at: at(43), what: "message-out", text: "The deploy failed: fetch failed." },
+    ],
+    lastScript: {
+      at: at(42),
+      status: "",
+      script: "  await itx.fetch(url)\nreturn 1",
+      error: "fetch failed",
+    },
+  });
+});
+
+test("the limit keeps the newest lines; an empty window has none and no script", () => {
+  const { did } = agentRecent(LOG, { since: at(40), limit: 2, own: true });
+  expect(did.map((line) => line.what)).toEqual(["summary", "message-out"]);
+  expect(agentRecent(LOG, { since: at(50), limit: 30, own: true })).toEqual({
+    did: [],
+    lastScript: null,
+  });
+});
+
+test("an event it cannot read is skipped, never thrown on", () => {
+  const log = [
+    { ...event(41, "agent/summary-updated", {}), payload: undefined },
+    { ...event(41, "agent/context-added", {}), payload: "not an object" },
+    {
+      ...event(41, "itx/run-settled", { requestOffset: "x", settlement: null }),
+      source: undefined,
+    },
+    event(41, "llm-request/settled", { result: "no record" }),
+    event(42, "agent-ui/message-sent", { message: "Still here." }),
+  ] as unknown as StreamEvent[]; // malformed on purpose: a raw log can hold any payload
+  expect(agentRecent(log, { since: at(40), limit: 30, own: true })).toEqual({
+    did: [{ at: at(42), what: "message-out", text: "Still here." }],
+    lastScript: null,
+  });
+});
+
+test("another kind's log: its words in are `message-received`, and a missing type is no error", () => {
+  const log = [
+    event(41, "agent/message-received", { message: "Hi", from: "/agents/b" }),
+    event(41, "agent/context-added", { role: "user", content: "a bridge's own copy" }),
+    event(42, "claude/tool-used", { name: "Bash" }),
+  ];
+  expect(agentRecent(log, { since: at(40), limit: 30, own: false })).toEqual({
+    did: [{ at: at(41), what: "message-in", text: "[from /agents/b] Hi" }],
+    lastScript: null,
+  });
+});
+
+test("the mind's own agent: its words in are its input, with the sender; an answer with no block is no script", () => {
+  const log = [
+    event(41, "agent/message-received", { message: "Count the files" }),
+    event(41, "agent/context-added", { role: "user", content: "Count the files\n\n— Web UI" }),
+    event(41, "agent/context-added", {
+      role: "user",
+      content: "And the folders",
+      from: "/agents/b",
+    }),
+    event(41, "agent/context-added", { role: "developer", content: "[result 4]\n3" }),
+    event(41, "llm-request/settled", answer(block("const n = 3\nreturn n"))),
+    event(41, "itx/run-requested", { code: "wrapped" }, ownRun),
+    event(42, "agent-ui/message-sent", { message: "There are 3 files." }),
+    // the run after an answer with no block is not the script of an answer
+    event(43, "llm-request/settled", answer("")),
+    event(43, "itx/run-requested", { code: "wrapped" }, ownRun),
+  ];
+  expect(agentRecent(log, { since: at(40), limit: 30, own: true })).toEqual({
+    did: [
+      { at: at(41), what: "message-in", text: "Count the files — Web UI" },
+      { at: at(41), what: "message-in", text: "[from /agents/b] And the folders" },
+      { at: at(41), what: "script", text: "const n = 3" },
+      { at: at(42), what: "message-out", text: "There are 3 files." },
+    ],
+    lastScript: { at: at(41), status: "", script: "const n = 3\nreturn n" },
+  });
+});
+
+const PATH = "/agents/a";
+const at = (minute: number) => `2026-11-16T10:${String(minute).padStart(2, "0")}:00.000Z`;
+let offset = 0;
+function event(minute: number, type: string, payload: unknown, source: object = {}): StreamEvent {
+  offset += 1;
+  return {
+    offset,
+    path: PATH,
+    type: `events.iterate.com/${type}`,
+    payload,
+    createdAt: at(minute),
+    source: { origin: PATH, ...source },
+  } as StreamEvent;
+}
+const ownRun = { processor: { slug: "agent" } };
+/** A model's answer as the request maker settles it: the mind's own agent answers with one
+ *  `<codemode>` block, which its next run runs. */
+const answer = (text: string) => ({ llmRequestOffset: 1, result: { status: "succeeded", text } });
+const block = (script: string) => `<codemode>\n${script}\n</codemode>`;
+
+const LOG = [
+  event(30, "agent/context-added", { role: "user", content: "Old words" }),
+  event(36, "llm-request/settled", answer(block("const files = 1\nreturn files"))),
+  event(41, "agent/context-added", { role: "user", content: "Check the\ndeploy log" }),
+  event(41, "agent/summary-updated", { activity: "Reading the deploy log" }),
+  event(41, "itx/run-requested", { code: "wrapped" }, ownRun),
+  event(41, "itx/run-settled", { requestOffset: 5, settlement: { status: "succeeded" } }),
+  event(42, "llm-request/settled", answer(block("  await itx.fetch(url)\nreturn 1"))),
+  event(42, "agent/summary-updated", { activity: "Fetching it" }),
+  event(42, "itx/run-requested", { code: "wrapped" }, ownRun),
+  event(42, "itx/run-requested", { code: "someone else's" }),
+  event(43, "itx/run-settled", {
+    requestOffset: 9,
+    settlement: { status: "failed", error: "fetch failed", failureKind: "runtime" },
+  }),
+  event(43, "agent/summary-updated", { title: "Deploy check", waitingFor: "user_input" }),
+  event(43, "agent-ui/message-sent", { message: "The deploy failed: fetch failed." }),
+];
A core/lib/src/agents/recent.ts
@@ -0,0 +1,110 @@
+// recent.ts — `itx.agents.get(path).recent()` (api.ts `AgentRecent`): what one agent did lately,
+// folded from a slice of its own log. collection.ts reads the slice; this file only folds it, so a
+// test needs no context. Every kind of agent is read the same way: an event type its log does not
+// have is simply absent, and a field it cannot read (a raw log can hold any payload) is skipped.
+import type { StreamEvent } from "../stream/processor.ts";
+import type { AgentDidKind, AgentRecent } from "./api.ts";
+
+/** A `did` line is cut to this many characters. */
+const DID_CHARS = 300;
+
+/** The script of an answer of a mind's own agent: everything between the first line, `<codemode>`,
+ *  and the last `</codemode>` line. */
+const CODEMODE_BLOCK = /^\s*<codemode>[ \t]*\n([\s\S]*)\n[ \t]*<\/codemode>\s*$/;
+
+/** The window's lines and newest script, from `events` in offset order. `own` says which event
+ *  is the words in: the input of the mind's own agent, `context-added` (a person's words, mail, a
+ *  schedule's input, all one type), or, for another kind, the `message-received` it is sent. */
+export function agentRecent(
+  events: Pick<StreamEvent, "offset" | "path" | "type" | "payload" | "createdAt" | "source">[],
+  { since, limit, own }: { since: string; limit: number; own: boolean },
+): Pick<AgentRecent, "did" | "lastScript"> {
+  const did: AgentRecent["did"] = [];
+  const add = (at: string, what: AgentDidKind, text: string) => {
+    if (at < since) return;
+    const line = text.replace(/\s+/g, " ").trim();
+    if (line)
+      did.push({
+        at,
+        what,
+        text: line.length > DID_CHARS ? `${line.slice(0, DID_CHARS - 1)}…` : line,
+      });
+  };
+  /** The script of the newest answer, which the next run the agent requests runs. */
+  let call: { status: string; script: string } | null = null;
+  const scripts = new Map<number, NonNullable<AgentRecent["lastScript"]>>();
+  let lastScript: AgentRecent["lastScript"] = null;
+  // the events before `since` are read too: an answer's call may precede its run in the window
+  for (const event of events) {
+    const payload = fields(event.payload);
+    const text = (key: string) => textOf(payload, key);
+    const origin = textOf(fields(event.source), "origin");
+    switch (event.type) {
+      case "events.iterate.com/agent/summary-updated": {
+        add(event.createdAt, "status", text("activity"));
+        const waitingFor = text("waitingFor").replace("_", " ");
+        add(
+          event.createdAt,
+          "summary",
+          [text("title"), waitingFor && `waiting for ${waitingFor}`, text("description")]
+            .filter(Boolean)
+            .join(" — "),
+        );
+        break;
+      }
+      case "events.iterate.com/agent/context-added": {
+        const from = text("from") || (origin !== event.path && origin);
+        if (own && text("role") === "user")
+          add(event.createdAt, "message-in", `${from ? `[from ${from}] ` : ""}${text("content")}`);
+        break;
+      }
+      case "events.iterate.com/agent/message-received":
+        if (!own)
+          add(
+            event.createdAt,
+            "message-in",
+            `${text("from") ? `[from ${text("from")}] ` : ""}${text("message")}`,
+          );
+        break;
+      // words out: the words of the mind's own agent in the web or mobile UI
+      case "events.iterate.com/agent-ui/message-sent":
+        add(event.createdAt, "message-out", text("message"));
+        break;
+      // a mind's own agent answers with one `<codemode>` block, which the next run it requests runs
+      case "events.iterate.com/llm-request/settled": {
+        const script = CODEMODE_BLOCK.exec(textOf(fields(payload.result), "text"))?.[1];
+        if (script?.trim()) call = { status: "", script };
+        break;
+      }
+      // the agent's own run (the engine stamps it with the processor) runs the newest answer's script
+      case "events.iterate.com/itx/run-requested": {
+        if (textOf(fields(fields(event.source).processor), "slug") !== "agent" || !call) break;
+        const ran = { at: event.createdAt, ...call };
+        call = null;
+        if (event.createdAt < since) break;
+        add(event.createdAt, "script", ran.script.split("\n").find((line) => line.trim()) || "");
+        scripts.set(event.offset, ran);
+        lastScript = ran;
+        break;
+      }
+      case "events.iterate.com/itx/run-settled": {
+        const settlement = fields(payload.settlement);
+        const script = scripts.get(Number(payload.requestOffset));
+        if (script && settlement.status === "failed")
+          script.error = textOf(settlement, "error") || "failed";
+        break;
+      }
+    }
+  }
+  return { did: did.slice(-limit), lastScript };
+}
+
+/** A value's own fields when it is an object, else none: an event of a raw log may hold anything. */
+function fields(value: unknown): Record<string, unknown> {
+  return typeof value === "object" && value ? Object.fromEntries(Object.entries(value)) : {};
+}
+
+function textOf(record: Record<string, unknown>, key: string): string {
+  const value = record[key];
+  return typeof value === "string" ? value : "";
+}
A core/lib/src/api.ts
@@ -0,0 +1,2687 @@
+// api.ts — THE API AN APP DIALS: the shapes of a mind's `/api` session and a context's surface, as
+// a capnweb client sees them. DECLARED here, never generated, and never the platform's classes:
+// core/itx serves a context as `IterateContextRpcTarget` (core/itx/src/iterate-context.ts, served
+// by core/itx/src/session.ts), so an app built against this package types against what the
+// deployment answers. A context
+// has ONE method — `invoke(call, ...args)`, a dotted itx expression — and a capnweb stub proxies the
+// dotted spelling (`itx.repos.get(path).readFile(file)`) onto it. THIS FILE IS THE SOURCE OF TRUTH
+// for every root app code reaches: core/itx derives its built-in record's type from these members
+// (core/itx/src/context/built-ins.ts `BuiltInScope`), so a root or a verb the platform
+// implements and this file does not declare — or declares differently — fails to typecheck there.
+// The roots installed apps add are NOT here: each app registers its own on `InstalledAppRoots` from
+// its package, and `IterateContextApiWith` spells a context that has them.
+
+import type {
+  Ai,
+  AiGatewayLog,
+  AiGatewayPatchLog,
+  AIGatewayUniversalRequest,
+  AiWebSearchRequest,
+  ConversionRequestOptions,
+  ConversionResponse,
+  ImageDrawOptions,
+  ImageInfoResponse,
+  ImageInputOptions,
+  ImageOutputOptions,
+  ImageTransform,
+  ImageTransformationOutputOptions,
+  ImageTransformationResponseOptions,
+  R2HTTPMetadata,
+  R2Range,
+  SupportedFileFormat,
+  TextOptions,
+  UniversalGatewayOptions,
+} from "@cloudflare/workers-types";
+import type { InvokeHandle, ItxExpression, ItxExpressionInput } from "./expression.ts";
+import type { ActRule } from "./acts.ts";
+import type { Principal } from "./principal.ts";
+import type { Envelope } from "./signed.ts";
+import type { StreamEvent, StreamEventInput } from "./stream/processor.ts";
+
+/** One page of a context's durable log (`readEvents`). */
+export interface StreamPage {
+  events: StreamEvent[];
+  scannedThroughOffset: number;
+  /** True iff the scan reached the durable mark: nothing more to read until the next commit. */
+  atHead: boolean;
+  /** The context's version and the offset of that version's `itx/created`, from the second
+   *  version on (`newVersion`); absent in a first version. A reader that holds one version of a
+   *  log reads nothing below the offset. */
+  version?: number;
+  versionStartedAtOffset?: number;
+}
+
+/** `waitForEvent`'s filter: an event type (or one of a list), payload fields the event must carry
+ *  with exactly these values (each a JSON primitive, compared with `===`), a floor, a timeout. With
+ *  an explicit `afterOffset` the log after it is searched first. Large searches yield between
+ *  pages; an older historical match takes precedence if found before the search deadline. */
+export type WaitForEventFilter = {
+  type?: string | string[];
+  payload?: Record<string, string | number | boolean | null>;
+  afterOffset?: number;
+  /** The time budget for the historical search and subsequent wait. A live match received within
+   *  the budget is kept if the historical search reaches its deadline. */
+  timeoutMs?: number;
+};
+
+/** The `rewrite-rule-configured` event's payload — what `itx.append` writes durably and `provide`
+ *  writes for its session: make `match` mean `target` (an expression, or `null` to deny). `description` is the one
+ *  line a model reads for the name; it rides the row into `rewriteRules.list()`. */
+export type RewriteRuleConfigured = {
+  match: ItxExpressionInput;
+  target: ItxExpressionInput | null;
+  /** What the name means here, in one line (≤ 500 chars). */
+  description?: string;
+  /** On the rule of a lent stub, the grant of the session that lends it: a key's is `key:<id>`, a
+   *  member's is the grant of their sign-in. `provide` sets it, and it rides the row into
+   *  `rewriteRules.list()`. A lend by a caller with no grant has none. */
+  lentBy?: string;
+};
+
+/** One row of `rewriteRules.list()` — the tree a context can spell. `context` is the path the row
+ *  was read from: this context for its own rows and its implicit rows, the target context for the
+ *  rows a bare hop row (`itx ⇒ itx.builtins.cd(path)`) reaches. A mask lists as `target: null`. */
+export type RewriteRuleListEntry = {
+  match: string;
+  target: string | null;
+  description?: string;
+  /** Who lent the row's stub (`RewriteRuleConfigured.lentBy`). */
+  lentBy?: string;
+  context: string;
+};
+
+/** One row of `subscriptions.list()` / `processors.list()`. */
+export type SubscriptionListEntry = {
+  name: string;
+  target: string;
+  consumes?: string[];
+  configuredAtOffset: number;
+  afterOffset?: number;
+  /** `false`: a FAN-OUT row — one event per call, in any order, each event retried on its own and
+   *  dead-lettered alone (`itx/subscription-delivery-failed`). Its `cursor` is how far it has
+   *  admitted events, `pending` how many events wait for a retry, and `paused` whether new events
+   *  wait for the receiver (it failed the last few distinct events: one new event is let through at
+   *  each rung of the row's own probe). */
+  ordered?: false;
+  pending?: number;
+  paused?: boolean;
+  /** Set on a copy row (one subscribed with an `EventCopyTarget`): which events it copies, and the
+   *  target as it was written. Its `target` is then `itx.cd(path)`, which only checks that this
+   *  context's rules still let it reach `path`. */
+  filter?: string;
+  copy?: EventCopyTarget;
+  /** Set when this row hosts a facet (a processor). `restarts`: how many times the platform failed
+   *  the facet at its start and the context restarted it under a fresh loaded identity (a platform
+   *  defect the context works around; the count is the cheap way to ask "how often, here"). */
+  hostedFacet?: {
+    name: string;
+    className: string;
+    cacheKey?: string;
+    mainModule?: string;
+    /** The worker's name when the source is one (`FacetSpec`): any other source is not listed. */
+    source?: unknown;
+    restarts: number;
+  };
+  /** Set for a row the context delivers at-least-once (an itx expression target; a facet and a lent
+   *  stub own their progress): the offset the last acked call confirmed, the retry ladder's attempt
+   *  and when the next attempt is due. */
+  cursor?: { confirmedOffset: number; attempt: number; nextAttemptAtMs?: number };
+  /** Set once delivery exhausted its retries: the offset it stopped after, and why. */
+  halted?: { afterOffset: number; attempts: number; error?: string };
+  /** Set on a live-callback row (its target is `itx.builtins.rpcStubs.get("subscription:<name>")`):
+   *  who lent the callback, by the platform's stamp on the row's event: `source.principal`, else
+   *  `source.onBehalfOf.principal` of a person's one-context view (a stamp with neither `run` nor
+   *  `call`), with how they came (`via`). Code that ran for someone (a script's run, a facet's
+   *  call) names no holder. Never read from the payload. */
+  heldBy?: { principal: Principal; via?: { appPage: string } };
+};
+
+/** A `subscribe` target that copies each event onto the log of the context at `path`. `type`
+ *  replaces the event's type in the copy, and can't be an `itx/*` type, since a copy is never one of
+ *  the platform's own events. `payload` is a JSONata expression evaluated against the original
+ *  event, and the JSON object it answers is the copy's payload, for example
+ *  `{ "title": $substring(payload.title, 0, 120) }`. Without it the copy's payload is empty: name
+ *  the fields to keep, or write `payload` to keep them all. Quote keys as in JSON: an unquoted key
+ *  is a path into the event. */
+export type EventCopyTarget = { path: string; type?: string; payload?: string };
+
+/** A loaded worker's source: its modules, literally, or an itx expression that produces them (then
+ *  `cacheKey` names the build, and the caller owns "same key ⇒ same code"). */
+export type WorkerSource = Record<string, string> | ItxExpressionInput;
+
+/** What hosts a class as a durable facet — `facets.get(name, spec)`, `processors.enable(name, spec)`.
+ *  `source` is the code (its modules, or an expression that produces them under `cacheKey`), or —
+ *  an expression with NO `cacheKey` — the NAME of a loaded worker: one that resolves, as a call
+ *  would, to `itx.builtins.workers.get(spec)` in the table of the context whose rule it is
+ *  (`itx.cd('/').config`, the mind's published config). The facet loads that worker's source,
+ *  its producer run with that context's authority. `mainModule` names the module of the source that
+ *  exports `className` when it is not the source's entry (`agents.ts` of a config repo whose entry
+ *  is `worker.ts`): the facet runs that module's own graph, and — named by the mind's published
+ *  config — restarts in place, storage kept, only when that module's identity changes, never onto
+ *  an older publication. */
+export type FacetSpec = {
+  source: WorkerSource;
+  cacheKey?: string;
+  className: string;
+  mainModule?: string;
+};
+
+/** What `schedules.set` answers: the definition's identity, to cancel exactly it. */
+export type ScheduleReceipt = { key: string; scheduledAtOffset: number };
+
+/** A schedule's key: a string, or a pair that scopes a local key to its owner (a facet instance). */
+export type ScheduleKey = string | [string, string];
+
+/** When a schedule fires: at an instant (ISO, with offset), after a delay, or on an interval (at
+ *  least a second; missed ticks coalesce). */
+export type ScheduleWhen = { at: string } | { afterMs: number } | { everyMs: number };
+
+/** What `schedules.set` takes: the key, when, and the events (one to a hundred) each occurrence
+ *  appends — an event's type, payload and metadata only: identity and provenance are the firing's. */
+export type ScheduledAppendInput = {
+  key: ScheduleKey;
+  when: ScheduleWhen;
+  events: Pick<StreamEventInput, "type" | "payload" | "metadata">[];
+};
+
+/** One live schedule as `schedules.list()` / `get(key)` answer it: the definition (its key
+ *  normalized to a string), when it fires next, the offset of the fact that set it, who set it, and
+ *  the last failure until it is replaced or cancelled. */
+export type ScheduledAppend = {
+  key: string;
+  when: ScheduleWhen;
+  events: Pick<StreamEventInput, "type" | "payload" | "metadata">[];
+  nextAt: string;
+  scheduledAtOffset: number;
+  source?: StreamEventInput["source"];
+  failure?: { error: string; offset: number };
+};
+
+/** A secret's material: one string (`getSecret("/secrets/<name>")` is the whole value) or a JSON
+ *  object whose string fields `getSecret("/secrets/<name>", { field: "a.b" })` picks — the
+ *  multidimensional shape a credential exchange needs (`{ username, password, accessToken }`,
+ *  `{ clientId, clientSecret, refreshToken, accessToken }`). A string is always the one value: it has
+ *  no fields, whether or not it parses as JSON. `getSecret("/secrets/<name>", { appJwt: true })`, in
+ *  the Authorization header of a request to https://api.github.com alone, is a GitHub App's JWT
+ *  (RS256, ten minutes) made from the material's `appId` and `privateKey` (PEM): the key itself is
+ *  not sent. */
+export type SecretMaterial = string | Record<string, unknown>;
+
+/** A SECRET THAT GOES BY PROXY holds no value: a request that names it goes, signed by this mind
+ *  for `mind` (a control-plane hostname), to `<url>/<target host><path and query>`. THE PROXYING
+ *  MIND SEES EVERY REQUEST AND ANSWER OF THIS SECRET. Whoever may `secrets.set` a path can point
+ *  it at any https host this way: a jail grants no `set`. No approval rule holds one. */
+export type SecretProxy = { mind: string; url: string };
+
+/** How a token endpoint wants the client credential — the RFC 8414 `token_endpoint_auth_methods_supported`
+ *  registry values, so a provider's discovery document pastes straight in: `client_secret_basic`
+ *  (HTTP Basic — Google, Slack, the petshop; the default), `client_secret_post` (`client_id` +
+ *  `client_secret` as form fields — GitHub, Linear), `none` (a public client: `client_id` alone,
+ *  PKCE stands in for the secret). RFC 6749 §2.3.1 forbids sending two forms at once. */
+export type ClientAuth = "client_secret_basic" | "client_secret_post" | "none";
+
+/** ONE OF AN iterate Cloud's CLIENTS, as a secret names it: `cloud` is the Cloud's name for the
+ *  client (`github`, `google`, `slack`, `x`), and `origin` is that Cloud's address, an exact
+ *  `https:` origin with no path (`https://cloud.iterate.com`). No config of the stack names a
+ *  Cloud: the code that makes the secret does, and the secret keeps the origin from then on.
+ *  Everything that the secret later asks of a Cloud (the code's exchange, a refresh, an
+ *  installation's token, an ask) goes to that origin and to no other. Another origin is another
+ *  secret. */
+export type CloudClientName = { cloud: string; origin: string };
+
+/** A grant whose refresh names the stack's own OAuth client at Cloudflare. The stack makes no such
+ *  client (a mind connects through Cloudflare's MCP server, as its own client), so such a grant
+ *  does not refresh, and a member connects again. */
+export type StackClientName = { stack: "cloudflare" };
+
+/** CLOUDFLARE'S OWN OAUTH SERVER, the one behind its dashboard: where a connect through a client
+ *  that a member made in the account asks and exchanges, and where its token may go. The default
+ *  template connects through Cloudflare's MCP server instead (core/configs/default/cloudflare.ts);
+ *  a config of a mind's own that still connects here is held to the vault's own ceiling for
+ *  Cloudflare, reads alone, as every connect to Cloudflare is. */
+export const CLOUDFLARE_OAUTH = {
+  authorizationEndpoint: "https://dash.cloudflare.com/oauth2/auth",
+  tokenEndpoint: "https://dash.cloudflare.com/oauth2/token",
+  urls: ["https://api.cloudflare.com", "https://mcp.cloudflare.com"],
+} as const;
+
+/** WHAT A MIND'S CLOUDFLARE CONNECTION MAY READ: the OAuth scopes that a connect asks for, and
+ *  outside which the vault keeps no grant from Cloudflare (`grantedWithin`, and the vault's own
+ *  ceiling). The list is every read of Cloudflare's MCP server's "Read only" template
+ *  (github.com/cloudflare/mcp at 19f7601: each scope whose last part is `read`, `metadata_read`,
+ *  `monitoring` or `report`), so Cloudflare's consent screen shows standard Read-only access rather
+ *  than a custom list. No write is in it: Cloudflare refuses every write. The MCP server adds
+ *  `user:read`, `account:read` and `offline_access` to every grant; they are no part of the list.
+ *  core/lib/src/cloudflare-read-scopes.test.ts holds the list to the rule. */
+export const CLOUDFLARE_READ_SCOPES = [
+  "access-acct.read",
+  "access-app.read",
+  "access-audit-log.read",
+  "access-certificate.read",
+  "access-custom-page.read",
+  "access-device-posture.read",
+  "access-group.read",
+  "access-idp.read",
+  "access-key.read",
+  "access-org.read",
+  "access-policy-test.read",
+  "access-policy.read",
+  "access-population.read",
+  "access-saml-certificate.read",
+  "access-scim-log.read",
+  "access-service-token.read",
+  "access-ssh-auditing.read",
+  "access-tag.read",
+  "access-users.read",
+  "access.read",
+  "account-analytics.read",
+  "account-api-gateway.read",
+  "account-custom-asset.read",
+  "account-custom-error-rules.read",
+  "account-custom-pages.read",
+  "account-disable-esc.read",
+  "account-dns-settings.read",
+  "account-firewall-access-rules.read",
+  "account-logs.read",
+  "account-rule-lists.read",
+  "account-rulesets.read",
+  "account-security-center-insights.read",
+  "account-security-center-partner-integrations.read",
+  "account-settings.read",
+  "account-ssl-and-certificates.read",
+  "account-waf.read",
+  "account-waiting-rooms.read",
+  "address-maps.read",
+  "agw.read",
+  "ai-model.read",
+  "ai-search.metadata_read",
+  "ai-search.read",
+  "ai.read",
+  "aiaudit.read",
+  "aig.metadata_read",
+  "aig.read",
+  "analytics.read",
+  "api-gateway.read",
+  "argotunnel.read",
+  "artifacts.read",
+  "bot-management-feedback.read",
+  "bot-management.read",
+  "browser-rendering.read",
+  "cache-settings.read",
+  "calls.read",
+  "casb.read",
+  "cf-agents.read",
+  "cfspeed.read",
+  "challenge-widgets.read",
+  "chinanetwork-steering.read",
+  "cloud-connector.read",
+  "cloud-email-security.read",
+  "cloudchamber.read",
+  "cloudforce-one.read",
+  "config-settings.read",
+  "connectivity-directory.read",
+  "constellation.read",
+  "containers.read",
+  "custom-errors.read",
+  "custom-pages.read",
+  "cws.read",
+  "d1.metadata_read",
+  "d1.read",
+  "ddos-botnet-feed.read",
+  "ddos-protection.read",
+  "dls.read",
+  "dns-firewall.read",
+  "dns-view.read",
+  "dns.read",
+  "domain-page-shield.read",
+  "dynamic-redirect.read",
+  "email-routing-account-rule.read",
+  "email-routing-address.read",
+  "email-routing-rule.read",
+  "email-routing-suppression.read",
+  "email-security-dmarcreports.read",
+  "email-sending.read",
+  "fbm.read",
+  "field-extractor.read",
+  "firewall-for-ai.read",
+  "firewall-services.read",
+  "flagship.read",
+  "fraud-detection-pii.read",
+  "fraud-detection.read",
+  "fraud-feedback.read",
+  "healthcheck.read",
+  "http-applications.read",
+  "http-ddos-managed-ruleset.read",
+  "images.metadata_read",
+  "images.read",
+  "intel.read",
+  "iot.read",
+  "ip-prefix-bgp-on-demand.read",
+  "ip-prefix.read",
+  "k2.read",
+  "l4-ddos-managed-ruleset.read",
+  "load-balancers-account.read",
+  "load-balancers.read",
+  "load-balancing-monitors-and-pools.read",
+  "logs.read",
+  "magic-firewall.read",
+  "magic-transit.read",
+  "magic-wan.read",
+  "managed-headers.read",
+  "mass-url-redirects.read",
+  "mcp-portals.read",
+  "memberships.read",
+  "messaging.metadata_read",
+  "messaging.read",
+  "moq.read",
+  "notifications.read",
+  "origin.read",
+  "page-rules.read",
+  "page-shield.read",
+  "page.read",
+  "pages.metadata_read",
+  "payments-gateway.read",
+  "pcaps-api.read",
+  "pipelines.read",
+  "precursor.read",
+  "pubsub.read",
+  "query-cache.read",
+  "queues.metadata_read",
+  "queues.read",
+  "r2-catalog-sql.read",
+  "r2-catalog.read",
+  "radar.read",
+  "rag.read",
+  "realtime.read",
+  "registrar-domains.read",
+  "registrar-sandbox-domains.read",
+  "reports-application-security-report.read",
+  "request-tracer.read",
+  "resource-library.read",
+  "resource-sharing.read",
+  "response-compression.read",
+  "sanitize.read",
+  "secrets-store.read",
+  "select-configuration.read",
+  "snippets.read",
+  "ssl-and-certificates.read",
+  "stream.metadata_read",
+  "stream.read",
+  "tag.read",
+  "teams-cds-compute-account.read",
+  "teams-connector-cloudflared.monitoring",
+  "teams-connector-cloudflared.read",
+  "teams-connector-warp.read",
+  "teams-connectors.read",
+  "teams-dex.read",
+  "teams-networks.read",
+  "teams-pii.read",
+  "teams-resilience.read",
+  "teams.read",
+  "teams.report",
+  "transform-rules.read",
+  "trust-and-safety.read",
+  "url-scanner.read",
+  "user-details.read",
+  "vectorize.read",
+  "waiting-rooms.read",
+  "web3-hostnames.read",
+  "websearch.metadata_read",
+  "websearch.read",
+  "workers-ci.read",
+  "workers-kv-storage.metadata_read",
+  "workers-kv-storage.read",
+  "workers-observability.read",
+  "workers-r2-bucket-item.read",
+  "workers-r2.metadata_read",
+  "workers-r2.read",
+  "workers-routes.read",
+  "workers-scripts.metadata_read",
+  "workers-scripts.read",
+  "workers-tail.read",
+  "workers_ai.metadata_read",
+  "zaraz.read",
+  "zone-access.read",
+  "zone-custom-asset.read",
+  "zone-disable-esc.read",
+  "zone-dns-settings.read",
+  "zone-observability.read",
+  "zone-security-center-insights.read",
+  "zone-security-center-partner-assets.read",
+  "zone-settings.read",
+  "zone-transform-rules.read",
+  "zone-versioning.read",
+  "zone-waf.read",
+  "zone.read",
+] as const;
+
+/** Reads excluded from `CLOUDFLARE_READ_SCOPES`: none — `CLOUDFLARE_READ_SCOPES` matches
+ *  Cloudflare MCP's full "Read only" template so the consent page shows standard read-only access. */
+export const CLOUDFLARE_READS_LEFT_OUT: Record<string, string> = {};
+
+/** How the secret's facet re-mints an expired credential, in its own trusted code: the
+ *  exchange reads this secret's own material, POSTs to an endpoint within the pin, and writes the
+ *  answer back into the material — `accessToken` (and a rotated `refreshToken`). Triggered on a 401
+ *  from the pinned host, and on first use when the placeholder's field is not there yet. An OAuth
+ *  token whose endpoint said when it ends (`expires_in`, kept in the material as
+ *  `accessTokenExpiresAt`) is also refreshed once that time has come, before the request goes:
+ *  not every provider answers an ended token with 401. */
+export type SecretRefresh =
+  /** RFC 6749 §6, the refresh_token grant: `refreshToken` + `clientId` (+ `clientSecret` for a
+   *  confidential client) from the material → `accessToken` (+ the newest `refreshToken`). Google,
+   *  GitHub, an MCP server's authorization server, the petshop fixture. With `client`, the client is
+   *  the deployment's own app at the provider (an integration connected through it): the material
+   *  holds the tokens alone, and the refresh attaches the client's credentials inside the facet. */
+  | {
+      kind: "oauth-refresh-token";
+      tokenEndpoint: string;
+      clientAuth?: ClientAuth;
+      /** The grant's scope ceiling (`SecretOAuthOptions.grantedWithin`), within the vault's own for
+       *  the provider: a refresh whose answer names a scope outside it, or names none, is refused,
+       *  and the new tokens are not kept. */
+      grantedWithin?: string[];
+      /** RFC 8707: the resource the grant is for (an MCP server's URL), as the authorization
+       *  request named it in `extra.resource`. Each refresh sends it again: an issuer that serves
+       *  more than one resource picks its authorization server by it. */
+      resource?: string;
+      /** `cloud`: the client is that of the iterate Cloud at `origin`, and `tokenEndpoint` is that
+       *  Cloud's broker, which adds the client secret. The refresh token in the material is sealed
+       *  for this deployment and means nothing anywhere else. `stack`: the stack's former client
+       *  at Cloudflare (`StackClientName`): such a grant no longer refreshes. */
+      client?: { platform: IntegrationProvider } | CloudClientName | StackClientName;
+    }
+  /** A GitHub App installation's token (`POST <apiOrigin>/app/installations/<id>/access_tokens`
+   *  with an App JWT) → `accessToken`, minted on first use and on a 401. The App is iterate Cloud's
+   *  (`{ cloud, origin }`) or one whose `appId` and `privateKey` the material holds (`{ mind: "github" }`,
+   *  and `{ platform: "github" }` the same way); either of those two fields may be a
+   *  `getSecret("/secrets/<name>", { field })` placeholder naming another of the owner's secrets
+   *  pinned to `apiOrigin`, so one secret holding the App's key serves every installation's
+   *  secret. */
+  | {
+      kind: "github-app-installation";
+      apiOrigin: string;
+      installationId: string;
+      /** `cloud`: the GitHub App of that name of the iterate Cloud at `origin`, whose key stays
+       *  at the Cloud. The Cloud mints the token, for an installation this deployment connected.
+       *  The Cloud mints no token for a secret whose `urls` go beyond the hosts the Cloud names
+       *  for the App. */
+      client: { platform: "github" } | { mind: "github" } | CloudClientName;
+    }
+  /** EXCHANGE CODE: `source` is one ES module exporting `async function exchange(material, fetch)`,
+   *  which logs in (any vendor's shape: a CSRF form and its cookie, a GraphQL mutation) and returns
+   *  the NEXT material — keep what the next login needs (`{ ...material, accessToken }`). It runs
+   *  only on first use and on a 401, in a jail the secret's facet loads: no bindings, `fetch` (the
+   *  argument and the global alike) reaches the secret's pinned origins and nothing else — a
+   *  request anywhere else fails the refresh — and `console` is silenced. Only the returned object
+   *  is kept. The source is part of the record, so changing it is a `set` like the material's. */
+  | { kind: "worker"; source: string };
+
+/** A secret's catalog entry — `secrets.list()` — its path, the pin, the strategy's KIND, when it
+ *  was first set and its public fields; never a secret value (the owner root's fold of the
+ *  `secret/set` certificates). */
+export type SecretCatalogEntry = {
+  path: string;
+  urls: string[];
+  refresh?: SecretRefresh["kind"];
+  /** The iterate Cloud's client that brokers the secret's refresh (`refresh.client.cloud`): an
+   *  account that a member connected through iterate's own app at a provider. */
+  cloud?: string;
+  /** That Cloud's origin (`refresh.client.origin`), which the secret has kept since it was made. */
+  cloudOrigin?: string;
+  /** For exchange code (`refresh.kind` "worker"): the SHA-256 of its source, hex — which code it is. */
+  refreshSourceSha256?: string;
+  createdAt: string;
+  /** The material's public fields (`set`'s `public`, a collection form's public parts), by name:
+   *  an OAuth client's `clientId` beside the secret that holds its `clientSecret`. */
+  public?: Record<string, string>;
+  proxy?: SecretProxy;
+  /** A path that forwards every use to a secret elsewhere, as a lend of the old platform left it:
+   *  whose, under which lend, and the connection it is. packages/mind-backup reads it. */
+  borrowed?: {
+    lendId: string;
+    lender: { userId: string; email?: string } | { instance: true };
+    integration?: { provider: string; account: string; externalId: string };
+  };
+};
+
+/** THE OPERATIONS a secret may answer, the vault used as a signer: none unless the secret is made
+ *  with them (`SecretUses.operations`). */
+export const SECRET_OPERATIONS = [
+  "signHmac",
+  "verifyHmac",
+  "verifyEquals",
+  "deriveSharedSecret",
+  "publicKeyOf",
+  "signWithKey",
+  "signStatement",
+  "seal",
+  "unseal",
+] as const;
+export type SecretOperation = (typeof SECRET_OPERATIONS)[number];
+
+/** ONE FIELD OF ONE REQUEST'S JSON BODY THAT A SECRET'S VALUE MAY GO INTO (`SecretUses.bodyFields`):
+ *  the request's method, its exact URL (https, with no query, at an origin of the secret's `urls`),
+ *  and the dotted name of a string field of the body's JSON object.
+ *  `{ method: "POST", url: "https://api.example.com/v1/sinks", field: "config.token" }` */
+export type SecretBodyField = { method: string; url: string; field: string };
+
+/** WHAT A SECRET MAY BE USED FOR, fixed when it is made, kept by the secrets Worker and shown to the
+ *  person who gives it on the collection form or the OAuth start page: the mind's code cannot
+ *  widen it later. */
+export type SecretUses = {
+  /** Where its placeholder may sit in a request: in a header (`"header"`, the default; a `Basic`
+   *  credential is a header), or also in the URL (`"url"`, a Telegram bot token in the path). */
+  placement?: "header" | "url";
+  /** The fields of JSON request bodies that its value may also go into, for an API that takes a
+   *  token as a field: none by default, ten at most. In a request with that method to that URL,
+   *  the placeholder as the WHOLE value of that field is filled:
+   *  `JSON.stringify({ config: { token: 'getSecret("/secrets/<name>")' } })`. The request names
+   *  the secret in a header too, which is how it reaches the secrets Worker. Such a request has a
+   *  JSON body (`content-type: application/json`, UTF-8, at most 1 MiB) with the placeholder at
+   *  one of those fields, or it is refused. The body is parsed and written again with the field
+   *  set: its keys keep the order of the parse, of a key written twice the last one stays, a
+   *  number that a double does not hold exactly changes, and one beyond a double's range leaves
+   *  as `null`. Its content type leaves as the one JSON type that it names, with no parameter.
+   *  So a caller that signs its body cannot use this. Nothing else is read: a placeholder at
+   *  another place of that body, or in the body of any other request, leaves as written. The
+   *  method and the URL are the request's as it is written: one with a query, with a header
+   *  that names another method, or with a placeholder in its URL is another request. The fields
+   *  are fixed when the value is given: to change them, give it again.
+   *  A WEAKER USE THAN A HEADER: a secret that is sent in a body is NOT kept from this mind's own
+   *  code if that service shows it back, in an answer to this secret or to another one. So give
+   *  such a secret only the reach that you would give the mind itself. The rest of the body and
+   *  the headers are the caller's too: they can tell the service what to do with the value, or
+   *  which endpoint to take the request for. Where the secret has an approval rule, a request
+   *  whose body is filled waits for a member, whatever the rule names. An approval is for the
+   *  value that the secret holds then: when the secret is given again, each request that waits
+   *  or was approved to fill a body ends, and the same request, sent again, waits anew. */
+  bodyFields?: SecretBodyField[];
+  /** The operations it answers (`SECRET_OPERATIONS`). Default: none. */
+  operations?: SecretOperation[];
+  /** The secrets whose refresh may borrow its material, by path: as a client secret or a GitHub
+   *  App's key that their refresh names with `getSecret("/secrets/<name>", { field })`. Default:
+   *  none. `null`: every secret of the mind, for a client secret whose accounts' paths are not
+   *  known when it is made; it is what `describe` answers for such a secret. */
+  lendTo?: string[] | null;
+  /** For `signStatement`: the paths a statement it signs may name, each with everything under it
+   *  (`["/integrations/"]`). Default: any path. */
+  statementPaths?: string[];
+};
+
+/** What `secrets.signStatement(path, input)` signs: a statement to the mind at `mind` (its domain),
+ *  for the context at `path`, of `type`, ending `expiresInSeconds` from now (default 300, at most a
+ *  day, the most a mind takes). The secrets Worker adds `at` and the nonce. */
+export type SecretStatementSigning = {
+  mind: string;
+  path: string;
+  type: string;
+  payload?: Record<string, unknown>;
+  about?: string[];
+  expiresInSeconds?: number;
+};
+
+/** The input an agent gives `itx.secrets.collectFromUser`: the write-only secret path, the
+ * origins its material may reach, what the collection page shows the person, and, for a secret of
+ * several parts, one field each. `description` is markdown: say where the value comes from, with
+ * links (they open in a new tab). */
+export type CollectSecretInput = {
+  path: string;
+  egress: { urls: string[] };
+  description?: string;
+  /** One input per field, saved as one JSON secret `{ [name]: value }`, whose parts are then
+   *  `getSecret(path, { field: name })`: an OAuth app's `clientSecret` (which `beginOAuth` takes as
+   *  a placeholder), a webhook's `signingSecret`. Without it, one Value. */
+  fields?: CollectSecretField[];
+  /** Where the page sends the person once the secret is saved, as an OAuth redirect does: an
+   *  absolute http(s) URL without credentials, such as the mind's page that asked. The page
+   *  shows its host before the person saves. Without it, the page says the tab can close. */
+  redirectUrl?: string;
+  /** Whoever holds the link may fill the form, signed in or not; the page says so. Without it, only
+   *  a member of the mind, signed in. */
+  anyoneWithLink?: boolean;
+} & SecretUses;
+
+/** One part of a secret a collection page asks for: its name in the JSON secret
+ *  (`[A-Za-z_][A-Za-z0-9_]*`), the label the person reads, whether its value is several lines
+ *  (a PEM private key), and whether it is PUBLIC. A public part is no secret (an OAuth client's
+ *  ID, a GitHub App's ID and slug): it is entered on the same form as the parts that are, and the
+ *  catalog answers its value (`SecretCatalogEntry.public`), so the code that needs it reads it
+ *  there and keeps no copy. `placeholder` and `pattern` are the input's (HTML's `pattern`
+ *  attribute: the whole value must match; it is compiled with the `v` flag). */
+export type CollectSecretField = {
+  name: string;
+  label: string;
+  multiline?: boolean;
+  public?: boolean;
+  placeholder?: string;
+  pattern?: string;
+};
+
+/** A secret collection link. Sending this asks the person to authenticate to the intended
+ * Iterate instance; it is not itself permission to write a secret. */
+export type CollectSecretLink = { path: string; url: string };
+
+/** What `secrets.verifyHmac(path, input)` checks: the bytes the provider signed (a string is its
+ *  UTF-8 bytes), the hex HMAC-SHA256 it sent (either case, the scheme's prefix — `sha256=`, `v0=` —
+ *  stripped), and which field of a JSON material is the key (the whole material when omitted).
+ *  Stripe signs `${t}.${body}`, GitHub the body, Slack `v0:${t}:${body}`: the caller assembles them. */
+export type SecretHmacVerification = {
+  payload: string | Uint8Array;
+  signature: string;
+  field?: string;
+  derive?: SecretKeyDerivation;
+};
+
+/** A key derived from the secret's for one purpose, so one secret serves several (`signHmac`,
+ *  `verifyHmac`, `seal`, `unseal`): HKDF-SHA256 with an empty salt and `info`, 32 bytes, from a
+ *  signing secret's private scalar `d` (its P-256 JWK), else from the UTF-8 bytes of the string at
+ *  `field`. The iterate Cloud derives its proof key (`iterate-cloud/proof`) and its seal key
+ *  (`iterate-cloud/seal`) from its P-256 key this way. */
+export type SecretKeyDerivation = { info: string };
+
+/** What `secrets.seal(path, input)` seals: `plaintext` under AES-256-GCM, with the key derived for
+ *  `info` (`SecretKeyDerivation`). The answer is `sealed.<iv>.<ciphertext>`, each base64url. */
+export type SecretSealing = { info: string; plaintext: string; field?: string };
+
+/** What `secrets.unseal(path, input)` opens: a `seal` answer under the same `info`. */
+export type SecretUnsealing = { info: string; sealed: string; field?: string };
+
+/** What `secrets.signHmac(path, input)` signs: the bytes to sign (a string is its UTF-8 bytes),
+ *  which field of a JSON material is the key (the whole material when omitted), and how the
+ *  signature is written: `hex` (the default) or `base64`. X's webhook check wants
+ *  `sha256=<base64>` of its `crc_token`. */
+export type SecretHmacSigning = {
+  payload: string | Uint8Array;
+  field?: string;
+  encoding?: "hex" | "base64";
+  derive?: SecretKeyDerivation;
+};
+
+/** What `secrets.verifyEquals(path, input)` checks: the candidate string a request presented (a
+ *  static header token, say), and which field of a JSON material is the secret (the whole
+ *  material when omitted). */
+export type SecretEqualsVerification = {
+  value: string;
+  field?: string;
+};
+
+/** EVERY PROVIDER AN INTEGRATION CONNECTS, spelled once: a connection to one is the log
+ *  `/integrations/<provider>/<connection>` and the secret `/secrets/<provider>-<connection>`. The
+ *  kinds below are read off it. */
+export const INTEGRATION_PROVIDERS = ["slack", "google", "cloudflare", "github", "x"] as const;
+export type IntegrationProvider = (typeof INTEGRATION_PROVIDERS)[number];
+
+/** Each provider's name as a person reads it, wherever a page or a message names one. */
+export const INTEGRATION_PROVIDER_NAMES = {
+  slack: "Slack",
+  google: "Google",
+  cloudflare: "Cloudflare",
+  github: "GitHub",
+  x: "X",
+} as const satisfies Record<IntegrationProvider, string>;
+
+/** The providers a person signs in with, each through iterate's app there. */
+export type SignInProvider = Exclude<IntegrationProvider, "slack" | "x">;
+
+/** Whose OAuth app a secret's `beginOAuth` goes through when it is not a client passed in the
+ *  clear: one of an iterate Cloud's by its name there (`github`, `google`, `x`) and that Cloud's
+ *  `origin` (`CloudClientName`), the app every deployment shares. The Cloud keeps that app's secret and
+ *  adds it to the exchange and to each refresh; the tokens stay in this secret. */
+export type SecretOAuthClient = CloudClientName & {
+  /** For a GitHub App of the Cloud's: the accounts (a person's or an organization's login)
+   *  whose installations this mind asks to be connected to. The member's consent reaches
+   *  every account they administer; the mind gets the events and the installation tokens
+   *  of these alone, and the Cloud's page names them before the member approves. With none
+   *  named it gets no installation, unless `install: true` sends the member to the App's
+   *  install page, where the one they choose is connected. */
+  accounts?: string[];
+};
+
+/** What `secrets.beginOAuth(path, options)` takes: the provider's two endpoints, the OAuth client
+ *  (the mind's own in the clear, or an integration's `client`), the scope, the pin, and any extra
+ *  authorize parameters the provider needs (Google: `access_type=offline`, `prompt=consent`). */
+export type SecretOAuthOptions = {
+  /** The provider's two endpoints. Absent with a Cloud client, which names them, the client's id
+   *  and the pin itself. */
+  authorizationEndpoint?: string;
+  tokenEndpoint?: string;
+  /** Exactly one of `clientId` and `client`. */
+  clientId?: string;
+  /** Absent for a public client (PKCE alone), and with `client`. The secret itself, or one
+   *  placeholder naming the secret that holds it — `getSecret("/secrets/<name>")`, or
+   *  `getSecret("/secrets/<name>", { field: "a.b" })` — so it never passes through your hands:
+   *  collect it with `collectFromUser` into a secret pinned to the token endpoint's origin. The
+   *  platform reads it from there at the code exchange and at every refresh, and stores only the
+   *  placeholder, so rotating that secret takes effect at the next refresh. `beginOAuth` refuses
+   *  a placeholder that names no such secret. */
+  clientSecret?: string;
+  client?: SecretOAuthClient;
+  /** With a GitHub App of the Cloud's: the member goes to the App's install page first, and the
+   *  installation they choose there is connected. */
+  install?: boolean;
+  /** Where the platform's callback sends the human once the tokens are stored: an absolute URL on
+   *  a hostname of the mind's zones (a page of the mind's own is
+   *  `await itx.url({ hostname, path })`). That page reads what the consent granted with
+   *  `oauthResult`. Every attempt comes back to the platform's callback first
+   *  (`oauthCallbackUrl`, the redirect URI to register for a client of your own), which completes
+   *  it only in the browser that opened the start link. */
+  next?: string;
+  /** The one person who may complete the attempt, by their user id (`user_…`), when they need not
+   *  reach this secret's owner: a customer of the mind's own app connecting their own account,
+   *  whom the mind knows from a sign-in with this platform. The platform's callback then
+   *  completes the attempt only in a browser signed in as that person, in place of one that reaches
+   *  the owner; a member who is not that person is refused like anyone else. Only for a mind's
+   *  secret, and only with a client of your own (`clientId`): the deployment's app is consented to
+   *  by someone who reaches the owner. */
+  completedByUserId?: string;
+  /** How the token endpoint wants the client credential. */
+  clientAuth?: ClientAuth;
+  scope?: string;
+  /** THE SCOPE CEILING: every scope that the grant may hold. With it the platform keeps a grant
+   *  only when the token answer names the scopes it granted (`scope`) and each one is in the list:
+   *  an answer that names one outside it, or names none, is refused before anything is kept, and
+   *  the person's page says which scopes were too many. A refresh whose answer names a scope
+   *  outside it, or names none, is refused the same way. `scope` itself must be within it. Not
+   *  with `client`. THE VAULT'S OWN CEILING: for a provider that it holds to reads alone
+   *  (Cloudflare: `CLOUDFLARE_READ_SCOPES` and the three scopes that its MCP server adds), a
+   *  connect is held to that list with or without this one, and this one may only narrow it. */
+  grantedWithin?: string[];
+  /** RFC 7009's endpoint, within `urls`: a grant that the vault refuses (its ceiling, its account)
+   *  goes back there, its refresh token and its access token, and the `secret/grant-refused` fact
+   *  says whether the provider took them. */
+  revocationEndpoint?: string;
+  /** The origins the tokens may be sent to; defaults to the token endpoint's, which it must include. */
+  urls?: string[];
+  extra?: Record<string, string>;
+  /** The account the tokens must be for — an existing connection's, asked for more: the provider's
+   *  id for it (a Slack team, an OpenID `sub`), read off the token response, or off `account`'s
+   *  endpoint when given. Another account's tokens are refused before anything is stored. */
+  expectAccount?: string;
+  /** Where the provider names the account the new tokens are for, when its token response does
+   *  not (X; any provider without an ID token): a JSON endpoint within `urls`, which the secret's
+   *  facet calls once with the new access token before anything is stored, and the paths of the
+   *  account's id and, when it has one, its name (`data.id`, `data.username`). `completeOAuth`
+   *  answers the account, and `expectAccount` is checked against its id: another account, no
+   *  account, or an answer that is not 200 is refused, and nothing is kept. `method: "POST"` with
+   *  `body` (JSON) asks a JSON-RPC endpoint, such as an MCP server's `tools/call`. A step of a path
+   *  that ends in `@json` reads a string that holds JSON, as an MCP tool's text does:
+   *  `result.content.0.text@json.id`. Not with `client`: the deployment's app names its own
+   *  accounts. */
+  account?: { url: string; id: string; name?: string; method?: "GET" | "POST"; body?: unknown };
+  /** Whoever holds the start link may consent, signed in or not; the page says so. Without it, only
+   *  a member of the mind, signed in. */
+  anyoneWithLink?: boolean;
+  /** The start link goes straight to the provider, whose consent is then the one page the person
+   *  confirms on. Without it, the platform's page comes first and the person clicks Continue. That
+   *  page still comes first when the secret has an unusual use (`placement: "url"`, `bodyFields`,
+   *  `operations`, `lendTo`). With `client`, the Cloud's own page already comes in its place. */
+  straightToProvider?: boolean;
+} & SecretUses;
+
+/** An `R2Object` as `itx.r2` answers it: every field the class carries, as data — the key with the
+ *  owner prefix stripped, dates as ISO strings, checksums as hex. */
+export type R2ObjectRecord = {
+  key: string;
+  version: string;
+  size: number;
+  etag: string;
+  httpEtag: string;
+  checksums: Record<string, string>;
+  uploaded: string;
+  httpMetadata: R2HTTPMetadata;
+  customMetadata: Record<string, string>;
+  range?: R2Range;
+  storageClass: string;
+};
+
+/** A Browser Run quick-action name (`browser.quickAction`'s first argument): what to extract from
+ *  the rendered page — content, screenshot, PDF, markdown, accessibility snapshot, scraped elements,
+ *  structured JSON, links, or a crawl. */
+export type CfBrowserQuickAction =
+  | "content"
+  | "screenshot"
+  | "pdf"
+  | "markdown"
+  | "snapshot"
+  | "scrape"
+  | "json"
+  | "links"
+  | "crawl";
+
+/** Options for a Browser Run quick action: the target page as a `url` or as inline `html`, plus the
+ *  action's own pass-through options (e.g. `screenshotOptions`). */
+export type CfBrowserQuickActionOptions = Record<string, unknown> &
+  ({ url: string } | { html: string });
+
+/** What a browser session is acquired with: how long it lives idle (`keepAlive`, 10 seconds to 20
+ *  minutes, in milliseconds), whether it is recorded, the country its requests leave from (ISO
+ *  3166 alpha-2), and the hosts it may reach. */
+export type CfBrowserSessionOptions = {
+  keepAlive?: number;
+  recording?: boolean;
+  location?: string;
+  guardrails?: { allowedDomains?: string[]; allowedDomainSets?: string[] };
+};
+
+/** A tab (or worker, or frame) of a session's browser, as its DevTools endpoint lists it. */
+export type CfBrowserTarget = {
+  id: string;
+  type: string;
+  url: string;
+  title?: string;
+  description?: string;
+  webSocketDebuggerUrl?: string;
+  devtoolsFrontendUrl?: string;
+};
+
+/** A page a session has open, once it loaded (`loaded: false` when its load event did not arrive
+ *  in time: the page may still be usable). */
+export type CfBrowserPage = {
+  sessionId: string;
+  targetId: string;
+  url: string;
+  title: string;
+  loaded: boolean;
+};
+
+/** Which of a session's targets a call is for: the session's first page when omitted, and
+ *  `"browser"` for the browser's own endpoint (`Target.*`, `Browser.*`). `timeoutMs` bounds the
+ *  command (30 seconds when omitted). */
+export type CfBrowserCdpOptions = { targetId?: string; timeoutMs?: number };
+
+/** `itx.ai`: the Workers AI binding's methods under their own names and shapes, as far as a call
+ *  across RPC can carry them. No RPC carries a Blob, so a file for `toMarkdown` is its bytes; and a
+ *  method whose binding answers a Response (`websearch`, a gateway's `run`) answers that Response's
+ *  body. The binding's `aiSearch()` and `autorag(id)` are not here: Cloudflare deprecated both for
+ *  the `ai_search` bindings, and both reach every instance on the deployment's account. Nor is
+ *  `aiGatewayLogId`, which the binding sets after each `run` and so holds whichever call ended
+ *  last. */
+export type ItxAiApi = Pick<Ai, "run" | "models"> & {
+  /** Documents, spreadsheets, web pages and pictures as Markdown: Cloudflare's `toMarkdown`. One
+   *  file answers one result, a list a list; a file Cloudflare cannot convert answers
+   *  `format: "error"` in its place. With no files, the service, for `supported()`. */
+  toMarkdown(): ItxToMarkdownService;
+  toMarkdown(
+    files: ItxMarkdownDocument[],
+    options?: ConversionRequestOptions,
+  ): Promise<ConversionResponse[]>;
+  toMarkdown(
+    files: ItxMarkdownDocument,
+    options?: ConversionRequestOptions,
+  ): Promise<ConversionResponse>;
+  /** AI Gateway `gatewayId` on the deployment's account. */
+  gateway(gatewayId: string): ItxAiGateway;
+  /** Cloudflare's Web Search API through AI Gateway `gatewayId`, billed to that gateway's
+   *  credits (or a provider key stored on it): the answer's body. */
+  websearch(request: AiWebSearchRequest): Promise<ItxWebSearchAnswer>;
+};
+
+/** A file for `itx.ai.toMarkdown`: Cloudflare's `{ name, blob }` with what the Blob is made of in
+ *  place of the Blob, bytes or text (`new Blob([blob], { type })`), or `{ name, data }` with the
+ *  bytes in base64. `name`'s extension tells Cloudflare the format; `type` is
+ *  `application/octet-stream` when omitted. */
+export type ItxMarkdownDocument =
+  | { name: string; blob: Uint8Array | ArrayBuffer | string; type?: string }
+  | { name: string; data: string; type?: string };
+
+/** `itx.ai.toMarkdown()`: the binding's `ToMarkdownService`. */
+export type ItxToMarkdownService = {
+  transform(
+    files: ItxMarkdownDocument[],
+    options?: ConversionRequestOptions,
+  ): Promise<ConversionResponse[]>;
+  transform(
+    files: ItxMarkdownDocument,
+    options?: ConversionRequestOptions,
+  ): Promise<ConversionResponse>;
+  supported(): Promise<SupportedFileFormat[]>;
+};
+
+/** `itx.ai.gateway(id)`: the binding's `AiGateway`. `run` is the gateway's universal endpoint and
+ *  answers the provider's body: parsed JSON, text, or bytes. `getLog` and `patchLog` take a log's
+ *  id as the gateway's log list shows it; a gateway may log other minds' calls too, so nothing
+ *  here lists them. */
+export type ItxAiGateway = {
+  getLog(logId: string): Promise<AiGatewayLog>;
+  patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;
+  getUrl(provider?: string): Promise<string>;
+  run(
+    data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
+    options?: { gateway?: UniversalGatewayOptions; extraHeaders?: object },
+  ): Promise<unknown>;
+};
+
+/** What `itx.ai.websearch` answers: the Web Search API's JSON. A result carries more fields when its
+ *  provider gives them (Exa: `imageUrl`, `lastModifiedDate`). */
+export type ItxWebSearchAnswer = {
+  items: ({ url: string; title: string; description?: string } & Record<string, unknown>)[];
+  metadata: { query: string; requestId: string; latencyMs: number } & Record<string, unknown>;
+};
+
+/** `itx.browser`: Cloudflare Browser Run.
+ *
+ *  ONE-SHOT: `quickAction` renders a page and answers the action's RESULT (a string, parsed JSON, or
+ *  bytes for a screenshot or a PDF), not the binding's `{ success, result }` envelope; a failed
+ *  action throws.
+ *
+ *  A SESSION is a browser that stays open between calls, with its pages, cookies and sign-ins:
+ *  `openPage({ url })` starts one and answers once the page loaded, `cdp(sessionId, method, params)`
+ *  runs one Chrome DevTools Protocol command on it (read with `Runtime.evaluate`, click by
+ *  evaluating a script, type with `Input.insertText`, picture with `Page.captureScreenshot`),
+ *  `navigate` loads another URL in the same page, and `closeSession` ends it. A session left open
+ *  is billed until its `keepAlive` runs out. Every session call names a session by the id
+ *  `openPage` or `acquire` answered, which is the capability: nothing here lists sessions.
+ *
+ *  `fetch` is the binding's raw endpoint, for a library that speaks CDP itself. */
+export type CfBrowserApi = {
+  fetch(input: Request | string | URL, init?: RequestInit): Promise<Response>;
+  quickAction(action: CfBrowserQuickAction, options: CfBrowserQuickActionOptions): Promise<unknown>;
+  /** A new session with `url` open in its page. `keepAlive` is five minutes when omitted. */
+  openPage(input: { url: string } & CfBrowserSessionOptions): Promise<CfBrowserPage>;
+  /** Another URL in a session's page (the first page, or `targetId`'s). */
+  navigate(sessionId: string, url: string, options?: CfBrowserCdpOptions): Promise<CfBrowserPage>;
+  /** One CDP command on a session's page, answered with the command's result. A CDP error throws. */
+  cdp(
+    sessionId: string,
+    method: string,
+    params?: Record<string, unknown>,
+    options?: CfBrowserCdpOptions,
+  ): Promise<unknown>;
+  /** The binding's own `acquire`: a session with a blank page, and `targets` when asked for. */
+  acquire(
+    options?: CfBrowserSessionOptions & { targets?: boolean; liveViewUrlExpiresInMs?: number },
+  ): Promise<{ sessionId: string; targets?: CfBrowserTarget[] }>;
+  /** The session's times and state, or null when there is no such session. */
+  getSession(sessionId: string): Promise<Record<string, unknown> | null>;
+  closeSession(sessionId: string): Promise<{ status: "closing" | "closed" }>;
+  /** A link a person opens to watch (or, without `guardrails`, drive) the session. The link is a
+   *  credential. */
+  getLiveView(
+    sessionId: string,
+    options?: {
+      mode?: "devtools" | "tab" | "full";
+      targetId?: string;
+      expiresInMs?: number;
+      guardrails?: { mode: "readonly" };
+    },
+  ): Promise<{ webSocketDebuggerUrl: string; devtoolsFrontendUrl: string; id: string }>;
+  /** How many sessions the account may run and is running, and when the next may start. */
+  limits(): Promise<{
+    activeSessions: number;
+    maxConcurrentSessions: number;
+    allowedBrowserAcquisitions: number;
+    timeUntilNextAllowedBrowserAcquisition: number;
+    usedBrowserTimeSeconds?: number;
+  }>;
+  /** A session's tabs: list them, open one, bring one to the front, close one. */
+  devtools: {
+    getVersion(sessionId: string): Promise<Record<string, unknown>>;
+    listTargets(sessionId: string): Promise<CfBrowserTarget[]>;
+    getTarget(sessionId: string, targetId: string): Promise<CfBrowserTarget>;
+    newTarget(sessionId: string, url?: string): Promise<CfBrowserTarget>;
+    activateTarget(sessionId: string, targetId: string): Promise<{ message: string }>;
+    closeTarget(sessionId: string, targetId: string): Promise<{ message: string }>;
+  };
+};
+
+/** Where an `itx.images` image comes from: its bytes, a `ReadableStream` of them, an http(s) URL
+ *  (fetched by the platform through the mind's egress, so the bytes never visit you), a mind
+ *  file's path (`"/images/photo.jpg"`), or a file handle (`itx.files.get(path)`). A script uses the
+ *  path: its `itx.files.get(path)` is a promise it must `await` before it can pass the handle on.
+ *  At most 20 MB, the Images binding's own limit. */
+export type CfImageSource =
+  | Uint8Array
+  | ArrayBuffer
+  | ReadableStream<Uint8Array>
+  | string
+  | URL
+  | Pick<FileHandle, "bytes">;
+
+/** A file `itx.images` writes into: its path (`"/images/small.jpg"`) or `itx.files.get(path)`. */
+export type CfImagesFile = Pick<FileHandle, "put"> | string;
+
+/** What `itx.images.input(…)` and `.text(…)` answer, and every `.transform(…)` and `.draw(…)` on it:
+ *  the Images binding's `ImageTransformer`, a plan nothing has run yet. `draw`'s overlay is any
+ *  `CfImageSource`. Chain freely: `input(x).transform(a).output(o).response()` is one round trip. */
+export type CfImageTransformer = {
+  transform(transform: ImageTransform): CfImageTransformer;
+  draw(image: CfImageSource, options?: ImageDrawOptions): CfImageTransformer;
+  output(options: ImageOutputOptions): Promise<CfImageTransformationResult>;
+};
+
+/** The binding's `ImageTransformationResult`. The image is made when `response`, `image` or
+ *  `writeTo` runs (and again each time you call one, which Images bills once per unique image and
+ *  parameters per month); `contentType` is the output format and runs nothing. */
+export type CfImageTransformationResult = {
+  response(options?: ImageTransformationResponseOptions): Promise<Response>;
+  contentType(): Promise<string>;
+  image(options?: ImageTransformationOutputOptions): Promise<ReadableStream<Uint8Array>>;
+  /** The image into a file, without visiting the caller; answers the stored file's record. */
+  writeTo(file: CfImagesFile): Promise<FileRecord>;
+};
+
+/** `itx.images`: the Cloudflare Images binding (`env.IMAGES`), same method names and options, over
+ *  `CfImageSource`s. `info` is free; every unique transformation is billed once a month. Not wrapped
+ *  yet: `hosted`. A caller's non-image fails as `INVALID_INPUT`. */
+export type CfImagesApi = {
+  info(image: CfImageSource, options?: ImageInputOptions): Promise<ImageInfoResponse>;
+  input(image: CfImageSource, options?: ImageInputOptions): CfImageTransformer;
+  text(content: string, options: TextOptions): CfImageTransformer;
+};
+
+/** A token for an Artifacts repo's git remote. `id` names it to `revokeToken` and in
+ *  `listTokens`, and opens nothing. */
+export interface ArtifactToken {
+  id?: string;
+  plaintext: string;
+  expiresAt?: string;
+}
+
+/** What Artifacts says of a token after the mint: never its text. */
+export interface ArtifactTokenInfo {
+  id: string;
+  scope: "read" | "write";
+  state: "active" | "expired" | "revoked";
+  createdAt: string;
+  expiresAt: string;
+}
+
+/** `itx.cfArtifacts.get(path)`: the repo's handle — a token for its remote, the tokens that
+ *  Artifacts has for it, and the remote's git-over-HTTPS URL. A repo that does not exist fails at
+ *  these, with the binding's own error. */
+export interface CfArtifactRepoApi {
+  createToken(scope: "read" | "write", ttlSeconds: number): Promise<ArtifactToken>;
+  /** The tokens of this repo that still open it, with no token's text. One that ended, by its
+   *  date or by `revokeToken`, is not listed. */
+  listTokens(): Promise<{ tokens: ArtifactTokenInfo[]; total: number }>;
+  /** Ends one token of this repo, by its id. A token's text is refused: pass none, a script's
+   *  source is on its caller's log. True also for a token that has ended already; false when the
+   *  repo never had a token of that id. */
+  revokeToken(id: string): Promise<boolean>;
+  remote(): Promise<string>;
+}
+
+/** `itx.cfArtifacts`: Cloudflare Artifacts, mind-scoped and addressed BY THE REPO'S PATH — the
+ *  binding's own verbs. `repos` is the friendlier surface. */
+export interface CfArtifactsApi {
+  /** The Artifacts repo, `main` unborn until the first commit; false when it already existed. */
+  create(path: string): Promise<{ created: boolean }>;
+  get(path: string): Promise<CfArtifactRepoApi>;
+  /** This mind's repos, as paths (one page). */
+  list(options?: { limit?: number; cursor?: string }): Promise<{
+    repos: { path: string }[];
+    cursor?: string;
+  }>;
+  /** True when the repo existed; false when it was already gone. */
+  delete(path: string): Promise<boolean>;
+}
+
+/** `connectToMcp`'s options: headers every request carries (`getSecret(…)` placeholders substitute
+ *  at egress). A CREDENTIAL NAMES A SECRET, AND NOTHING BESIDE IT:
+ *  `{ authorization: 'Bearer getSecret("/secrets/x")' }`, and each pair of a `cookie` likewise.
+ *  A connection with a credential that is written out, in a header or in its address, works for
+ *  one script, and the context follows nothing up for it: a subscription is not renewed
+ *  (`McpSubscription.notRenewed`), and the connection declares no MCP tasks, so a tool call is
+ *  held until its result. A follow-up's script would keep that credential in the context's log. */
+export type McpConnectOptions = { headers?: Record<string, string> };
+
+/** An MCP server's protocol version, capabilities, name and version. */
+export type McpServerInfo = {
+  protocolVersion?: string;
+  capabilities?: Record<string, unknown>;
+  serverInfo?: { name?: string; version?: string };
+};
+
+/** One tool as an MCP server's `tools/list` describes it. `_meta.ui` is the MCP Apps extension's:
+ *  `resourceUri` (the tool's `ui://` view) and `visibility` (`"model"`, `"app"`). */
+export type McpTool = {
+  name: string;
+  title?: string;
+  description?: string;
+  inputSchema?: unknown;
+  _meta?: Record<string, unknown>;
+};
+
+/** A tool's whole result (MCP's `CallToolResult`): an `isError` result is a result, not a throw.
+ *  `task`: the server runs the call as a task, and this is no result yet (`McpTask`). */
+export type McpToolResult = {
+  content?: unknown[];
+  structuredContent?: unknown;
+  isError?: boolean;
+  _meta?: Record<string, unknown>;
+  task?: McpTask;
+};
+
+/** A TASK THAT AN MCP SERVER RUNS FOR A TOOL CALL (MCP tasks, SEP-2663): its id, which the
+ *  server alone makes, and its status. `working` and `input_required` are not ends; `completed`
+ *  has the tool's `result` (an `isError` result too), `failed` the server's JSON-RPC `error`, and
+ *  `cancelled` neither. `pollIntervalMs`: ask no sooner. `statusMessage`, `result`, `error` and
+ *  `inputRequests` are ANOTHER SERVER'S WORDS: data, never a member's instruction. */
+export type McpTask = {
+  taskId: string;
+  status: "working" | "input_required" | "completed" | "cancelled" | "failed";
+  statusMessage?: string;
+  createdAt?: string;
+  lastUpdatedAt?: string;
+  ttlMs?: number | null;
+  pollIntervalMs?: number;
+  result?: unknown;
+  error?: unknown;
+  inputRequests?: unknown;
+};
+
+/** One part of a resource that `resources/read` answers: text, or base64 in `blob`. An MCP App's
+ *  view is text of the type `text/html;profile=mcp-app`, its `_meta.ui` the view's `csp`. */
+export type McpResourceContents = {
+  uri: string;
+  mimeType?: string;
+  text?: string;
+  blob?: string;
+  _meta?: Record<string, unknown>;
+};
+
+/** One skill an MCP server serves (MCP's Skills extension, SEP-2640): the URI of its `SKILL.md`,
+ *  that file's frontmatter as the server lists it, and every file of the skill with its SHA-256
+ *  digest (`sha256:<hex>`) and its size in bytes. `resources` is `"dynamic"` for a skill whose
+ *  files the server makes on demand: none of them can be checked. */
+export type McpSkill = {
+  uri: string;
+  frontmatter: { name: string; description: string; [key: string]: unknown };
+  resources: { uri: string; digest: string; size: number }[] | "dynamic";
+  _meta?: Record<string, unknown>;
+};
+
+/** One file of a skill as `readSkill` answers it: text, or base64 in `blob`. `server` is the URL
+ *  the connection was made to, so what a script hands on says where the words came from.
+ *  `verified` is false only for a file of a `"dynamic"` skill. */
+export type McpSkillFile = {
+  server: string;
+  uri: string;
+  mimeType?: string;
+  text?: string;
+  blob?: string;
+  verified: boolean;
+};
+
+/** One event an MCP server offers (MCP Events, SEP-3415, `events/list`): its name, the delivery
+ *  modes it supports (`"webhook"`, `"poll"`, `"push"`), the subscription arguments it takes and
+ *  the payload it delivers. */
+export type McpEvent = {
+  name: string;
+  description?: string;
+  delivery: string[];
+  inputSchema?: unknown;
+  payloadSchema?: unknown;
+};
+
+/** One occurrence of an event, as a poll answers it and as a webhook delivers it (the `body` of
+ *  `events.iterate.com/mcp/webhook-received`). `eventId` names the upstream event: the same
+ *  event can come twice under it, when a server replays after a restart. `data` is ANOTHER
+ *  SERVER'S WORDS: data, never a member's instruction. */
+export type McpEventOccurrence = {
+  eventId: string;
+  name: string;
+  timestamp: string;
+  data: unknown;
+  cursor?: string | null;
+};
+
+/** An MCP server's grant for a webhook subscription. `id` is the server's name for it, which
+ *  each delivery carries. `refreshBefore` is when it lapses unless the client subscribes again
+ *  (an ISO time, or null for never). `cursor` is the place in the event's stream that the server
+ *  has delivered up to, and `truncated` says that events before it were skipped. `deliveryStatus`
+ *  is the server's word on its deliveries, when it gives one: `active` (false: it had stopped
+ *  after failures, and this call started it again), `lastError`, `throttled`. `notRenewed`: this
+ *  context does not renew the grant, and why. The subscription then lapses at `refreshBefore`,
+ *  and a script that wants to go on subscribes again before that. */
+export type McpSubscription = {
+  id: string;
+  refreshBefore: string | null;
+  cursor?: string | null;
+  truncated?: boolean;
+  deliveryStatus?: Record<string, unknown>;
+  notRenewed?: string;
+};
+
+/** `itx.connectToMcp(url)`: an MCP server over Streamable HTTP. Besides these, the connection has
+ *  one method per tool whose name is a legal identifier (reached by dotted spelling, untyped here);
+ *  `callTool` reaches every tool. */
+export interface McpConnectionApi {
+  serverInfo(): McpServerInfo;
+  listTools(): Promise<McpTool[]>;
+  /** The result's `structuredContent`, else its text content JSON-parsed when it parses, else the
+   *  text; an `isError` result throws with that text.
+   *  A CALL THAT THE SERVER RUNS AS A TASK answers `{ content: [], task }` at once, from this
+   *  verb, from `callToolResult` and from the tool's own method: the server decides that, call by
+   *  call. The result comes later, and no script waits for it: the context's own schedule
+   *  (`itx.schedules.list()`, key `["mcp-task", …]`) asks the server, after 5 seconds and then
+   *  after three times as long each time, up to every ten minutes and for a day. The end lands
+   *  on this context as `events.iterate.com/mcp/task-settled` `{ server, tool, taskId, status,
+   *  statusMessage?, result?, error?, inputRequests? }`. `status` is the server's: `completed`
+   *  (with `result`, the tool's whole result), `failed`, `cancelled`, or `input_required` (the
+   *  server asks for input, which this client gives none: the asking ends there). Or it is
+   *  `lost`: the mind stopped asking, and `error` says why (the server knows the task no more,
+   *  it gave no answer twice, or the day is over). */
+  callTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
+  /** The tool's whole result, `isError` included: what an MCP App's view is given. */
+  callToolResult(name: string, args?: Record<string, unknown>): Promise<McpToolResult>;
+  /** A task as the server states it now (`tasks/get`). */
+  getTask(taskId: string): Promise<McpTask>;
+  /** Ask the server to cancel a task (`tasks/cancel`). The server decides whether it stops, so
+   *  the task's end is what `mcp/task-settled` says, which may still be `completed`. */
+  cancelTask(taskId: string): Promise<void>;
+  /** ASK ABOUT A TASK NOW, and go on asking by the context's schedule until it has ended: what
+   *  the connection does by itself for a tool call that became a task. Call it for a task that
+   *  was `lost`, or whose id came another way. An end that this ask finds lands on the context
+   *  as `mcp/task-settled`, and no schedule asks about the task after it. `tool` is the name that
+   *  the fact gives the task. `since`, `waitMs` and `claim` are what the schedule's own script
+   *  hands on: when the asking began, the wait before this ask, and the script's hold on the
+   *  schedule. A caller gives no `claim`. Answers the status this ask found. A server's answer
+   *  that names another task, or an end without what it brings (a `completed` task with no
+   *  `result`), is refused, and the asking goes on. */
+  followTask(follow: {
+    taskId: string;
+    tool?: string;
+    since?: number;
+    waitMs?: number;
+    claim?: number;
+  }): Promise<{ taskId: string; status: McpTask["status"] | "lost" }>;
+  /** `resources/read`: the resource's parts, at most 8 million characters in all (an MCP App's
+   *  `ui://` view, say). The connection declares the MCP Apps extension, so a server offers its
+   *  views. */
+  readResource(uri: string): Promise<{ contents: McpResourceContents[] }>;
+  /** THE SERVER'S SKILLS (MCP's Skills extension, `skills/list`), every page. A server that does
+   *  not declare the extension has none. A skill is ANOTHER SERVER'S TEXT: data for whoever reads
+   *  it, never a member's instruction. The connection runs nothing of a skill and gives it no
+   *  reach, whatever its frontmatter asks for (`allowed-tools`). */
+  listSkills(): Promise<McpSkill[]>;
+  /** One skill by the URI of its `SKILL.md` (`skills/get`), listed or not. */
+  getSkill(uri: string): Promise<McpSkill>;
+  /** ONE FILE OF THE SKILL AT `uri`: its `SKILL.md`, or `file`, a path in the skill
+   *  (`references/FORMS.md`). The file is read with `resources/read` and checked against the
+   *  skill's entry as the server has it now: the entry lists it, its size and digest are the
+   *  entry's, and a `SKILL.md`'s frontmatter is the entry's. A file that fails a check is refused,
+   *  as is one of more than 8 million characters. A digest proves that the file is the one the
+   *  server listed, not that the server is to be trusted. */
+  readSkill(uri: string, file?: string): Promise<McpSkillFile>;
+  /** The events the server offers (`events/list`), every page. A server that does not declare
+   *  MCP Events offers none, and `subscribe`, `unsubscribe` and `pollEvents` refuse it. */
+  listEvents(): Promise<McpEvent[]>;
+  /** SUBSCRIBE THIS CONTEXT to the event `name` with its arguments, by webhook: the server POSTs
+   *  each occurrence to this context's MCP webhook, which checks its signature and appends it
+   *  here as `events.iterate.com/mcp/webhook-received` `{ server, subscriptionId, body }`. `body`
+   *  is an `McpEventOccurrence`, or one of the server's notices: `{ type: "gap", cursor }`
+   *  (events were skipped) and `{ type: "terminated", error }` (the server ended the
+   *  subscription).
+   *  THE MIND RENEWS IT. A grant lapses at its `refreshBefore`, so the context's own schedule
+   *  (`itx.schedules.list()`, key `["mcp-subscription", …]`) runs a script that subscribes again
+   *  after two thirds of each grant, with the cursor of the grant before. When that script fails
+   *  twice, two minutes apart, nothing renews the subscription any more, and this context gets
+   *  `events.iterate.com/mcp/subscription-ended` `{ server, name, arguments, error }`, once:
+   *  subscribe again to go on. It tries once when a second try would come after the grant's
+   *  lapse, and a renewal that begins after the lapse subscribes nothing and says that the grant
+   *  lapsed. A GRANT THAT THE CONTEXT DOES NOT RENEW says so in `notRenewed`: one that is
+   *  over within two minutes, the soonest a context renews, and one of a connection with a
+   *  credential that is written out (`McpConnectOptions`). When a renewal gets such a grant, the
+   *  context gets `mcp/subscription-ended` too. `cursor`: where delivery begins, for a
+   *  subscription that lapsed; without it, now. `claim` is the renewal script's own, its hold on
+   *  the schedule: a caller gives none. */
+  subscribe(
+    name: string,
+    args?: Record<string, unknown>,
+    options?: { cursor?: string; claim?: number },
+  ): Promise<McpSubscription>;
+  /** End the subscription `subscribe(name, args)` made, and its renewal. The renewal ends first:
+   *  when the server does not answer, the subscription still lapses at its `refreshBefore`. A
+   *  renewal that runs at that moment ends what it subscribed, and sets no next renewal. */
+  unsubscribe(name: string, args?: Record<string, unknown>): Promise<void>;
+  /** ONE POLL of the event `name` (`events/poll`), for an event that a server offers by poll
+   *  alone: the occurrences after `cursor`, and the cursor to go on from. No cursor starts from
+   *  now and answers no event. `hasMore`: poll again at once. Else wait `nextPollMs`, at least:
+   *  nothing here polls again, so a script that wants more sets a schedule of its own. */
+  pollEvents(
+    name: string,
+    args?: Record<string, unknown>,
+    options?: { cursor?: string; maxEvents?: number },
+  ): Promise<{
+    events: McpEventOccurrence[];
+    cursor?: string | null;
+    truncated?: boolean;
+    hasMore?: boolean;
+    nextPollMs?: number;
+  }>;
+  close(): Promise<void>;
+}
+
+/** `connectToOpenApi`'s options: the base URL requests go to (default: the document's first
+ *  server), and headers every request carries. */
+export type OpenApiConnectOptions = { baseUrl?: string; headers?: Record<string, string> };
+
+/** An OpenAPI 3 document — only `openapi`, `servers` and `paths` are read. */
+export type OpenApiDocument = {
+  openapi: string;
+  servers?: Array<{ url?: string }>;
+  paths?: Record<string, Record<string, unknown>>;
+};
+
+/** One operation an OpenAPI connection grew a method for. */
+export type OpenApiOperation = {
+  operationId: string;
+  method: string;
+  path: string;
+  parameters: Array<{ name: string; in: string; required?: boolean }>;
+  hasRequestBody: boolean;
+  summary?: string;
+};
+
+/** `itx.connectToOpenApi(specOrUrl)`: an OpenAPI 3 service. Besides these, one method per
+ *  `operationId` (dotted spelling, untyped here), each taking one input object. */
+export interface OpenApiConnectionApi {
+  operations(): OpenApiOperation[];
+  /** The input object's fields become path, query and header parameters, the rest the JSON body;
+   *  the answer is JSON when the response says so, else its text. */
+  call(operationId: string, input?: Record<string, unknown>): Promise<unknown>;
+}
+
+/** `connectToCapnweb`'s options: headers for the session's requests, and the transport — a
+ *  WebSocket session (default) or one HTTP batch per chain. */
+export type CapnwebConnectOptions = {
+  headers?: Record<string, string>;
+  transport?: "websocket" | "batch";
+};
+
+/** `itx.connectToCapnweb(url)`: a remote capnweb API's main object as a pipelinable handle (its
+ *  methods are the remote's, untyped here), and `close()` for the session (the next call reopens). */
+export type CapnwebConnectionApi = InvokeHandle & { close(): void };
+
+/** A stored file as `itx.files` answers it: its path, content type and size. */
+export type FileRecord = { path: string; contentType: string; size: number };
+
+/** `itx.files.get(path)`: a file's verbs. `put`'s string data is base64 or a `data:` URL; `url` is
+ *  a signed URL on the mind host that downloads (`GET`, the default) or uploads (`PUT`) it. */
+export type FileHandle = {
+  put(input: {
+    contentType?: string;
+    data: Uint8Array | ArrayBuffer | string;
+  }): Promise<FileRecord>;
+  bytes(): Promise<Uint8Array>;
+  head(): Promise<FileRecord | null>;
+  delete(): Promise<void>;
+  url(input?: {
+    method?: "GET" | "PUT";
+    expiresInSeconds?: number;
+  }): Promise<{ url: string; expiresAt: string }>;
+};
+
+/** `itx.email.send`: one message from an address of the mind's. `inReplyToOffset` names a
+ *  message on the mind's `/integrations/email` and answers it in its thread: its recipients,
+ *  `Re:` subject and threading headers are the defaults. Each attachment is a mind file
+ *  (`itx.files`). */
+export type EmailSendInput = {
+  /** The sender: any address at one of the mind's zones (`agent@example.com`). There is no
+   *  default: a send that names none is refused, and so is any other address. */
+  from: string;
+  to?: string | string[];
+  cc?: string | string[];
+  subject?: string;
+  text?: string;
+  html?: string;
+  inReplyToOffset?: number;
+  attachments?: { path: string; filename?: string }[];
+};
+
+/** WHICH requests a fetch route takes — every field given must hold. A fetch route matches an HTTP
+ *  request: `url` is a standard `URLPattern` over the real URL (hostname and path; its init's
+ *  fields, each a pattern string: `url: { hostname: "here.tunnels.example.com" }`), `headers`
+ *  exact values. It names at least one url field or header: `{}` is refused. */
+export type FetchRouteRequestMatcher = {
+  url?: {
+    protocol?: string;
+    username?: string;
+    password?: string;
+    hostname?: string;
+    port?: string;
+    pathname?: string;
+    search?: string;
+    hash?: string;
+    baseURL?: string;
+  };
+  headers?: Record<string, string>;
+};
+
+/** A route as `itx.fetchRoutes.set(name, route)` takes it: the requests it takes, the itx
+ *  expression they go to, who may use it (`mind-members`: the config worker answers anyone else
+ *  the sign-in challenge; absent or null: public) and its priority (higher first, then by name). */
+export type FetchRouteInput = {
+  requestMatcher: FetchRouteRequestMatcher;
+  target: ItxExpressionInput;
+  authRequirement?: { visitors: "mind-members" } | null;
+  priority?: number;
+};
+
+/** A live route as `list()` and `match` answer it, its target parsed, with the offset of the
+ *  `itx/fetch-route-configured` fact that set it. */
+export type FetchRouteEntry = {
+  fetchRouteName: string;
+  requestMatcher: FetchRouteRequestMatcher;
+  target: ItxExpression;
+  authRequirement: { visitors: "mind-members" } | null;
+  priority: number;
+  configuredOffset: number;
+};
+
+/** One change a repo commit applies: a file's new content, as text or as bytes, or its deletion. */
+export type RepoFileChange =
+  | { path: string; content: string }
+  | { path: string; bytes: Uint8Array | ArrayBuffer }
+  | { path: string; delete: true };
+/** One commit as `log` lists it, newest first (`timestamp` is epoch milliseconds). */
+export type RepoLogEntry = {
+  oid: string;
+  message: string;
+  author: { name: string; email: string };
+  /** who made the commit: `iterate` for every commit the platform makes, whoever wrote it */
+  committer: { name: string; email: string };
+  timestamp: number;
+  parents: string[];
+};
+/** What a commit reports: the new tip (null on an unborn repo that stayed empty) and the paths it
+ *  changed (none when the tree was already as asked). */
+export type RepoCommitResult = { commitOid: string | null; changedPaths: string[] };
+/** How a `pull` or `push` ended: `main` moved from `previousOid` to `commitOid` (`updated`), or both
+ *  sides were already at `commitOid` (`up-to-date`). Pulling or pushing without `force` when neither
+ *  side contains the other throws `NOT_FAST_FORWARD`, with `{ ours, theirs }` as its data. */
+export type RepoSyncResult = {
+  status: "updated" | "up-to-date";
+  commitOid: string | null;
+  previousOid: string | null;
+};
+/** `itx.repos.get(path)`: the repo's verbs, branch `main` only (core/mind-worker/src/repo). A
+ *  `commitOid` pins a read to that commit; without one, a read is of the tip. */
+export type RepoHandle = InvokeHandle & {
+  tip(): Promise<string | null>;
+  /** A text file's text; null when the repo has no such file. A file that is not text is refused:
+   *  `readBytes` reads any file. */
+  readFile(path: string, options?: { commitOid: string }): Promise<string | null>;
+  /** Any file's bytes, as a stream with its size: `await new Response(file.data).bytes()`. */
+  readBytes(
+    path: string,
+    options?: { commitOid: string },
+  ): Promise<{ data: ReadableStream<Uint8Array>; size: number } | null>;
+  /** The repo's text files by path, or with `dir` those under that folder. */
+  modules(options?: { commitOid?: string; dir?: string }): Promise<Record<string, string>>;
+  /** Every file, as the loader reads a worker's source: text, or `{ base64 }` for a file that is
+   *  not text. */
+  files(options?: {
+    commitOid?: string;
+    dir?: string;
+  }): Promise<Record<string, string | { base64: string }>>;
+  listFiles(): Promise<{ commitOid: string | null; paths: string[] }>;
+  commitFiles(input: {
+    message: string;
+    changes: RepoFileChange[];
+    author?: { name: string; email: string };
+    parent?: string | null;
+  }): Promise<RepoCommitResult>;
+  writeFile(path: string, content: string): Promise<RepoCommitResult>;
+  /** The newest commits, newest first, each step along the commit's first parent: from main's
+   *  tip, or `from` any commit (a branch's tip, which reads a proposal's own commits). */
+  log(options?: { limit?: number; from?: string }): Promise<RepoLogEntry[]>;
+  /** Every branch with its newest commit. The mind reads and publishes `main`; a push to any
+   *  other branch changes nothing that runs. */
+  branches(): Promise<{ name: string; commitOid: string }[]>;
+  /** Lands the tip's `repo/commit-completed` fact again, and answers the tip. On a stack whose
+   *  queue has the repo's Artifacts subscription (the config repo's, made at each deploy), a
+   *  `git push` to the repo's remote lands the fact by itself, so `/repos/config` publishes. Call
+   *  this after a push to a repo with no subscription (one made after the deploy), and when a
+   *  mind takes over an Artifacts repo that an older stack made. Null when the repo has no commit. */
+  announceTip(): Promise<string | null>;
+  /** The one remote the repo remembers, as git's `origin`: a git URL over HTTP(S) whose userinfo may
+   *  hold a secret placeholder (`https://x-access-token:getSecret("/secrets/github-acme", { field:
+   *  "accessToken" })@github.com/acme/config.git`, the placeholder percent-encoded or not), never a
+   *  token; null when none. */
+  origin(): Promise<string | null>;
+  /** Remember `url` as origin, or forget it (`null`): a `repo/origin-set` fact on the repo's log. */
+  setOrigin(url: string | null): Promise<{ origin: string | null }>;
+  /** Bring the remote's `main` into this repo, the same commits and oids, fast-forward only unless
+   *  `force` (which resets `main` to the remote's). A pull that moves `main` lands
+   *  `repo/commit-completed` like a commit, so `/repos/config` publishes. `remote` defaults to origin. */
+  pull(options?: { remote?: string; force?: boolean }): Promise<RepoSyncResult>;
+  /** Send this repo's `main` to the remote's `main`, fast-forward only unless `force` (which
+   *  overwrites the remote's). `remote` defaults to origin. */
+  push(options?: { remote?: string; force?: boolean }): Promise<RepoSyncResult>;
+  /** Append the repo's own events on its context; its lifecycle facts are the collection's. */
+  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
+};
+
+/** One overlay entry as a workspace's `gitStatus` reports it, against its mount at HEAD. */
+export type WorkspaceChange = { path: string; change: "added" | "deleted" | "modified" };
+/** One mount as `gitStatus` reports it: its path, its repo, and the overlay's changes under it. */
+export type WorkspaceMountStatus = { path: string; repo: string; changes: WorkspaceChange[] };
+/** `itx.workspaces.get(path)`: a private overlay over the mind's repos, each repo mounted at its
+ *  path (core/mind-worker/src/workspace). Reads see the overlay, then the mounted repo's tip. */
+export type WorkspaceHandle = InvokeHandle & {
+  mounts(): Promise<Record<string, { repo: string }>>;
+  /** The overlay's copy (a deletion reads null), else the mounted repo's file at its tip. */
+  readFile(path: string): Promise<string | null>;
+  /** The mounted repo's file at its tip whatever the overlay says. */
+  readBase(path: string): Promise<string | null>;
+  writeFile(path: string, content: string): Promise<void>;
+  /** False when the path was not a file of the merged view. */
+  deleteFile(path: string): Promise<boolean>;
+  /** Drop the overlay's entry at `path`. */
+  revert(path: string): Promise<void>;
+  listAllFiles(): Promise<string[]>;
+  gitStatus(): Promise<{ mounts: WorkspaceMountStatus[]; unmounted: WorkspaceChange[] }>;
+  /** Commit the overlay's changes under one mount (`scope`, needed when several are dirty). */
+  gitCommit(input: {
+    message: string;
+    scope?: string;
+    author?: { name: string; email: string };
+  }): Promise<{ commitOid: string | null; mount: string; repo: string; changedPaths: string[] }>;
+  gitLog(input?: { scope?: string; limit?: number }): Promise<RepoLogEntry[]>;
+  /** Append the workspace's own events on its context; its lifecycle facts are the collection's. */
+  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
+};
+
+/** Cloudflare's handle to a snapshot of the writable root filesystem, as `itx.sandboxes` records it. Opaque; valid only for the
+ *  image it was taken from, and for 30 days after its last restore. */
+export type SandboxSnapshot = { id: string; size: number; name?: string };
+
+/** What the container API's `start` takes: `ctx.container.start`'s options, but for
+ *  `enableInternet` (refused: a sandbox's only way out is the mind's egress) and a
+ *  `containerSnapshot`, which can only be the snapshot the sandbox's own log records. A start that
+ *  names a size (`instance`) is remembered: the sandbox starts on it again until one names another. */
+export type SandboxContainerStartOptions = {
+  image?: string;
+  containerSnapshot?: { id: string };
+  entrypoint?: string[];
+  env?: Record<string, string>;
+  instance?:
+    | "lite"
+    | "standard-1"
+    | "standard-2"
+    | "standard-3"
+    | "standard-4"
+    | { vcpu: number; memoryMib: number; diskMb: number };
+  labels?: Record<string, string>;
+};
+
+/** What the sandbox's own `start` takes: the container API's, and `from`, which copies a sandbox:
+ *  the path of another sandbox of this mind whose snapshot this one starts from (tools installed
+ *  once, then started many times). That snapshot is this sandbox's own from then on. One of
+ *  `image`, `containerSnapshot` and `from` at most. `image` is `"cloudflare/debian-trixie"` (the
+ *  Cloudflare-managed image), the name of an image of the stack, or a digest-pinned image of the
+ *  account's own registry (`registry.cloudflare.com/<account>/<repository>@sha256:<digest>`);
+ *  anything else fails, since Cloudflare pulls from no other registry. */
+export type SandboxStartOptions = SandboxContainerStartOptions & {
+  from?: string;
+  /** What answers the sandbox's requests in place of the mind's `itx.fetch`: a rule for `itx.fetch`
+   *  on the sandbox's context, written as the caller's. It stays until another start names one. */
+  egress?: ItxExpressionInput;
+};
+
+/** What a sandbox's `files.stat` and `files.lstat` answer (the `iterate fs` tool's, run in the
+ *  container). */
+export type SandboxFileStat = {
+  type: "file" | "directory" | "symlink" | "other";
+  size: number;
+  mode: number;
+  uid: number;
+  gid: number;
+  atimeMs: number;
+  mtimeMs: number;
+  ctimeMs: number;
+};
+
+/** `itx.sandboxes.get(path).files`: the Sandbox SDK's `Files`, over the sandbox's container, with
+ *  `iterate fs` (the CLI's file tool) running inside it. A file is read and written as a stream. A
+ *  failure carries the errno's name as `code`: `ENOENT`, `EISDIR`, `ENOTDIR`, … Each call starts the
+ *  container first, from the snapshot last taken, as `exec` does. */
+export type SandboxFilesApi = {
+  /** A file's bytes. A missing file, or a directory, fails the call, never the stream half way. */
+  read(path: string): Promise<ReadableStream<Uint8Array>>;
+  /** `content` into a file, created or truncated; its directory must exist. A string is UTF-8. */
+  write(
+    path: string,
+    content: string | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>,
+  ): Promise<void>;
+  /** A path's metadata, a symbolic link followed. */
+  stat(path: string): Promise<SandboxFileStat>;
+  /** `stat` without following a symbolic link at the end of the path. */
+  lstat(path: string): Promise<SandboxFileStat>;
+  /** A directory's immediate entries, in the order it gives them. */
+  readDirectory(path: string): Promise<{ name: string; type: SandboxFileStat["type"] }[]>;
+  /** A directory; with `recursive`, its missing parents too, and no error when it exists. */
+  mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;
+  /** A file, directory or link renamed; an existing file at the destination is replaced. */
+  rename(source: string, destination: string): Promise<void>;
+  /** A file or link removed; a directory needs `recursive`, `force` makes a missing path no error. */
+  remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>;
+};
+
+/** `itx.sandboxes.get(path).container`: the Durable Object container API (`ctx.container`) itself,
+ *  every member under its own name, replayed where the container lives. A member that answers data is
+ *  a call: `container.inspect()`, `container.snapshotContainer()`, `container.destroy()`. A CHAIN is
+ *  `container.invoke(steps)`: `container.invoke([["exec", argv, { stdin?: ReadableStream }], "stdout"])`
+ *  is one call, and a `ReadableStream` comes back as it is; an `exec` chain ends in the process's
+ *  `.stdout`, `.stderr`, `.exitCode`, `.pid`, `.output()` (plain `{ exitCode, stdout, stderr }`) or
+ *  `.kill(signo?)`. A `start`, `snapshotContainer` or `destroy` lands on the sandbox's log, and a
+ *  sandbox with a call running is not parked. Cloudflare's meaning holds: a raw `start` restores
+ *  nothing by itself and a `destroy` saves nothing. Not reachable: `interceptOutbound*` (the
+ *  mind's egress is the platform's alone). */
+export type SandboxContainerApi = InvokeHandle & {
+  readonly running: Promise<boolean>;
+  readonly images: Promise<Record<string, string>>;
+  start(options?: SandboxContainerStartOptions): Promise<void>;
+  monitor(): Promise<void>;
+  destroy(reason?: string): Promise<void>;
+  signal(signo: number): Promise<void>;
+  setInactivityTimeout(durationMs: number): Promise<void>;
+  snapshotContainer(options?: { name?: string }): Promise<SandboxSnapshot>;
+  inspect(): Promise<{ image: string; labels: Record<string, string> } | null>;
+  /** The chain, replayed in one call: `[["exec", argv, options], "stdout"]`. */
+  invoke(steps: ItxExpression): Promise<any>;
+};
+
+/** `itx.sandboxes.get(path)`: a Linux container whose writable root filesystem is kept as a
+ *  snapshot (core/mind-worker/src/sandbox). `exec` and every call of `files` start the container
+ *  when none runs, from the snapshot last taken, on `standard-1` unless `start({ instance })` says
+ *  otherwise. Memory and running processes do not survive a stop; the snapshot does, for 30 days
+ *  after its last restore and only on the image it was taken from. With no snapshot and no
+ *  `image`, a start runs the image the mind names
+ *  (`events.iterate.com/mind/sandbox-image-configured` on `/`), else the stack's named image when
+ *  its config names exactly one (with several, the start must name one), else the
+ *  Cloudflare-managed image `cloudflare/debian-trixie`:
+ *  Node 24 and npm on Debian, with no git, no curl and no coding CLI
+ *  (`start({ image: "cloudflare/debian-trixie" })` asks for it on any stack). iterate's own image,
+ *  named `iterate-dev-image` on a stack that has it, is Node on Debian with git, gh, Chromium,
+ *  ffmpeg, pnpm, the Claude, Codex and Grok CLIs, the cf CLI, doppler and the iterate CLI.
+ *  INSTALL ONCE, THEN COPY THE SANDBOX: install what is missing in one sandbox, take a snapshot
+ *  (`container.snapshotContainer({ name })`), and start every other sandbox with
+ *  `start({ from: "<that sandbox's path>" })`. Do not use the first sandbox after its snapshot: its
+ *  next idle save replaces the snapshot. NOTHING RUNS FOR NOTHING: a sandbox unused for
+ *  `idleAfterMs` (five minutes by default; a command, a file call or a stream being read is use;
+ *  a call left open counts for an hour at most; a background job is not use, and the stop kills
+ *  it) is saved and stopped, a sandbox in use has a snapshot taken every 15 minutes, and
+ *  Cloudflare stops the container two hours after it last answered, whatever else fails. THE ONLY WAY OUT IS THE
+ *  MIND'S EGRESS: the container starts with the internet off, and every HTTP and HTTPS request it
+ *  makes, to any name or address, WebSocket handshakes included, is answered by the mind's own
+ *  `itx.fetch` (its rewrite rules;
+ *  `getSecret("/secrets/…")` placeholders are substituted there). `apt-get` works through it. A
+ *  mind's GitHub connection is in every command's environment as placeholders (`GH_TOKEN`, and a
+ *  git credential helper that answers with it): with `git` and `gh` installed, cloning, pushing and
+ *  opening pull requests need no setup, and no token ever enters the container. A call
+ *  that does not answer within a minute fails: run longer work in the background, as Cloudflare's
+ *  recipe does, and poll its files within the idle period:
+ *  `container.invoke([["exec", ["setsid", "sh", "-c", "<command> > /tmp/job.log 2>&1; echo $? > /tmp/job.exit"], { stdout: "ignore", stderr: "ignore" }], "pid"])`
+ *  answers the process id at once. A plain
+ *  `exec(["bash", "-c", "setsid nohup <command> > /tmp/job.log 2>&1 < /dev/null & echo started"])`
+ *  works too, joined with `;` and never `&&`. Where the sandbox stands is
+ *  `(await handle.snapshot()).state`. */
+export type SandboxHandle = InvokeHandle & {
+  /** `container.start(options)` with the sandbox's snapshot: make the container run, from the
+   *  snapshot last taken unless `image` asks for a fresh start (which leaves that snapshot behind).
+   *  Running already: `start()` does nothing, and so does a start that names what the sandbox
+   *  started on (a start asked again). A start that names another `image`, `containerSnapshot` or
+   *  `from` FAILS, since it would change nothing (`container.destroy()` stops the sandbox first).
+   *  A snapshot Cloudflare will not restore (the image was replaced, or 30 days passed)
+   *  FAILS the start rather than start empty; `start({ image })` is the way out. */
+  start(options?: SandboxStartOptions): Promise<void>;
+  /** `container.exec(argv, options)` then `process.output()`: run a command and wait for it
+   *  (a shell is `["bash", "-c", "…"]`). A nonzero exit is an answer, not a failure. Output over
+   *  8 MiB fails (write it to a file, or stream it with `container.exec(argv).stdout`); take secrets
+   *  from `env`, since the log keeps the first 500 characters of the command. The call fails when
+   *  it has no answer within a minute; `timeoutMs` (ten minutes when absent) is when the command
+   *  itself is stopped. */
+  exec(
+    command: string[],
+    options?: {
+      cwd?: string;
+      env?: Record<string, string>;
+      user?: string;
+      stdin?: string | Uint8Array;
+      timeoutMs?: number;
+    },
+  ): Promise<{ exitCode: number; stdout: Uint8Array; stderr: Uint8Array }>;
+  /** The Sandbox SDK's `Files`. */
+  files: SandboxFilesApi;
+  /** The container API itself. `container.invoke([["getTcpPort", port], ["fetch", request]])` with a
+   *  `Request` is a request to a server in the sandbox: it starts a stopped sandbox and runs the
+   *  command of an exposed port that is closed. From a script or from an app's `fetch` it carries
+   *  HTTP alone: no RPC answer holds a socket. A WebSocket needs the port's own host
+   *  (`exposePort`), where the platform sends the request with no RPC in its way. */
+  container: SandboxContainerApi;
+  /** SERVE A PORT OF THE SANDBOX AT A HOST OF THE MIND, `https://<name>.<domain>/`: HTTP, streamed
+   *  bodies and WebSockets. A request that finds the sandbox stopped starts it, as `exec` does,
+   *  and one that finds the port closed runs `command` (detached, its output in
+   *  `/var/log/iterate-port-<port>.log`) and waits for the port, 45 seconds at most in all. Members
+   *  only, unless `public: true`. A PUBLIC PORT LETS ANY VISITOR START THAT ONE CONTAINER AND KEEP IT
+   *  RUNNING, with no bound on how often: each request is a use. NEVER PUT A SECRET IN `command`: the
+   *  sandbox's log keeps it. `name` is a DNS label that no other fetch route takes and is not
+   *  `iterate`, `auth`, `dash`, `docs` or `voice`; a name that an app of the mind's own serves takes
+   *  that host until `unexposePort`, because a fetch route is served before the mind's code. Only a
+   *  context that the sandbox is beneath, and that may set a fetch route on `/`, exposes a port. A
+   *  second call with the same port and name replaces the command and who may reach it. An idle
+   *  stop keeps the host; deleting the sandbox removes it. */
+  exposePort(
+    port: number,
+    options: { name: string; command?: string[]; public?: boolean },
+  ): Promise<{ port: number; name: string; url: string; public: boolean }>;
+  /** Stop serving the port at its host and free the name. `name` is null when it was not exposed. */
+  unexposePort(port: number): Promise<{ port: number; name: string | null }>;
+  /** The ports that a host serves now, read from the fetch routes on `/`. */
+  getExposedPorts(): Promise<
+    { port: number; name: string; url: string; public: boolean; command?: string[] }[]
+  >;
+  /** How long the sandbox may sit unused before it is saved and stopped: 1 second to 1 hour, five
+   *  minutes by default. */
+  configure(settings: { idleAfterMs?: number }): Promise<{ idleAfterMs: number }>;
+  /** Append the sandbox's own events on its context; its lifecycle facts are the collection's. */
+  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
+};
+
+export type ContextListOptions = {
+  /** Words that must all occur in the path or in anything the context said about itself. */
+  search?: string;
+  /** Only this context and the contexts below it. */
+  under?: string;
+  /** Only the contexts that have work now. */
+  awake?: boolean;
+  /** At most this many, 200 when absent and never more than 1,000. */
+  limit?: number;
+};
+
+/** One live in-flight activity on a context's activity stack (`itx.contexts.list`, `activities` live state). */
+export type ContextActivity = {
+  key: string;
+  text: string;
+  icon?: string;
+  url?: string;
+  tags?: string[];
+  pushedAt?: string;
+  expiresAt?: string;
+};
+
+/** One context as the mind's catalog lists it (`itx.contexts.list`). */
+export type ContextListing = {
+  path: string;
+  /** Present while the context has work, and for about a second after: when it woke (ms). */
+  awake?: { since: number };
+  createdAt?: string;
+  lastEventAt?: string;
+  /** The newest event that is not the kernel's own (`itx/*`). */
+  lastActivityAt?: string;
+  /** How many durable events its log holds. */
+  eventCount: number;
+  /** How many of each type, by type. */
+  eventTypes: Record<string, number>;
+  /** The last few types that are not the kernel's own, newest last. */
+  recentTypes: string[];
+  /** The names of the processors it hosts. */
+  processors: string[];
+  /** The size of its storage, in bytes. */
+  storageBytes?: number;
+  /** What the context is for, in its own words: its newest `events.iterate.com/itx/described`. */
+  description?: string;
+  metadata?: Record<string, unknown>;
+  /** Live in-flight activities on this context's stack while it is awake, newest first. */
+  activities?: ContextActivity[];
+};
+
+/** THE ORDERS OF A WATCHED QUERY (`itx.contexts.watch`). Each is total: the path breaks a tie.
+ *  - `active`: the newest activity first (`activeMs`, then the path, both descending).
+ *  - `created`: the newest context first (`createdMs`, then the path, both descending).
+ *  - `path`: by path, A to Z, as UTF-8 bytes. */
+export type CatalogOrder = "active" | "created" | "path";
+
+/** A QUERY OF THE MIND'S CATALOG THAT IS WATCHED (`itx.contexts.watch`). Nothing declares a query
+ *  ahead of time: a watcher sends one at run time. One of three kinds:
+ *  - a window: the contexts that hold every fact named (`where`, `under`, `childrenOf`), in one
+ *    `order`, up to `limit`;
+ *  - `keys`: exactly these paths, which is what a join asks for;
+ *  - `awake`: the contexts that have work now.
+ *
+ *  A FACT is a scalar at the top of a context's `metadata` (its newest
+ *  `events.iterate.com/itx/described`), or a scalar of a list there: `{ status: "open" }` matches
+ *  `metadata.status === "open"`, and `{ tags: "pinned" }` matches a `metadata.tags` that holds
+ *  `"pinned"`. A number or a boolean matches as its text. The kernel's own facts start with `$`:
+ *  `$processor` is a processor that the context hosts. A query that the catalog cannot answer
+ *  exactly is refused with the reason: nothing is dropped. So a query cannot name a fact that the
+ *  index does not hold: a key of more than 80 characters, a value of more than 200, or another
+ *  key that starts with `$`.
+ *
+ *  ONE KIND OF CONTEXT IS IN NO WATCHED ANSWER, and `contexts.list` has it: one whose row the
+ *  catalog cannot order or index (a path that is not well-formed text, or more than 2,048
+ *  facts). The catalog logs each (`context.reactive-catalog-row-refused`). */
+export type CatalogQuery = {
+  /** Every fact must hold. */
+  where?: Record<string, string | number | boolean>;
+  /** The context at this path and every context below it. */
+  under?: string;
+  /** The contexts one level below this path. */
+  childrenOf?: string;
+  /** `active` when absent. */
+  order?: CatalogOrder;
+  /** At most this many rows, 50 when absent and never more than 500. */
+  limit?: number;
+  /** Exactly these paths, at most 500, with no order and no limit. It stands alone. */
+  keys?: string[];
+  /** The contexts that are awake now. It stands alone. */
+  awake?: true;
+};
+
+/** ONE CONTEXT AS A WATCH SENDS IT: its listing without `awake` and `activities` (the awake list
+ *  is a watch of its own, `{ awake: true }`), the two values that the orders sort by, and the
+ *  catalog's revision at which the row last changed. A ROW CHANGES WHEN ITS CONTEXT SENDS A
+ *  SUMMARY THAT DIFFERS in something the row holds: the counts and times of its events, its
+ *  storage, what it says of itself. A context that works sends a summary shortly after each
+ *  burst of changes of its activity stack, once in 15 s with no such change, and once when it
+ *  goes quiet. It gathers a burst for 100 ms, and that is no least time between two summaries.
+ *  So the row of a context that does many short pieces of work, each of which adds to its log,
+ *  changes about ten times a second: a watcher that draws should not draw at each frame. One
+ *  long piece of work that only adds to the log changes the row once in 15 s. */
+export type CatalogRow = Omit<ContextListing, "awake" | "activities"> & {
+  /** What the order `active` sorts by, in milliseconds: when the context was last active
+   *  (`lastActivityAt`, or `lastEventAt` when it has had no activity of its own). */
+  activeMs: number;
+  /** What the order `created` sorts by, in milliseconds: `createdAt`. */
+  createdMs: number;
+  rev: number;
+};
+
+/** One row of the awake list (`{ awake: true }`). It comes from the open sockets alone, so it has
+ *  no revision. */
+export type CatalogAwakeRow = { path: string; since: number; activities?: ContextActivity[] };
+
+/** WHAT A WATCHER HOLDS OF A QUERY, for a watch that starts again (a page that reconnects): the
+ *  catalog then sends every path of the answer and only the rows that the watcher lacks. `gen`,
+ *  `rev` and `q` are those of the watcher's last frame. A cursor of another generation or another
+ *  query gets every row. */
+export type CatalogCursor = {
+  gen: string;
+  rev: number;
+  q: string;
+  /** Of a window: the sort key of the LAST row that the watcher holds, in the window's order
+   *  (`[activeMs, path]`, `[createdMs, path]`, or `[0, path]` for the order `path`); null when it
+   *  holds none. */
+  bound?: [at: number, path: string] | null;
+  /** Of a `keys` query: the paths that the watcher holds. */
+  have?: string[];
+};
+
+/** WHAT A WATCH'S CALLBACK IS CALLED WITH. The first frame is the answer: `reset` holds every
+ *  row; `resume` (the answer to a cursor) holds every path of the answer in `ids` and only the
+ *  rows that the watcher lacks. Every later frame is a `change`: the paths that left the answer
+ *  and the rows that came or changed. `from` is the revision of the frame before, so a watcher
+ *  sees a gap; the session's end sees it first and sends a `reset`. A `reset` may come at any
+ *  time (after a deploy, the catalog is asked again), and it is the whole truth: a watcher puts
+ *  its rows in the place of what it holds, also where a row's `rev` is the one it has, since a
+ *  new `gen` counts its revisions anew.
+ *
+ *  ONE WRITE IS ONE BATCH, of any size. A write that changes several watches of one session sends
+ *  one frame to each, and every frame but the last says `more: true`: a watcher that joins two
+ *  watches applies the frames of a batch together, and never sees half of a write. */
+export type CatalogFrame<Row = CatalogRow> = { gen: string; rev: number; more?: true } & (
+  | { type: "reset"; q: string; full: boolean; rows: Row[] }
+  | { type: "resume"; q: string; full: boolean; ids: string[]; rows: Row[] }
+  | { type: "change"; from: number; del: string[]; rows: Row[] }
+);
+
+/** What `itx.contexts.watches()` answers: the catalog's own account of who watches what. */
+export type CatalogWatches = {
+  /** False until the first watch: the catalog then copies each context's row and keeps the copy. */
+  active: boolean;
+  gen: string;
+  rev: number;
+  rows: number;
+  sockets: number;
+  awake: number;
+  windows: {
+    /** The query in the catalog's one form of it. */
+    query: string;
+    size: number;
+    bound: [at: number, path: string] | null;
+    rev: number;
+    watchers: number;
+  }[];
+  /** How many contexts' rows the copy could not write, and still owes: each is made again from
+   *  the catalog's own row, after a wait, eight times at most. 0 in a catalog that is whole. */
+  owed: number;
+  /** What the catalog did since it last woke: statements with the rows that SQLite read and
+   *  wrote for them (what the object is billed by), writes, the writes that changed no window,
+   *  seeks, messages and characters sent. */
+  counters: Record<string, number>;
+  /** With `{ verify: true }`: each window whose stored size or bound disagrees with the rows. */
+  faults?: string[];
+  /** With `{ plans: true }`: how SQLite reads each statement of the engine. */
+  plans?: Record<string, string[]>;
+};
+
+/** An entity collection root (`itx.repos`, `itx.workspaces`, `itx.sandboxes`): `get(path)` the entity's handle,
+ *  `list()` the mind catalog, `create(path)` the creation saga on that path (the parent link the
+ *  caller's context writes first, then the processor row, the request, the terminal fact — created,
+ *  or create-failed thrown), `delete(path)` the deletion saga (the request, `deleted` cross-posted to
+ *  `/`, the row disabled). A relative `path` means the caller's. `get` and `list` reach the whole
+ *  mind; `create` and `delete` only paths strictly beneath the caller's context (FORBIDDEN). An
+ *  entity whose creation has not landed refuses its handle's verbs and `delete` (NOT_CREATED). */
+export type EntityCollectionApi<Handle> = {
+  get(path: string): Handle;
+  list(): Promise<{ path: string; createdAt: string }[]>;
+  create(path: string): Promise<{ path: string }>;
+  delete(path: string): Promise<{ path: string }>;
+};
+
+/** The roots an installable app adds by rewrite rule — present only on a context whose table has
+ *  the rule (a mind that installed the app), so never part of `IterateContextApi` itself. An
+ *  installed app publishes its root by augmenting this interface from its own package
+ *  (`declare module "iterate/api" { interface InstalledAppRoots { myApp: MyAppApi } }`), so a root
+ *  the platform does not ship is never named here; a caller imports that module to spell
+ *  `IterateContextApiWith<"myApp">`. */
+export interface InstalledAppRoots {}
+
+/** What `itx.telemetry.query` answers: the rows, the SQL that ran for the mind, and an optional
+ *  plain notice (a table query on a stack with no telemetry tables answers no rows and a notice).
+ *  `truncated` is there when the answer holds the 1,000 rows that are the most one query
+ *  answers: more may match. `dataset` names the Cloudflare dataset that answered a query over one
+ *  (`TELEMETRY_DATASETS`); the SQL that ran holds the cut's values as named parameters
+ *  (`$itx_since`, `$itx_worker_0`, …). */
+export type TelemetryRows = {
+  rows: Record<string, unknown>[];
+  sql: string;
+  notice?: string;
+  truncated?: true;
+  dataset?: TelemetryDataset;
+};
+
+/** Cloudflare's own datasets that `itx.telemetry.query` reads with no token, each by the name
+ *  Cloudflare's Analytics SQL gives it; `metrics` is the stack's own Analytics Engine dataset. */
+export const TELEMETRY_DATASETS = [
+  "logs.workersLogs",
+  "logs.traces",
+  "logs.issues",
+  "events.workersInvocations",
+  "metrics",
+] as const;
+export type TelemetryDataset = (typeof TELEMETRY_DATASETS)[number];
+
+/** Whether a query goes to Cloudflare's datasets (`TELEMETRY_DATASETS`) and not to the telemetry
+ *  tables (`events`, `logs`, `spans`): a FROM or a JOIN names one of them, or another dataset of
+ *  Cloudflare's, which the query then refuses. The platform's `itx.telemetry.query` routes by it. */
+export const isTelemetryDatasetQuery = (sql: string) =>
+  /\b(?:FROM|JOIN)\s+(?:metrics\b|(?:logs|events)\s*\.)/i.test(sql);
+
+/** A context whose mind installed the named apps: with the app's package imported,
+ *  `IterateContextApiWith<"myApp">` spells `itx.myApp`. Code that holds a plain scope asserts it
+ *  (`itx as IterateContextApiWith<"myApp">`) where it knows the app is installed. */
+export type IterateContextApiWith<App extends keyof InstalledAppRoots> = IterateContextApi &
+  Pick<InstalledAppRoots, App>;
+
+/** THE ROOT OF EVERY SESSION AT `https://<controlPlaneHostname>/api`, the control plane's API: a
+ *  capnweb session over a WebSocket, which the boundary ends (core/boundary-worker
+ *  `ControlPlaneRpcTarget`). The root is small, after capnweb's own pattern of a root whose main
+ *  method answers the real API (https://github.com/cloudflare/capnweb#more-complicated-example).
+ *  Call `authenticate` at once and do not await it: capnweb sends the calls that are made on its
+ *  answer in the same round trip (`root.authenticate(token).mind.whoami()`). */
+export interface ControlPlaneApi {
+  /** What anyone may know of this stack, asked with no credential. `stackKey` is the document
+   *  that the stack publishes at `/keys/stack.json`. */
+  about(): Promise<{
+    controlPlaneHostname: string;
+    topology: "full-cloudflare" | "external-mind-connects-into-cloudflare-boundary";
+    stackKey: unknown;
+  }>;
+  /** ONE WAY IN FOR EVERY KIND OF CLIENT. With `token`: a token of this mind's issuer. With
+   *  nothing: what the WebSocket's own request carried, its `Authorization` bearer, else (from a
+   *  page of the control plane's own origin alone) the browser's session cookie. What the session
+   *  offers follows from what the credential is for. The socket closes when the credential ends. */
+  authenticate(token?: string): ControlPlaneSessionApi;
+}
+
+/** WHAT ONE AUTHENTICATED SESSION OF THE CONTROL PLANE'S API OFFERS A CLIENT. The whole session is
+ *  iterate/workers `ControlPlaneSession`: its other method is for a mind that runs elsewhere, and
+ *  its types are the stack's own, which a client does not load. */
+export interface ControlPlaneSessionApi {
+  /** A member's credential: the mind's root context, `/`, as that member. A key's token: the one
+   *  lend that the key may make, `whoami` and `provide`, and nothing else of the mind. Any other
+   *  credential: reading it is refused. */
+  readonly mind: IterateContextApi;
+}
+
+/** A context (a mind, a user, an organization): every `itx` root, reached through `invoke`. */
+export interface IterateContextApi {
+  invoke(call: ItxExpressionInput, ...args: unknown[]): Promise<unknown>;
+  /** Another context of this mind, by path (`..` and `/` allowed; the global namespace is not). */
+  cd(path: string): IterateContextApi;
+  /** Durable batches appended after a deadline (`afterMs`), at an instant (`at`) or on an interval
+   *  (`everyMs`); a key set again is replaced, but an interval set again as it stands keeps its
+   *  clock (a failed one is revived); a receipt cancels exactly the definition it names. */
+  schedules: {
+    set(
+      input: ScheduledAppendInput,
+      options?: { idempotencyKey?: string },
+    ): Promise<ScheduleReceipt>;
+    cancel(schedule: ScheduleKey | ScheduleReceipt): Promise<StreamEvent[]>;
+    list(): ScheduledAppend[];
+    get(key: ScheduleKey): ScheduledAppend | null;
+  };
+  /** `principal` is who is calling, when the call has one: a person through the mind's API. Code
+   *  the mind loaded calls as itself and gets none. `mindId` is the mind's id, the hash of its
+   *  signed genesis (./mind-identity.ts), which stays when its hostname changes; `mindSlug` is
+   *  its control-plane hostname, the name that people read. */
+  whoami():
+    | {
+        mindId?: string;
+        path: string;
+        mindSlug?: string;
+        mindUrl?: string;
+        principal?: Principal;
+      }
+    | Promise<{
+        mindId?: string;
+        path: string;
+        mindSlug?: string;
+        mindUrl?: string;
+        principal?: Principal;
+      }>;
+  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
+  /** `append`, answered with each event's offset alone: the events do not travel back. */
+  appendOffsets(...events: StreamEventInput[]): Promise<number[]>;
+  /** A public URL of this mind's own code over HTTP: `https://<hostname><path>`. `hostname` is a
+   *  hostname of one of the mind's zones (the first zone when absent), and never the control-plane
+   *  hostname, which the platform answers. `path` is "/" when absent. `await itx.url()` is how
+   *  code learns a zone of the mind: an app at the label `blog` is at
+   *  `blog.<new URL(await itx.url()).hostname>`. */
+  url(target?: { hostname?: string; path?: string }): Promise<string>;
+  /** RESET this context (Cloudflare's `ctx.abort`): its Durable Object drops everything it holds in
+   *  memory and the next call starts a fresh incarnation from durable storage. Resolves with the
+   *  `events.iterate.com/itx/aborted { reason?, callerPath?, app? }` event it recorded — durable
+   *  and attributed to the caller before anything resets — and the reset follows the answer.
+   *  SURVIVES: the log and everything derived from it (rewrite rules, subscriptions, schedules),
+   *  every facet's storage, kv. GOES: in-memory state, every facet instance and its in-flight work,
+   *  every socket on the context (a provider's re-dials), and every other call in flight there — it
+   *  rejects with the reset's message (`itx.abort() reset the context <path>: <reason>`). A handle
+   *  you kept names its target by expression, so its next call reaches the new incarnation.
+   *  Another context of the mind: `itx.cd(path).abort()`. A rewrite rule masks it like any name
+   *  (`provide("itx.abort", null)`). */
+  abort(reason?: string): Promise<StreamEvent>;
+  /** START THIS CONTEXT OVER at the same path, in the same Durable Object: it ends the context's
+   *  version (a number that starts at 1) and starts the next. Resolves with the
+   *  `events.iterate.com/itx/started-over { version, reason?, callerPath?, app?, held }` event it
+   *  recorded, where `held` names the version's schedules, subscriptions and rewrite rules.
+   *  `events.iterate.com/itx/created { path, version }` follows it, and the object restarts. The
+   *  next incarnation empties what the earlier version left, and its first wake is the version's
+   *  birth: `itx/woken`, then the host's birth events and its wake events. The answer waits until
+   *  no other isolate holds the earlier version's rules (5 s at most), so no grant of the earlier
+   *  version answers after it. An append that arrives between the capstone and the restart is
+   *  refused as `UNAVAILABLE` and may be sent again.
+   *  EACH CALL THAT RUNS STARTS A VERSION: a second call that reaches the context after the
+   *  restart starts another, so call once for a path and do not send it again after an error.
+   *  A LIVE CLIENT IS TOLD. A subscriber whose target is a client's live callback gets the capstone
+   *  (`itx/started-over` and `itx/created`) as its last batch, whatever it consumes, since its row
+   *  goes with the version; an event that its row does not take comes as the bare border, with the
+   *  version alone. `iterate/client` then subscribes again and reads the new version from its
+   *  start. A WebSocket that a client holds through the context to a provider (a fetch upgrade)
+   *  dials again after the restart, as it does after `abort`, and goes on when its expression still
+   *  resolves; a name that a client lent the earlier version goes with it. A write that another context makes in
+   *  reaction to the earlier version and that arrives after the capstone lands in the new version:
+   *  it is sent again like any write. A handle made with `facets.get(name, spec)` names a spec;
+   *  called after a new version, it hosts that spec under the name again.
+   *  GOES: every rewrite rule but the holds (below), subscriptions, schedules, fetch routes and pause, every open run
+   *  (settled `interrupted`), every facet and its storage, every subscription's cursor and
+   *  deliveries, the at-most-once send marks; then everything `abort` drops.
+   *  STAYS: the log and its offsets, and what other objects keep under this path: child contexts,
+   *  the parent's catalog row, secrets, the mind's kv, files, telemetry. A child announces itself
+   *  to its ancestors once, so a new version of an ancestor holds no `itx/child-created` for the
+   *  children that exist, and a catalog it folds from those facts starts empty. A read from the start
+   *  begins at the current version (`allVersions: true` reads from the log's start); a read from
+   *  a positive offset answers that offset's event whatever its version.
+   *  An idempotency key counts within its version, so an event delivered again after a new version
+   *  is taken as new. (No key begins with the control character U+001F: the kernel stores a later
+   *  version's keys under it, and `append` refuses one.) WHAT HOLDS THE CONTEXT'S CODE STAYS: a
+   *  mask (a rule with a null target, a jail's bare `itx ⇒ null` among them), and a rule at one of
+   *  the context's own verbs (`itx.cd` pointed at a broker, `itx.run` at a jail); loaded code can
+   *  remove neither. Every other rule goes (the parent link, and a rule at any other name; under a
+   *  jail every rule with a target, since each is a grant there), so the config writes a jail's
+   *  grants again. A context that masks a name takes a new version only
+   *  from a member's session.
+   *  Refused on `/` and on a context that hosts a first-party facet (a repo, a sandbox, a
+   *  workspace, mail, integrations), whose resources are outside the context. Another context of
+   *  the mind: `itx.cd(path).newVersion()`. A rewrite rule masks it like any name. */
+  newVersion(reason?: string): Promise<StreamEvent>;
+  readEvents(
+    afterOffset?: number,
+    limit?: number,
+    /** A read from the start (`afterOffset` 0 or absent) begins at the current version
+     *  (`newVersion`), unless `allVersions` is true. A positive `afterOffset` is taken as given,
+     *  whatever version it is in. */
+    options?: { includeEphemeral?: boolean; allVersions?: boolean },
+  ): Promise<StreamPage>;
+  waitForEvent(filter?: WaitForEventFilter): Promise<StreamEvent>;
+  /** The request through this context's rule for `itx.fetch`. The method, headers and body go
+   *  into the Request.
+   *  THERE ARE TWO SIGNERS, AND NOTHING ELSE SIGNS. (1) The built-in fetch signs for the mind its
+   *  caller names by argument: `{ signFor: "<another mind's control-plane hostname>" }` sends the
+   *  request as this mind to that one (`minds.get(domain).fetch` asks so); its record is
+   *  `events.iterate.com/itx/signed-request-sent`. (2) A request that uses a secret by proxy
+   *  (`SecretProxy`) is signed by the secrets Worker for that secret's proxy alone, to that
+   *  proxy's address, as the secret's `set` says; its record is the secret's own use fact, not
+   *  that event.
+   *  A rule's target gets the option as one more argument (a whole `@` hands on both): a narrow
+   *  fetch passes the request on and nothing else, so the built-in does not sign what it sends. A
+   *  request that names a by-proxy secret is still signed by the secrets Worker for that proxy,
+   *  for any caller that may use that secret. For a jail's
+   *  author: a narrowed fetch calls the mind's fetch with the request alone; it never hands on
+   *  what else it was given. */
+  fetch(request: Request, options?: { signFor: string }): Promise<Response>;
+  kv: {
+    get(key: string): Promise<string | null>;
+    put(key: string, value: string): Promise<{ ok: true }>;
+    delete(key: string): Promise<{ ok: true }>;
+    list(prefix?: string): Promise<{ keys: string[] }>;
+  };
+  /** The object store: every write and delete lands `itx/file-set` or `itx/file-deleted` on the
+   *  context that made it, so a file always has evidence on a log (a signed upload's is on `/`).
+   *  The R2 binding's own verbs on the owner's slice of one bucket (every key
+   *  prefixed, the prefix stripped from every key answered); what cannot cross the wire is answered
+   *  as data — an `R2Object` as its fields, a body as its bytes. `list` is one page with its cursor.
+   *  `presign` is a signed URL on the mind host, a download or an upload. `files` is the
+   *  friendlier surface. */
+  r2: {
+    head(key: string): Promise<R2ObjectRecord | null>;
+    get(
+      key: string,
+      options?: { range?: R2Range },
+    ): Promise<(R2ObjectRecord & { data: Uint8Array }) | null>;
+    put(
+      key: string,
+      value: ArrayBuffer | ArrayBufferView | string | null,
+      options?: {
+        httpMetadata?: R2HTTPMetadata;
+        customMetadata?: Record<string, string>;
+        storageClass?: string;
+      },
+    ): Promise<R2ObjectRecord>;
+    delete(keys: string | string[]): Promise<void>;
+    list(options?: {
+      limit?: number;
+      prefix?: string;
+      cursor?: string;
+      delimiter?: string;
+      startAfter?: string;
+      /** R2 lists neither unless asked. */
+      include?: ("httpMetadata" | "customMetadata")[];
+    }): Promise<{
+      objects: R2ObjectRecord[];
+      delimitedPrefixes: string[];
+      truncated: boolean;
+      cursor?: string;
+    }>;
+    presign(input: {
+      key: string;
+      method?: "GET" | "PUT";
+      expiresInSeconds?: number;
+    }): Promise<{ url: string; expiresAt: string }>;
+  };
+  /** The mind's secrets, WRITE-ONLY: a secret IS its path (`/secrets/<name>`, the name
+   *  `[a-zA-Z0-9._-]+`), and the path is what an outbound request's placeholder spells —
+   *  `getSecret("/secrets/<name>")` in a URL or a header substitutes to the value at egress, and only
+   *  towards the ORIGINS in `urls` (required: a secret is always pinned). In a JSON body it does
+   *  so only at a field that the secret names (`SecretUses.bodyFields`). `set` stores a string or a
+   *  JSON object (`refresh` names the strategy that re-mints an expiring credential); `delete`
+   *  forgets it (re-settable); `list` is the catalog — paths, pins, strategy kinds, when first set,
+   *  public fields — never a secret value. Every change is one fact on the secret's path
+   *  (`secret/set`, `secret/deleted`), attributed to the caller and cross-posted to the root, so the
+   *  log says who set what and when. No fact carries the value, sealed or not. */
+  secrets: {
+    set(
+      path: string,
+      /** Null for a secret that goes by proxy (`options.proxy`), and only for one. */
+      material: SecretMaterial | null,
+      /** The material and its options replace the whole of what the secret held. `public`: the
+       *  names of the material's top-level string fields that are no secret (an OAuth client's
+       *  `clientId`): the `secret/set` fact carries their values and `describe` answers them.
+       *  `placement`, `operations` and `lendTo` (`SecretUses`) fix what the secret may be used for:
+       *  where its placeholder may sit, the operations it answers, and the secrets whose refresh may
+       *  borrow it. */
+      options: {
+        urls: string[];
+        refresh?: SecretRefresh;
+        merge?: boolean;
+        public?: string[];
+        /** With it, `material` is null and only `urls` and `placement: "header"` go beside it. */
+        proxy?: SecretProxy;
+      } & SecretUses,
+    ): Promise<{ path: string }>;
+    /** OAuth's first tokens: the link to send a human to — the secrets Worker's start page on the
+     *  platform's hostname, which shows the secret, the origins its tokens go to and what else they
+     *  may be used for, and whose Continue sends the browser on to the provider's consent page. A
+     *  signed-in member opens it, or anyone with `anyoneWithLink`. The provider redirects to the
+     *  secrets Worker's callback, which completes only in the browser shown that page; the secret's
+     *  object exchanges the code, `secret/set` lands, and the callback redirects to `next`. The
+     *  provider's URL and the PKCE verifier stay in the secrets Worker. The attempt lasts an hour.
+     *  `nonce` names it; a later `beginOAuth` on the same path replaces it. */
+    beginOAuth(
+      path: string,
+      options: SecretOAuthOptions,
+    ): Promise<{ authorizationUrl: string; nonce: string }>;
+    /** What became of the attempt `nonce` (`beginOAuth`'s answer), for the page `next` lands on:
+     *  `complete` with the scopes the provider granted and, with `account`, the account the tokens
+     *  are for; `pending` while it is in flight; `declined` with the provider's `error`
+     *  (`access_denied`) when the person said no at the provider, or `failed` with any other
+     *  `error` it sent back (for example `server_error`), until a later consent on the same link
+     *  completes it; `unavailable` once it expired, a newer attempt replaced it, or a write since
+     *  superseded its tokens. Never a token. */
+    oauthResult(
+      path: string,
+      input: { nonce: string },
+    ): Promise<
+      | { status: "pending" }
+      | { status: "complete"; scopes: string[]; account?: { id: string; name: string | null } }
+      | { status: "declined" | "failed"; error: string }
+      | { status: "unavailable" }
+    >;
+    /** The redirect URI to register at a provider for a client of your own: the platform's one
+     *  callback, `<platform origin>/secrets/oauth/callback`. */
+    oauthCallbackUrl(): Promise<string>;
+    delete(path: string): Promise<{ path: string }>;
+    /** Deletes the secret at `path` only while it goes by proxy, with no write, live OAuth attempt
+     *  or live key form in flight, all decided in one turn of the secret's object; else deletes
+     *  nothing (`deleted: false`), with no throw. It names no proxy: none can be set over another
+     *  without a delete between, so `describe` first tells whose proxy it is. A rule on the exact
+     *  name `itx.secrets.delete` does not hold this verb; a rule on `itx.secrets.*` holds both. */
+    deleteIfProxy(path: string): Promise<{ path: string; deleted: boolean }>;
+    /** Whether the secret at `path` is set, never its value: by a value, or by proxy with
+     *  `proxy` and no value here. `set` is false for a path that holds neither, one never set
+     *  included. A read alone: no fact. The answer has more fields
+     *  (`SecretDescription`, iterate/workers). */
+    describe(path: string): Promise<{ path: string; set: boolean; proxy?: SecretProxy }>;
+    list(): Promise<SecretCatalogEntry[]>;
+    /** A secret's stored cell as text, for a backup: ciphertext that only the stack's at-rest key
+     *  opens, handed to a caller whose `proof` is the HMAC-SHA256 of
+     *  `[path, "exportSealed", until]` as JSON under that key. `until` is when the proof ends, in
+     *  milliseconds since the epoch, five minutes ahead at most. One fact on the secret's path
+     *  says that it left. */
+    exportSealed(path: string, proof: string, until: number): Promise<{ sealed: string }>;
+    /** A sealed cell, taken in once: one that `exportSealed` handed out on a stack with the same
+     *  at-rest key, which comes back as it was. `proof`: the HMAC-SHA256 of `[path, cell]` as JSON
+     *  under that key.
+     *  AN OLDER CELL IS TAKEN OVER A NEWER VALUE, once: that is what a restore is for. A proxy's
+     *  cell goes only over nothing, as its `set` does. An older genuine cell of the path still
+     *  imports over nothing, so an archive can bring back a secret, or a proxy, that the owner
+     *  has replaced since (main's behaviour for a value too). A cell of
+     *  a grant whose refresh token works once holds a token that is spent by then. */
+    importSealed(path: string, cell: string, proof: string): Promise<{ path: string }>;
+    /** The persons' grants that the iterate Cloud brokers, refreshed now, whichever client of the
+     *  Cloud a grant is of: one row for each. core/secrets-worker/src/grant-refresh.ts says why a
+     *  mind asks for this, and when.
+     *  `fresh`: refreshed within the last hour, and left alone. `failed`: the secret is as it
+     *  was, and the person may have to connect again. `answerLost`: no answer came, so nobody
+     *  refused; the next refresh tells if the grant still stands. */
+    refreshGrants(): Promise<
+      (
+        | { path: string; outcome: "refreshed" | "fresh" }
+        | { path: string; outcome: "failed"; error: string; answerLost?: true }
+      )[]
+    >;
+    /** The iterate Cloud at `origin` (an exact `https:` origin, no path: iterate's own is
+     *  `https://cloud.iterate.com`), and the names of the clients that Cloud publishes: each is a
+     *  `client: { cloud: <name>, origin }` of `beginOAuth`. No client when the Cloud gave no
+     *  list. */
+    cloud(origin: string): Promise<{ origin: string; clients: string[] }>;
+    /** Always false: the stack makes no OAuth client at Cloudflare. A config that asks connects
+     *  with no stack client. */
+    hasStackClient(name: StackClientName["stack"]): Promise<boolean>;
+    /** The link to a form on the platform's own hostname where a person enters a value an agent
+     *  must never see in chat. The form shows the secret's path, its pin, what it may be used for
+     *  (`SecretUses`) and `description` as the requester's words, and answers a signed-in member
+     *  alone unless `anyoneWithLink`. */
+    collectFromUser(input: CollectSecretInput): Promise<CollectSecretLink>;
+    /** A webhook's signature checked against a secret WITHOUT revealing it: one bit back,
+     *  constant-time, run in the secrets Worker. A material with no key at the field answers false.
+     *  Like every operation, only a secret made with it in `operations` answers, within a limit
+     *  per minute (`SecretUses`). */
+    verifyHmac(path: string, input: SecretHmacVerification): Promise<boolean>;
+    /** The HMAC-SHA256 of `payload` under a secret, WITHOUT revealing it: the signature comes back,
+     *  the key never does, run in the secrets Worker. For a provider that proves an endpoint by a
+     *  challenge only the key's holder can answer (X's CRC). A secret never set, or a material with
+     *  no key at the field, is refused (`SECRET_NOT_SET`); so is a secret not made with it in
+     *  `operations` (`FORBIDDEN`). */
+    signHmac(path: string, input: SecretHmacSigning): Promise<string>;
+    /** A presented string compared with a secret WITHOUT revealing it, for a credential a caller can
+     *  only send as it is (a webhook's static header token): one bit back, constant-time, run in the
+     *  secrets Worker, for a secret made with it in `operations`. No string at the field answers
+     *  false. A replayable token stays replayable: prefer `verifyHmac` wherever the sender signs. */
+    verifyEquals(path: string, input: SecretEqualsVerification): Promise<boolean>;
+    /** A P-256 key made in the secrets Worker and kept at `path`, its private half never outside
+     *  it: not in `describe`, not through a placeholder (a signing secret is never sent), not lent.
+     *  The answer and `describe`'s `public` give its public half (`publicKey`, SPKI DER as
+     *  base64url) and `keyId` (`keyIdOf` of iterate/signed), what a mind's `auth.keys` trusts. It
+     *  answers `signStatement`, with `statementPaths` as its limit. To keep a key made elsewhere,
+     *  collect it instead (`collectFromUser` with one field `privateKey`, the private JWK as JSON,
+     *  and `operations: ["signStatement"]`): a secret made to sign takes only such a material. */
+    generateSigningKey(
+      path: string,
+      options?: Pick<SecretUses, "statementPaths">,
+    ): Promise<{ path: string; publicKey: string; keyId: string }>;
+    /** A signed statement under the secret's P-256 key, as a mind's `POST /statements` takes it
+     *  (iterate/signed `Envelope`). Only a secret made with it in `operations` answers, within its
+     *  limit per minute, and only for a `path` under its `statementPaths`; a secret with an
+     *  approval rule signs nothing (`FORBIDDEN`). */
+    signStatement(path: string, input: SecretStatementSigning): Promise<Envelope>;
+    /** `plaintext` sealed under a key derived from the secret's (`SecretSealing`), the key never
+     *  outside the secrets Worker; for a secret made with it in `operations`. A secret with an
+     *  approval rule seals nothing (`FORBIDDEN`), as it signs nothing. */
+    seal(path: string, input: SecretSealing): Promise<string>;
+    /** A `seal` answer opened again, for a secret made with it in `operations`. A value that does
+     *  not open under this secret and `info` is refused (`INVALID_INPUT`). */
+    unseal(path: string, input: SecretUnsealing): Promise<string>;
+  };
+  /** The mind's fetch routes, on its root `/`: which itx expression, the route's `target`, a
+   *  request on its hosts goes to. `set` appends one `itx/fetch-route-configured` fact (`null`
+   *  deletes the route); `match` answers the route a request takes. The platform serves a request a
+   *  route takes from `route.target` (a WebSocket upgrade included), before the config worker's
+   *  fetch; a write answers once no host is served from the routes before it. */
+  fetchRoutes: {
+    set(fetchRouteName: string, route: FetchRouteInput | null): Promise<{ fetchRouteName: string }>;
+    list(): Promise<FetchRouteEntry[]>;
+    match(request: {
+      url: string;
+      headers: Headers | Record<string, string> | [string, string][];
+    }): Promise<FetchRouteEntry | null>;
+  };
+  /** The table this context resolves against, described — the tree a model reads. `list()` follows a
+   *  bare hop row into the context it names (a Durable Object hop, hence async). */
+  rewriteRules: {
+    /** `depth`: how many bare hop rows to follow (default: all). */
+    list(depth?: number): Promise<RewriteRuleListEntry[]>;
+    get(match: string): Promise<RewriteRuleListEntry | null>;
+    resolve(call: ItxExpressionInput): string[];
+  };
+  /** A facet of this context: a caller reaches only what its class lists in `static publicMethods`
+   *  (sdk/index.ts `FacetDurableObject`); anything else is refused FORBIDDEN. */
+  facets: {
+    /** The facet `name` — addressed when it is running (a processor, a named instance), loaded and
+     *  hosted from `spec` otherwise. `Facet` types its methods for the caller
+     *  (`facets.get<{ snapshot(): Promise<Snapshot> }>("x").snapshot()`): an UNCHECKED assertion,
+     *  like a cast — nothing verifies the hosted class has them, so name the facet's own published
+     *  type where there is one. A capnweb `RpcStub` of this interface erases the type parameter:
+     *  there, cast the handle instead. */
+    get<Facet = unknown>(name: string, spec?: FacetSpec): InvokeHandle & Facet;
+    /** RESET one facet of this context, from the context that hosts it — any facet, whether or not
+     *  it extends the SDK's host, including one that would never answer a call. Its instance and
+     *  in-memory state go, and every call in flight on it rejects `FACET_ABORTED`; its storage
+     *  stays, and its next call starts it fresh. The context itself is not reset. Resolves with the
+     *  `events.iterate.com/itx/facet-aborted { name, reason?, callerPath?, app? }` event;
+     *  `NO_FACET` for a name never hosted here. */
+    abort(name: string, reason?: string): Promise<StreamEvent>;
+  };
+  subscriptions: {
+    list(): SubscriptionListEntry[];
+    get(name: string): SubscriptionListEntry | null;
+  };
+  /** The rpc stubs lent to this context right now, by key (a live session's `provide`): `get(key)`
+   *  one, as a handle over its transport (offline ⇒ RPC_STUB_OFFLINE at call time). */
+  rpcStubs: { get(rpcStubKey: string): InvokeHandle; list(): string[] };
+  /** THE MIND'S CATALOG OF ITS CONTEXTS, on the mind's root: `list(options)` answers what each
+   *  context last said about itself, the most recently active first, and which are awake now. A
+   *  context says it when it has had work, so a row is at most one wake behind its log
+   *  (core/itx/src/context/context-catalog.ts).
+   *
+   *  `watch(query, onFrame, options?)` keeps answering a query: the catalog calls `onFrame` with
+   *  the answer, and then with each change to it, for as long as the handle lives
+   *  (core/itx/src/context/reactive-catalog.ts). The call resolves when `onFrame` has returned
+   *  from the answer. It rejects with the reason, and each reason has its code: `INVALID_INPUT`
+   *  for a query that the catalog cannot answer exactly, `WATCH_LIMIT` when the session has 64
+   *  watches or the mind 512 different live queries, `UNAVAILABLE` when the catalog could not be
+   *  reached or did not answer, `FORBIDDEN` for loaded code. It is a session's call: the frames
+   *  ride the session's own connection, and the session's end closes every watch. The handle's
+   *  `ended()` settles with the reason when the watch ends: the watcher's own dispose, the
+   *  session's end, or a catalog that could not be reached again, after which the watcher
+   *  watches again. Who may `list` may `watch`. `options.cursor` says what the watcher holds
+   *  already. `watches()` answers who watches what: it names the paths and the facts that other
+   *  sessions ask for, so it is a session's call too, and loaded code is refused (`FORBIDDEN`). */
+  contexts: {
+    list(options?: ContextListOptions): Promise<ContextListing[]>;
+    watch<Query extends CatalogQuery>(
+      query: Query,
+      onFrame: (
+        frame: CatalogFrame<Query extends { awake: true } ? CatalogAwakeRow : CatalogRow>,
+      ) => void,
+      options?: { cursor?: CatalogCursor },
+    ): Promise<{ ended(): Promise<string>; [Symbol.dispose](): void }>;
+    watches(options?: { verify?: boolean; plans?: boolean }): Promise<CatalogWatches>;
+  };
+  processors: {
+    enable(
+      name: string,
+      spec?: (FacetSpec & { consumes?: string[] }) | { consumes?: string[] },
+    ): Promise<{ name: string }>;
+    disable(name: string): Promise<void>;
+    list(): SubscriptionListEntry[];
+    /** A hosted processor's claim on this context's alarm: "revive me by `at`" (a facet with a
+     *  `runInBackground` attempt in flight), or `null` to release it. */
+    claim(name: string, at: number | null): Promise<void>;
+  };
+  workers: {
+    /** A stateless worker loaded from `spec`: `mainModule` loads that module of the source as its
+     *  entry in place of package.json's `main`. `source` is as `FacetSpec`'s: an expression with no
+     *  `cacheKey` is the NAME of a loaded worker (`itx.cd('/').config`), whose code each call loads,
+     *  `mainModule` as the mind's publication of it recorded it. */
+    get(spec: {
+      source: WorkerSource;
+      cacheKey?: string;
+      mainModule?: string;
+      className?: string;
+      props?: unknown;
+    }): InvokeHandle;
+  };
+  /** HTTP WEBHOOKS, the target of a fan-out row that sends each event to another server, Stripe's
+   *  way: `webhooks.get({ url, signingSecret? }).deliverEvent` POSTs the event as JSON from this
+   *  context through its own `itx.fetch` (a context that may not fetch sends nothing), with
+   *  `iterate-event-id: <mindId><path>@<offset>` (repeats share it) and, given a signing secret (a secret
+   *  path pinned to `url`'s origin), `iterate-timestamp` and `iterate-signature: v1=<hex
+   *  HMAC-SHA256 of "<timestamp>.<body>">`. A 2xx acks; any other status retries on the event's own
+   *  ladder (~44 h); a 410 halts the row until a resume. `deliverEvent` is the delivery loop's call
+   *  alone. A signature vouches for the MIND, not a context: a receiver checks the body's `path`,
+   *  and loaded code names a signing secret only at the mind's root. */
+  webhooks: {
+    get(spec: {
+      url: string;
+      signingSecret?: string;
+      /** The MCP Events subscription it delivers: each event as an `event.appended` occurrence,
+       *  signed per Standard Webhooks with `signingSecret` (our MCP server's `events/subscribe`). */
+      mcpSubscription?: string;
+    }): InvokeHandle;
+  };
+  /** ANOTHER MIND THAT LETS THIS ONE IN (core/configs/default/minds.md), as a row's target:
+   *  `minds.get("<domain>").deliverEvents` (or `deliverEvent` on a fan-out row) signs each event
+   *  with this mind's key and posts it to that mind, which adds it under
+   *  `/minds/<this mind><the event's path>`. `minds.get("<domain>").at("<path>").deliverEvents`
+   *  adds each event at that one context of the other mind instead, when its rule lets this mind
+   *  append there. `itx/*` and `mind-meld/*` events are not sent. Any
+   *  answer but a 200 throws, so the row tries again and ends in a dead letter. The delivery
+   *  loop's call alone.
+   *  THE KERNEL'S LOOP COUNT DOES NOT CROSS A MIND'S EDGE: never answer another mind's request or
+   *  event with one to that mind unless the app bounds the exchange itself. A nest of requests
+   *  ends only at Cloudflare's limit (a 503 at about the 14th); a chain of events never ends. */
+  minds: {
+    /** `.fetch(request)`: an https request to that mind, signed as this mind. One Request and
+     *  nothing more; no WebSocket. It is the `itx.fetch(request, { signFor: domain })` of the
+     *  context where dispatch starts, so that context's rule for `itx.fetch` decides it. For loaded
+     *  code that is the caller, wherever the call is spelled: `minds` is answered at the caller, so
+     *  its `itx.cd(<a limited context>).minds.get(x).fetch(request)` signs when its own fetch is
+     *  free. A member's `itx.cd(<context>)` handle starts dispatch at that context, so there that
+     *  context's fetch decides. A mask refuses it, and a narrow fetch sends it on without the
+     *  built-in's signature. A context signs wherever it can reach the built-in fetch unchanged, its own or
+     *  another context's by `itx.cd`, exactly as it can fetch there: a table that masks its own
+     *  fetch and leaves `itx.cd('/')` open has not narrowed fetch. Each try leaves `events.iterate.com/itx/signed-request-sent` on the
+     *  calling context's log, written when egress settles, whether or not the caller waits for
+     *  the answer; on a context's own object the local write runs before the caller goes on. It
+     *  holds the URL's origin and path, never its query: a path can itself hold a token. Its `source` names who asked by
+     *  the same fields as any event of that caller: the principal with its grant, and for loaded
+     *  code the person it runs for (`onBehalfOf`); code that runs for nobody is named by nobody. When a
+     *  member's page makes the call through a context's fetch channel, the source has the member
+     *  and not `via.appPage`, because that channel carries no `via`; an ordinary append of the
+     *  same page keeps it. */
+    get(domain: string): InvokeHandle & { fetch(request: Request): Promise<Response> };
+  };
+  /** A subscription: a pure itx expression, or a live callback lent to the registry (what live state
+   *  uses); `null` removes the row. The handle's dispose removes it too. */
+  subscribe(input: {
+    name?: string;
+    target:
+      | ItxExpressionInput
+      | ((events: unknown[], range: unknown) => void)
+      | EventCopyTarget
+      | null;
+    consumes?: string[];
+    afterOffset?: number;
+    /** `false`: FAN-OUT delivery — one event per call (`deliverEvent(event)`), in any order, each
+     *  retried and dead-lettered on its own. Absent: the ordered queue, the one that may take a
+     *  dead letter (`itx/subscription-delivery-failed`): alert on dead letters from an ordered row. */
+    ordered?: false;
+    /** With an `EventCopyTarget`, the row COPIES each event it takes onto the log at the target's
+     *  `path`. It's always `ordered: false`, and each copy gets a `source.copiedFrom` saying which
+     *  event it copies. `filter` is only for such a row: a JSONata expression over the event, and
+     *  only events it answers exactly `true` for are copied.
+     *
+     *  An expression that doesn't compile, or uses something forbidden
+     *  (core/itx/src/stream/event-expressions.ts), makes `subscribe` throw. One that throws on a
+     *  particular event fails that event's delivery, which is retried like any other. `itx/*`
+     *  events are never copied. Copies can land in any order, so read `copiedFrom` to see when and
+     *  where each original happened. */
+    filter?: string;
+  }): Promise<{ [Symbol.dispose](): void }>;
+  /** A rewrite rule of this context, session-scoped (the handle's dispose removes it): make `match`
+   *  mean `target`, an expression, a live stub, or null to deny. `description` is the one line a
+   *  model reads for the name. `fetchRoute` (a live stub, on the mind's root) is a fetch route to
+   *  `match` that lives exactly as long as the lend: set with it, set again when the platform
+   *  re-attaches it, removed when it ends however it ends. A live stub's handle answers
+   *  `lendEnded()` with why the lend ended — it can end while the session lives (the platform lost
+   *  its pager). The durable spelling is the rule's event (`RewriteRuleConfigured`) through
+   *  `itx.append`. */
+  provide(
+    match: ItxExpressionInput,
+    // Expressions, null, or live RPC references (RpcTarget / callable), serialized by capnweb.
+    target: unknown,
+    options?: {
+      description?: string;
+      fetchRoute?: Omit<FetchRouteInput, "target"> & { fetchRouteName: string };
+      /** A live stub's lend takes the name only when no other lender (`lentBy`) holds it. */
+      onlyFromItself?: true;
+    },
+  ): Promise<{ [Symbol.dispose](): void; lendEnded(): Promise<string> }>;
+  /** A script — the text of `async (itx) => { … }` — run once against this context, on its log:
+   *  `itx/run-requested` under the caller, the context's runner, `run-settled` (JSON in, JSON
+   *  out); resolves with the result or rejects with the settlement's error. Never re-run. A script
+   *  still running ten minutes after it started is settled failed (`failureKind: "deadline"`). */
+  run(script: string): Promise<unknown>;
+  /** The mind's repos and workspaces as domain objects — one shape each: `get(path)` is
+   *  the entity's facet on the context at `path` (its verbs, plus the typed `append` on that
+   *  context), `list()` the mind catalog, `create(path)` the creation saga on that path (the
+   *  parent link the caller's context writes first, then the processor row, the request, the
+   *  terminal fact — created, or create-failed thrown), `delete(path)` the deletion saga (the
+   *  request, `deleted` cross-posted to `/`, the row disabled). A relative `path` means the caller's. */
+  repos: EntityCollectionApi<RepoHandle>;
+  workspaces: EntityCollectionApi<WorkspaceHandle>;
+  /** Linux containers whose filesystem is kept as a snapshot: `create(path)` once, then `get(path).exec(["make", "test"])`. */
+  sandboxes: EntityCollectionApi<SandboxHandle>;
+  /** Workers AI's binding (`ItxAiApi`), under this context's capability rules. */
+  ai: ItxAiApi;
+  /** Cloudflare Browser Run. */
+  browser: CfBrowserApi;
+  /** Cloudflare Images: `info` and `transform` over image bytes. */
+  images: CfImagesApi;
+  /** Cloudflare Artifacts, mind-scoped (`repos` is the friendlier surface). */
+  cfArtifacts: CfArtifactsApi;
+  /** ONE COMMIT ON A GIT REMOTE'S `main`, with no repo of this mind: nothing is kept here, no
+   *  context, no copy of the remote's files and no event. The tip is read, `changes` are applied
+   *  to its files (whole files, as `repos.get(path).commitFiles` takes them), and the commit is
+   *  pushed, compare-and-swapped on the tip that was read and never forced: a commit that landed
+   *  meanwhile refuses it, and a second call reads the tip anew. `remote` is a git URL over
+   *  HTTP(S) whose userinfo may hold a secret placeholder, never a token; the requests leave by the
+   *  caller's own `itx.fetch`. A remote whose `main` has no commit is refused: the first commit of
+   *  a repo is its owner's. With no path changed, nothing is pushed and `commitOid` is the tip. */
+  git: {
+    commitFiles(input: {
+      remote: string;
+      message: string;
+      changes: RepoFileChange[];
+      author?: { name: string; email: string };
+    }): Promise<{ commitOid: string; parent: string; changedPaths: string[] }>;
+  };
+  /** Files stored in the mind's object store, by path (`r2` underneath). */
+  files: {
+    get(path: string): InvokeHandle & FileHandle;
+    list(prefix?: string): Promise<FileRecord[]>;
+  };
+  /** THE MIND'S TELEMETRY (docs/telemetry.md): `query(sql, { hours })` runs one SELECT, cut to
+   *  this mind's rows of the last `hours` (default 24), and answers the rows with the SQL that ran.
+   *  Over one of Cloudflare's own datasets (`TELEMETRY_DATASETS`: `logs.workersLogs`,
+   *  `logs.traces`, `logs.issues`, `events.workersInvocations`, and `metrics`, the stack's own
+   *  Analytics Engine dataset) it needs no token: Cloudflare's Analytics SQL, as Cloudflare's
+   *  docs write it, with no JOIN, subquery, UNION, CTE, comment or `$`; at most 168 hours over the
+   *  three logs and 768 over the other two. It reads the log lines of every Worker of the
+   *  mind's stack, and the spans of the mind's and the boundary's alone. Over the tables `events`, `logs` and `spans` (R2 SQL, at most 720
+   *  hours) it needs the stack's telemetry token. A stack with no telemetry tables answers a
+   *  notice for a table query, with no rows. `query` is the platform's alone, under this one
+   *  name. */
+  telemetry: {
+    query(sql: string, options?: { hours?: number }): Promise<TelemetryRows>;
+  };
+  /** WHO IS A MEMBER OF THE MIND NOW, as the stack's sign-in knows it: the addresses its config
+   *  names and the members an owner added. `has(email)` answers true or false. The mind's own
+   *  code asks it to decide whose words from outside, such as a chat message, are a member's. */
+  members: { has(email: string): Promise<boolean> };
+  /** The mind's email, `<slug>@iterate.app` (core/lib/src/email.ts has its events and
+   *  threads). `send` answers the `email/sent` event. */
+  email: {
+    send(input: EmailSendInput): Promise<StreamEvent>;
+  };
+  /** WHAT WAITS FOR A MEMBER'S SIGNED YES before it is done (./acts.ts): a mail, or a call of a
+   *  verb, that a rule names. `setRules` replaces the rules while they are open; once a member
+   *  locked them it is refused, and `propose` asks a member to sign one rule at `signAt`. A rule
+   *  for a request with a secret is a member's alone to put in force: `propose` is the one way
+   *  for code or an agent to ask for one. */
+  approvals: {
+    rules(): Promise<{ locked: boolean; rules: ActRule[] }>;
+    setRules(rules: ActRule[]): Promise<ActRule[]>;
+    /** With `secret`, a rule for a request with that secret is proposed: the mind's code sets no
+     *  such rule, and a member signs the proposal into one or rejects it. */
+    propose(
+      rule:
+        | ActRule
+        | {
+            secret: string;
+            methods: string[];
+            hosts: string[];
+            jsonStrings?: string[];
+            freePaths?: string[];
+          },
+    ): Promise<{ id: string; signAt: string }>;
+    /** One event for a person to sign with a passkey at `signAt`, a page that needs no sign-in,
+     *  for a day. Signed, it lands on `path` with the person as `event.source.signer`, whose
+     *  `member` says whether a member signed. `next`: where the page goes then, an https URL on a
+     *  host of the mind. `signerEmail`: the one person who signs; a non-member signs at
+     *  `/people/<address>` alone. */
+    proposeStatement(input: {
+      path: string;
+      type: string;
+      payload?: Record<string, unknown>;
+      signerEmail?: string;
+      next?: string;
+    }): Promise<{ draft: string; signAt: string; expires: number }>;
+  };
+  /** An MCP server over Streamable HTTP, through this context's egress; its events subscribed to
+   *  land on this context. */
+  connectToMcp(url: string, options?: McpConnectOptions): Promise<McpConnectionApi>;
+  /** An OpenAPI 3 service from its document or the URL of one, through this context's egress. */
+  connectToOpenApi(
+    specOrUrl: string | OpenApiDocument,
+    options?: OpenApiConnectOptions,
+  ): Promise<OpenApiConnectionApi>;
+  /** A remote capnweb API's main object — a WebSocket session through egress (default) or one
+   *  HTTP batch per chain (`{ transport: "batch" }`). */
+  connectToCapnweb(url: string, options?: CapnwebConnectOptions): Promise<CapnwebConnectionApi>;
+}
A core/lib/src/app-config.test.ts
@@ -0,0 +1,143 @@
+// app-config.test.ts — the mechanism every Worker's config goes through: the object and its vars
+// composed under the config's prefix, a key the schema does not name warned about in both
+// spellings and dropped, and a malformed field refused. Each schema's own fields
+// are its app's table (scripts/lib/start-app.test.ts).
+import { expect, test, vi } from "vitest";
+import { z } from "zod";
+import { configVarNameOf, httpOrigin, optionalOrigin, parseAppConfigVars } from "./app-config.ts";
+
+/** A schema with each shape the walk meets: a prefaulted block, an optional one, a record, an array
+ *  of objects. */
+const Schema = z.object({
+  urls: z.object({ os: httpOrigin, dash: optionalOrigin }).prefault({ os: "" }),
+  routing: z.object({ type: z.string() }).optional(),
+  labels: z.record(z.string(), z.string()).default({}),
+  routes: z.array(z.object({ pattern: z.string() })).optional(),
+});
+
+const IGNORED = "not in the schema, ignored — remove it, or add it to the schema";
+
+test.for<{
+  name: string;
+  /** the config's name; `ITERATE` when unset */
+  prefix?: string;
+  env: Record<string, string>;
+  becomes?: unknown;
+  throws?: RegExp;
+  /** every warning printed, in order: one per key the schema does not name */
+  warns?: string[];
+}>([
+  {
+    name: "the object and a var compose, and a record's keys are its own",
+    env: {
+      ITERATE: JSON.stringify({ urls: { os: "https://os.test" }, labels: { anything: "kept" } }),
+      ITERATE__URLS__DASH: "https://dash.test",
+    },
+    becomes: {
+      urls: { os: "https://os.test", dash: "https://dash.test" },
+      labels: { anything: "kept" },
+    },
+  },
+  {
+    name: "a key inside the object the schema does not name",
+    env: {
+      ITERATE: JSON.stringify({ urls: { os: "https://os.test", mcp: "https://mcp.test" } }),
+    },
+    becomes: { urls: { os: "https://os.test", dash: "" }, labels: {} },
+    warns: [`ITERATE urls.mcp (ITERATE__URLS__MCP): ${IGNORED}`],
+  },
+  {
+    name: "a var no field answers to, named where it leaves the schema",
+    env: { ITERATE__URLS__OS: "https://os.test", ITERATE__URL__DASH: "https://dash.test" },
+    becomes: { urls: { os: "https://os.test", dash: "" }, labels: {} },
+    warns: [`ITERATE url (ITERATE__URL): ${IGNORED}`],
+  },
+  {
+    name: "a stray key inside an optional block a var sets whole",
+    env: { ITERATE__URLS__OS: "https://os.test", ITERATE__ROUTING: '{"type":"paths","x":1}' },
+    becomes: { urls: { os: "https://os.test", dash: "" }, routing: { type: "paths" }, labels: {} },
+    warns: [`ITERATE routing.x (ITERATE__ROUTING__X): ${IGNORED}`],
+  },
+  {
+    name: "a malformed field, even beside a key the schema does not name",
+    env: { ITERATE__URLS__OS: "os.test", ITERATE__URLS__MCP: "https://mcp.test" },
+    throws: /^ITERATE urls\.os \(ITERATE__URLS__OS\): expected an HTTP\(S\) origin/,
+    warns: [`ITERATE urls.mcp (ITERATE__URLS__MCP): ${IGNORED}`],
+  },
+  {
+    name: "a field lands on the object its parent var sets, whatever order the environment lists them in",
+    env: {
+      ITERATE__URLS__OS: "https://os.test",
+      ITERATE__ROUTING__TYPE: "subdomains",
+      ITERATE__ROUTING: '{"type":"paths"}',
+    },
+    becomes: {
+      urls: { os: "https://os.test", dash: "" },
+      routing: { type: "subdomains" },
+      labels: {},
+    },
+  },
+  {
+    name: "a stray key inside an array's element",
+    env: {
+      ITERATE__URLS__OS: "https://os.test",
+      ITERATE__ROUTES: '[{"pattern":"a/*","zone":"z"}]',
+    },
+    becomes: {
+      urls: { os: "https://os.test", dash: "" },
+      routes: [{ pattern: "a/*" }],
+      labels: {},
+    },
+    warns: [`ITERATE routes.0.zone (ITERATE__ROUTES__0__ZONE): ${IGNORED}`],
+  },
+  {
+    name: "a binding that shares the name's first word is not the config's",
+    env: {
+      ITERATE__URLS__OS: "https://os.test",
+      ITERATE_CONTEXT: "a binding",
+    },
+    becomes: { urls: { os: "https://os.test", dash: "" }, labels: {} },
+  },
+  {
+    name: "another config's name reads only its own variables",
+    prefix: "ITERATE_APP",
+    env: {
+      ITERATE_APP: JSON.stringify({ urls: { os: "https://os.test" } }),
+      ITERATE_APP__URLS__DASH: "https://dash.test",
+      ITERATE__LABELS: '{"other":"config"}',
+    },
+    becomes: { urls: { os: "https://os.test", dash: "https://dash.test" }, labels: {} },
+  },
+  {
+    name: "an app's ITERATE_APP never reads the platform's ITERATE or ITERATE__*",
+    prefix: "ITERATE_APP",
+    env: {
+      ITERATE: JSON.stringify({ urls: { os: "https://platform.test" } }),
+      ITERATE__URLS__DASH: "https://platform-dash.test",
+      ITERATE_APP__URLS__OS: "https://os.test",
+    },
+    becomes: { urls: { os: "https://os.test", dash: "" }, labels: {} },
+  },
+  {
+    name: "the platform's ITERATE never reads an app's ITERATE_APP or ITERATE_APP__*",
+    env: {
+      ITERATE__URLS__OS: "https://os.test",
+      ITERATE_APP: JSON.stringify({ urls: { dash: "https://app-dash.test" } }),
+      ITERATE_APP__URLS__DASH: "https://app-dash.test",
+    },
+    becomes: { urls: { os: "https://os.test", dash: "" }, labels: {} },
+  },
+])("parseAppConfigVars: $name", ({ prefix = "ITERATE", env, becomes, throws, warns = [] }) => {
+  const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+  if (throws) expect(() => parseAppConfigVars(env, Schema, { prefix })).toThrow(throws);
+  // exact: a key the schema does not name is never kept
+  else expect(parseAppConfigVars(env, Schema, { prefix })).toEqual(becomes);
+  expect(warn.mock).toMatchObject({ calls: warns.map((message) => [message]) });
+});
+
+test("configVarNameOf: a field's var is its path, `__` before each part, each part in SNAKE_CASE", () => {
+  expect(
+    configVarNameOf(["integrations", "github", "oauthClientSecret"], { prefix: "ITERATE" }),
+  ).toBe("ITERATE__INTEGRATIONS__GITHUB__OAUTH_CLIENT_SECRET");
+  expect(configVarNameOf(["adminBearer"], { prefix: "ITERATE" })).toBe("ITERATE__ADMIN_BEARER");
+});
A core/lib/src/app-config.ts
@@ -0,0 +1,255 @@
+// app-config.ts — THE PREFIXED CONFIG MECHANISM: how a Worker of ours reads what differs between
+// deployments of the same code. ONE JSON object under a prefix of the Worker's own — the apps'
+// `ITERATE_APP`, for one — checked against the Worker's own zod schema; loud on anything
+// malformed, naming the field. A value left out takes its schema's default.
+//
+// Any key can also be set ALONE as a var: the name, then the path, `__` before every segment and
+// each segment in SNAKE_CASE: `ITERATE__URLS__OS`, `ITERATE__SECRETS_ENCRYPTION__KEY`,
+// `ITERATE_APP__URLS__OS`. The parser merges it on top of the object, so a deployment's vars and its
+// secrets compose, and a laptop's gitignored `.dev.vars` names one local origin without restating
+// the rest. A blank var is unset. A key the schema does not name, in the object or as a var, is
+// warned about loudly and dropped, never silently kept. A var under the prefix with ONE underscore
+// (`ITERATE_CONTEXT`, a binding, or the apps' `ITERATE_APP`) is not the config's.
+//
+// The apps' schema is in packages/shared/src/start-app-config.ts.
+
+import { z } from "zod";
+
+/** Which config: the object's variable, and the prefix of every one-field variable
+ *  (`<prefix>__<PATH>`). */
+export type ConfigPrefix = { prefix: string };
+
+/** Parse `schema` out of `env` (a worker env, or any record — only `<prefix>` and the
+ *  `<prefix>__*` keys are read; a blank one is unset). Pure. A malformed field throws naming
+ *  itself in both spellings (`fieldNameOf`); a key the schema does not name is warned about, named
+ *  the same way, and dropped. Unknown keys are tolerated because parallel branches add keys; a key
+ *  one branch adds must not fail another's deploy — owner decision 2026-09-26. */
+export function parseAppConfigVars<Schema extends z.ZodTypeAny>(
+  env: object,
+  schema: Schema,
+  config: ConfigPrefix,
+): z.output<Schema> {
+  return parseAppConfig(appConfigInputOf(env, config), schema, config);
+}
+
+/** The config's object as `env` gives it, before the schema: `<prefix>` with every `<prefix>__*`
+ *  override merged on top, the deeper path last. `<prefix>` is the object as JSON text (a plain
+ *  variable) or the object itself (a Workers JSON binding). Pure. What `parseAppConfigVars`
+ *  parses. */
+export function appConfigInputOf(env: object, { prefix }: ConfigPrefix): Record<string, unknown> {
+  const configEnv: Record<string, string> = {};
+  let boundObject: PlainObject | undefined;
+  for (const [key, value] of Object.entries(env)) {
+    if (!(key === prefix || key.startsWith(`${prefix}__`))) continue;
+    if (key === prefix && isPlainObject(value)) boundObject = value;
+    if (typeof value !== "string" || !value.trim()) continue;
+    configEnv[key] = value;
+  }
+  return deepMerge(
+    boundObject || objectOf(configEnv[prefix], prefix),
+    overridesOf(configEnv, prefix),
+  );
+}
+
+/** Parse `schema` out of the config's object, `raw` (`appConfigInputOf`'s, or a config file's).
+ *  Pure. Fails and warns as `parseAppConfigVars` does. */
+export function parseAppConfig<Schema extends z.ZodTypeAny>(
+  raw: unknown,
+  schema: Schema,
+  { prefix }: ConfigPrefix,
+): z.output<Schema> {
+  try {
+    warnUnknownKeys(raw, schema, [], prefix);
+    return schema.parse(raw);
+  } catch (error) {
+    if (error instanceof z.ZodError) {
+      const issue = error.issues[0]!;
+      throw new Error(`${fieldNameOf(issue.path, { prefix })}: ${issue.message}`);
+    }
+    throw error;
+  }
+}
+
+/** Where a field came from, for a message: its path in the object and its var spelling —
+ *  `ITERATE urls.os (ITERATE__URLS__OS)`. */
+export function fieldNameOf(path: readonly PropertyKey[], { prefix }: ConfigPrefix): string {
+  return `${prefix} ${path.map(String).join(".")} (${configVarNameOf(path, { prefix })})`;
+}
+
+/** An HTTP(S) origin with no path or query — `new URL(v).origin === v`. */
+export const httpOrigin = z
+  .string()
+  .trim()
+  .refine((value) => {
+    if (!URL.canParse(value)) return false;
+    const url = new URL(value);
+    return url.origin === value && (url.protocol === "https:" || url.protocol === "http:");
+  }, "expected an HTTP(S) origin without a path");
+
+/** An origin a deployment may leave out (blank ⇒ the field's documented default). */
+export const optionalOrigin = z.union([z.literal(""), httpOrigin]).default("");
+
+/** A DNS name: lowercase labels, no scheme, no trailing dot, no wildcard — the wildcard is implied. */
+export const dnsName = z
+  .string()
+  .trim()
+  .toLowerCase()
+  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)*$/, "expected a DNS name");
+
+/** The override var a schema path answers to — `["urls", "os"]` → `ITERATE__URLS__OS` — the inverse
+ *  of `overridesOf`, so a message names both spellings a human might have used. */
+export function configVarNameOf(path: readonly PropertyKey[], { prefix }: ConfigPrefix): string {
+  return [
+    prefix,
+    ...path.map((segment) =>
+      String(segment)
+        .replace(/([A-Z])/g, "_$1")
+        .toUpperCase(),
+    ),
+  ].join("__");
+}
+
+/** Warn, loudly, once per key, about a key the schema does not name — in the object or a
+ *  `<prefix>__*` override, checked once on the merged config; the schema's parse then drops it. */
+function warnUnknownKeys(raw: unknown, schema: z.ZodTypeAny, path: string[], prefix: string): void {
+  for (const unknownPath of unknownKeysOf(raw, schema, path))
+    console.warn(
+      `${fieldNameOf(unknownPath, { prefix })}: not in the schema, ignored — remove it, or add it to the schema`,
+    );
+}
+
+/** The paths in `raw` that `schema` does not name: what a parse drops. Walks the plain objects and
+ *  each element of an array; a record accepts any key. */
+export function unknownKeysOf(raw: unknown, schema: z.ZodTypeAny, path: string[] = []): string[][] {
+  // unwrap() and shape hand back loosely typed schemas; the walk checks each with instanceof
+  let current = schema;
+  while (
+    current instanceof z.ZodDefault ||
+    current instanceof z.ZodPrefault ||
+    current instanceof z.ZodOptional
+  )
+    current = current.unwrap() as z.ZodTypeAny;
+  if (current instanceof z.ZodArray && Array.isArray(raw)) {
+    const element = current.element as z.ZodTypeAny;
+    return raw.flatMap((item, index) => unknownKeysOf(item, element, [...path, String(index)]));
+  }
+  const object = z.record(z.string(), z.unknown()).safeParse(raw);
+  if (!object.success || !(current instanceof z.ZodObject)) return [];
+  const shape = current.shape;
+  return Object.entries(object.data).flatMap(([key, value]) => {
+    const child = shape[key] as z.ZodTypeAny | undefined;
+    return child ? unknownKeysOf(value, child, [...path, key]) : [[...path, key]];
+  });
+}
+
+type PlainObject = Record<string, unknown>;
+
+function isPlainObject(value: unknown): value is PlainObject {
+  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+/** The object itself (`<prefix>`); blank ⇒ `{}`. */
+function objectOf(value: string | undefined, prefix: string): PlainObject {
+  if (!value?.trim()) return {};
+  let parsed: unknown;
+  try {
+    parsed = JSON.parse(value);
+  } catch (error) {
+    throw new Error(`${prefix} must be valid JSON`, { cause: error });
+  }
+  if (!isPlainObject(parsed)) throw new Error(`${prefix} must be a JSON object`);
+  return parsed;
+}
+
+/** The `<prefix>__*` overrides as one nested object: `__` separates path segments and each
+ *  segment's SNAKE_CASE becomes camelCase (`ITERATE__LOGIN__METHODS__EMAIL_CODE__FROM` → `login.methods.emailCode.from`).
+ *  A value that reads as JSON (`true`, `false`, `null`, an object, an array, a quoted string) is
+ *  parsed; anything else is the string itself. The shallower path goes first, so a field
+ *  (`ITERATE__CUSTOM_HOSTNAMES__CLOUDFLARE_API_TOKEN`) lands on the object its parent sets
+ *  (`ITERATE__CUSTOM_HOSTNAMES`) whatever order the environment lists them in. */
+function overridesOf(configEnv: Record<string, string>, prefix: string): PlainObject {
+  const overrides: PlainObject = {};
+  const depth = (key: string) => key.split("__").length;
+  const entries = Object.entries(configEnv).sort(([a], [b]) => depth(a) - depth(b));
+  for (const [key, value] of entries) {
+    if (!key.startsWith(`${prefix}__`)) continue;
+    const path = key
+      .slice(`${prefix}__`.length)
+      .split("__")
+      .map((segment) =>
+        segment
+          .toLowerCase()
+          .split("_")
+          .filter(Boolean)
+          .map((word, index) => (index === 0 ? word : word[0]!.toUpperCase() + word.slice(1)))
+          .join(""),
+      )
+      .filter(Boolean);
+    const last = path.pop();
+    if (!last) continue;
+    let target = overrides;
+    for (const segment of path) {
+      const existing = target[segment];
+      const next: PlainObject = isPlainObject(existing) ? existing : {};
+      target[segment] = next;
+      target = next;
+    }
+    target[last] = overrideValueOf(value);
+  }
+  return overrides;
+}
+
+function overrideValueOf(value: string): unknown {
+  const trimmed = value.trim();
+  const looksLikeJson =
+    ["true", "false", "null"].includes(trimmed) ||
+    trimmed.startsWith("{") ||
+    trimmed.startsWith("[") ||
+    (trimmed.startsWith('"') && trimmed.endsWith('"'));
+  if (!looksLikeJson) return value;
+  try {
+    return JSON.parse(trimmed);
+  } catch {
+    return value;
+  }
+}
+
+/** `overrides` over `base`, plain objects merged key by key; anything else replaced whole, and an
+ *  undefined override leaves the base's value (at any depth). */
+export function deepMerge(base: PlainObject, overrides: PlainObject): PlainObject {
+  const merged = { ...base };
+  for (const [key, value] of Object.entries(overrides)) {
+    if (value === undefined) continue;
+    const existing = merged[key];
+    merged[key] = isPlainObject(value)
+      ? deepMerge(isPlainObject(existing) ? existing : {}, value)
+      : value;
+  }
+  return merged;
+}
+
+/** A secret config value: `exposeSecret()` hands it over. Printing, logging or serialising it
+ *  shows only "REDACTED", so a dump of a config never leaks it. */
+export class Redacted<T> {
+  #value: T;
+  constructor(value: T) {
+    this.#value = value;
+  }
+  exposeSecret(): T {
+    return this.#value;
+  }
+  toString(): string {
+    return "REDACTED";
+  }
+  toJSON(): string {
+    return "REDACTED";
+  }
+  [Symbol.for("nodejs.util.inspect.custom")](): string {
+    return "REDACTED";
+  }
+}
+
+/** `schema`'s value as a `Redacted`: how a config's schema marks a secret field. */
+export function redacted<Schema extends z.ZodTypeAny>(schema: Schema) {
+  return schema.transform((value): Redacted<z.output<Schema>> => new Redacted(value));
+}
A core/lib/src/app-description.test.ts
@@ -0,0 +1,88 @@
+import { expect, test } from "vitest";
+import {
+  APP_DESCRIPTION_PATH,
+  type AppDescription,
+  serveAppDescription,
+} from "./app-description.ts";
+import { OwnerEmailPattern } from "./mind-config.ts";
+
+test("the app's own object is answered as JSON at one well-known path, to anyone", async () => {
+  expect(APP_DESCRIPTION_PATH).toBe("/.well-known/iterate-app");
+  const answer = serveAppDescription(ask(APP_DESCRIPTION_PATH), GUESTBOOK);
+  expect(answer).toMatchObject({ status: 200 });
+  expect(answer!.headers.get("content-type")).toContain("application/json");
+  expect(await answer!.json()).toEqual(GUESTBOOK);
+  // an app for members that names no method says only what it wrote: the issuer has the default
+  const dash: AppDescription = { name: "Dash", for: "members" };
+  expect(await serveAppDescription(ask(`${APP_DESCRIPTION_PATH}?x=1`), dash)!.json()).toEqual(dash);
+});
+
+test("any other request is the app's own, and only a read is answered", () => {
+  for (const path of ["/", "/.well-known/iterate", `${APP_DESCRIPTION_PATH}/x`, "/icon.svg"])
+    expect(serveAppDescription(ask(path), GUESTBOOK), path).toBeNull();
+  expect(
+    serveAppDescription(ask(APP_DESCRIPTION_PATH, { method: "HEAD" }), GUESTBOOK),
+  ).toMatchObject({ status: 200 });
+  expect(
+    serveAppDescription(ask(APP_DESCRIPTION_PATH, { method: "POST" }), GUESTBOOK),
+  ).toMatchObject({ status: 405 });
+});
+
+test("a sign-in method that the issuer does not know is refused by the type, and as it is served", () => {
+  // @ts-expect-error -- "google" is no sign-in method
+  const outside: AppDescription = { name: "Guestbook", signIn: ["email", "google"] };
+  expect(() => serveAppDescription(ask(APP_DESCRIPTION_PATH), outside)).toThrow(/signIn/);
+  // @ts-expect-error -- a list names one method at least
+  const none: AppDescription = { name: "Guestbook", signIn: [] };
+  expect(() => serveAppDescription(ask(APP_DESCRIPTION_PATH), none)).toThrow(/signIn/);
+  // @ts-expect-error -- an app is for members, or says nothing of whom it is for
+  const everyone: AppDescription = { name: "Guestbook", for: "everyone" };
+  expect(() => serveAppDescription(ask(APP_DESCRIPTION_PATH), everyone)).toThrow(/for/);
+});
+
+test("the addresses and the patterns of an app's people are served in lowercase, and a pattern that is no owner email pattern is refused as it is served", async () => {
+  const shop: AppDescription = {
+    name: "Shop",
+    allowedEmails: ["eve@elsewhere.test"],
+    allowedEmailPatterns: ["*@example.com", "*@second.example"],
+  };
+  expect(await serveAppDescription(ask(APP_DESCRIPTION_PATH), shop)!.json()).toEqual(shop);
+  expect(
+    await serveAppDescription(ask(APP_DESCRIPTION_PATH), {
+      name: "Shop",
+      allowedEmails: ["Eve@Elsewhere.test"],
+    })!.json(),
+  ).toEqual({ name: "Shop", allowedEmails: ["eve@elsewhere.test"] });
+  // a list of domains is not read, and is not dropped in silence either
+  expect(() =>
+    serveAppDescription(ask(APP_DESCRIPTION_PATH), {
+      name: "Shop",
+      // @ts-expect-error -- no such field
+      emailDomains: ["example.com"],
+    }),
+  ).toThrow(/emailDomains is not read/);
+  // the same patterns as the mind config's, and no other spelling
+  for (const pattern of ["example.com", "@example.com", "*@*.example.com", "*@Example.com", "*"]) {
+    const says = { name: "Shop", allowedEmailPatterns: [pattern] };
+    expect(OwnerEmailPattern.safeParse(pattern), pattern).toMatchObject({ success: false });
+    expect(() => serveAppDescription(ask(APP_DESCRIPTION_PATH), says), pattern).toThrow(
+      /allowedEmailPatterns/,
+    );
+  }
+  for (const says of [
+    { name: "Shop", allowedEmails: ["example.com"] },
+    { name: "Shop", allowedEmails: [] },
+  ])
+    expect(() => serveAppDescription(ask(APP_DESCRIPTION_PATH), says)).toThrow(/allowedEmails/);
+  expect(() =>
+    serveAppDescription(ask(APP_DESCRIPTION_PATH), { name: "Shop", allowedEmailPatterns: [] }),
+  ).toThrow(/allowedEmailPatterns/);
+});
+
+const GUESTBOOK: AppDescription = {
+  name: "Guestbook",
+  icon: "/icon.svg",
+  signIn: ["email", "passkey"],
+};
+const ask = (path: string, init?: RequestInit) =>
+  new Request(`https://guestbook.example.com${path}`, init);
A core/lib/src/app-description.ts
@@ -0,0 +1,77 @@
+// app-description.ts — AN APP SAYS WHAT IT IS (`iterate/app-description`; the type and the helper
+// are in `iterate/sdk` too). An app is one hostname of a mind's zones, served by the mind's own
+// code, and an OAuth client of the mind's issuer. It says its name, its icon, whether it is for
+// members and how its people sign in as a typed object in its own code, and answers that object as
+// JSON at one well-known path of its hostname. The mind's issuer reads it there
+// (core/auth-worker/src/asking-app.ts): its sign-in pages show the name and the icon, the mailed
+// code names the app, and every sign-in for the app's hostname is held to `signIn`.
+//
+// It is no web app manifest: a browser reads none of it. An app that wants to be installable in a
+// browser serves a manifest of its own, which the platform does not read.
+import { z } from "zod";
+import { OwnerEmailPattern } from "./mind-config.ts";
+import { SignInMethod } from "./principal.ts";
+
+/** Where an app answers its `AppDescription`, on its own hostname, for anyone. */
+export const APP_DESCRIPTION_PATH = "/.well-known/iterate-app";
+
+/** WHAT AN APP OF A MIND SAYS OF ITSELF, as an object in the app's own code:
+ *
+ *  ```ts
+ *  const GUESTBOOK: AppDescription = { name: "Guestbook", icon: "/icon.svg", signIn: ["email"] };
+ *  ```
+ */
+export const AppDescription = z.object({
+  /** What the app calls itself. The sign-in pages show sixty characters of it. */
+  name: z.string().min(1),
+  /** The app's icon: a path on the app's own origin, which answers anyone. */
+  icon: z.string().startsWith("/").optional(),
+  /** "members": the app is for the mind's members alone. It changes the sign-in page's words and
+   *  the default of `signIn`. Who may come is still the guard in the app's own code. */
+  for: z.literal("members").optional(),
+  /** HOW THE APP'S PEOPLE SIGN IN, in the app's order: the sign-in page opens on the first and
+   *  offers the others below it, and offers no other. The issuer holds every sign-in for the
+   *  app's hostname to the list, whoever asks for it: the app's own page, or an MCP client. A
+   *  session that a passkey opened counts at every app, whatever the list. With none:
+   *  `["passkey"]` for an app for members, `["email", "passkey"]` for any other. A mailed code
+   *  signs in no member, so an app for members has no reason to name "email". */
+  signIn: z.tuple([SignInMethod], SignInMethod).optional(),
+  /** WHOSE ADDRESS A MAILED CODE SIGNS IN TO THE APP, as a mind's config names its owners
+   *  (iterate/mind-config `ownerEmails`, `ownerEmailPatterns`, and their one matcher
+   *  `isOwnerEmail`): `allowedEmails` names addresses, each whole, and `allowedEmailPatterns`
+   *  names patterns, each `*@<domain>`: every address at exactly that domain, no sub-domain. An
+   *  app that names either takes an address that one of the two names, and no other. The issuer
+   *  then mails no code for the app's hostname to any other address, and gives no code for the
+   *  hostname to a session that a mailed code opened for another address, whoever asks: the
+   *  app's own page, or an MCP client. They bind the method "email" alone: a passkey's session
+   *  still counts, so the guard in the app's own code says which members come. With neither, a
+   *  mailed code signs in any address. */
+  allowedEmails: z.array(z.email().toLowerCase()).min(1).optional(),
+  allowedEmailPatterns: z.array(OwnerEmailPattern).min(1).optional(),
+});
+export type AppDescription = z.infer<typeof AppDescription>;
+
+/** THE ANSWER TO A REQUEST FOR THE APP'S DESCRIPTION, and null for any other request. Call it
+ *  before the app's guard: the issuer asks as nobody, before a person has signed in.
+ *
+ *  ```ts
+ *  const described = serveAppDescription(request, GUESTBOOK);
+ *  if (described) return described;
+ *  ```
+ *
+ *  The object is parsed as it is served: a config repo runs with its types stripped, so code that
+ *  no type checker read fails here, with the field's name, and never names a sign-in method that
+ *  the issuer does not know. */
+export function serveAppDescription(request: Request, app: AppDescription): Response | null {
+  if (new URL(request.url).pathname !== APP_DESCRIPTION_PATH) return null;
+  if (request.method !== "GET" && request.method !== "HEAD")
+    return new Response("Method not allowed\n", { status: 405, headers: { allow: "GET, HEAD" } });
+  // A list of domains (`emailDomains`) is not read: the parse would drop it, and the app would
+  // then be for any address. So it is refused by name, and the issuer keeps what it last read.
+  if ("emailDomains" in app)
+    throw new Error(
+      'emailDomains is not read: name the people in allowedEmailPatterns, as "*@example.com"',
+    );
+  // the issuer keeps what it read for five minutes of its own: nothing between keeps it longer
+  return Response.json(AppDescription.parse(app), { headers: { "cache-control": "no-store" } });
+}
A core/lib/src/app-server.test.ts
@@ -0,0 +1,295 @@
+// The app Worker's gate (app-server.ts) against a mind that is not the app's friend: what the mind
+// answers on `/api` sets nothing in the browser, and a cookie id the app never wrote is not kept.
+import {
+  newWebSocketRpcSession,
+  RpcTarget,
+  upgradeWebSocketResponse,
+  WebSocketPair,
+} from "capnweb";
+import { expect, test, vi } from "vitest";
+import { appAuth, sessionCookieName } from "./app-server.ts";
+import type { BrowserSession } from "./app-session.ts";
+
+test("the mind's answer on /api sets no cookie and clears no site data in the browser", async () => {
+  const { namespace } = sessionsOf({ known: [PLANTED], signedIn: [PLANTED] });
+  const sent: Request[] = [];
+  vi.stubGlobal("fetch", async (request: Request) => {
+    sent.push(request);
+    return new Response('{"ok":true}', {
+      headers: [
+        ["content-type", "application/json"],
+        ["set-cookie", `${cookie("11111111-1111-4111-8111-111111111111")}; Secure; Path=/`],
+        ["set-cookie", "other=1; Path=/"],
+        ["clear-site-data", '"cookies"'],
+        ["x-kept", "yes"],
+      ],
+    });
+  });
+  const response = await appAuth(
+    new Request(`${APP}/api?mind=${MIND}`, {
+      headers: { cookie: cookie(PLANTED), origin: APP, upgrade: "websocket" },
+    }),
+    { sessions: namespace },
+  );
+  expect(response?.status).toBe(200);
+  expect(await response?.text()).toBe('{"ok":true}');
+  expect(response?.headers.getSetCookie()).toEqual([]);
+  expect(response?.headers.get("clear-site-data")).toBeNull();
+  // the rest of the answer is the mind's own
+  expect(response?.headers.get("x-kept")).toBe("yes");
+  expect(response?.headers.get("content-type")).toBe("application/json");
+  // and the mind got the session's bearer, never the browser's cookie or its origin
+  expect(sent[0]?.headers.get("authorization")).toBe("Bearer a-bearer");
+  expect(sent[0]?.headers.get("cookie")).toBeNull();
+  expect(sent[0]?.headers.get("origin")).toBeNull();
+});
+
+test("the page's probe is answered by the gate: a session says 204, none says 401, and the mind gets no request", async () => {
+  const { namespace } = sessionsOf({ known: [PLANTED], signedIn: [PLANTED] });
+  const sent: Request[] = [];
+  vi.stubGlobal("fetch", async (request: Request) => {
+    sent.push(request);
+    return new Response("unexpected");
+  });
+  const probe = (headers: Record<string, string>) =>
+    appAuth(new Request(`${APP}/api?mind=${MIND}`, { method: "POST", headers, body: "" }), {
+      sessions: namespace,
+    });
+  expect((await probe({ cookie: cookie(PLANTED), origin: APP }))?.status).toBe(204);
+  // the cookie's authority is same-origin only
+  expect(
+    (await probe({ cookie: cookie(PLANTED), origin: "https://elsewhere.example" }))?.status,
+  ).toBe(401);
+  expect((await probe({ origin: APP }))?.status).toBe(401);
+  expect(sent).toEqual([]);
+});
+
+test("a mind whose control plane is a zone's apex: the session's bearer goes to that hostname, and to no other", async () => {
+  const { namespace } = sessionsOf({ known: [PLANTED], signedIn: [PLANTED] });
+  const sent: Request[] = [];
+  vi.stubGlobal("fetch", async (request: Request) => {
+    sent.push(request);
+    return new Response("[]");
+  });
+  const response = await appAuth(
+    new Request(`${APP}/api?mind=example.com`, {
+      headers: { cookie: cookie(PLANTED), origin: APP, upgrade: "websocket" },
+    }),
+    { sessions: namespace },
+  );
+  expect(response).toMatchObject({ status: 200 });
+  // a parameter is the address as it is: the shorthand of a typed address is not applied to it
+  expect(sent.map((request) => request.url)).toEqual(["https://example.com/api"]);
+});
+
+test("the connect page is filled in with an apex address in a spelling that its field reads as that address", async () => {
+  const { namespace } = sessionsOf();
+  const response = await appAuth(new Request(`${APP}/.auth/login?mind=example.com&next=/x`), {
+    sessions: namespace,
+  });
+  expect(response?.headers.get("location")).toBe(
+    `/connect?${new URLSearchParams({ mind: "https://example.com", next: "/x" })}`,
+  );
+});
+
+test("a sign-in under a cookie id the app has no record of begins under a new id", async () => {
+  const { namespace, began } = sessionsOf();
+  const response = await connect(namespace, cookie(PLANTED));
+  expect(response?.status).toBe(200);
+  const id = idIn(response);
+  expect(id).toBeTruthy();
+  expect(id).not.toBe(PLANTED);
+  expect(began).toEqual([id]);
+});
+
+test("a sign-in under a cookie id the app knows keeps that id", async () => {
+  const { namespace, began } = sessionsOf({ known: [PLANTED] });
+  const response = await connect(namespace, cookie(PLANTED));
+  expect(response?.status).toBe(200);
+  expect(idIn(response)).toBe(PLANTED);
+  expect(began).toEqual([PLANTED]);
+});
+
+test("a stored bearer that the mind refuses leads to one new sign-in, not to a loop: the gate asks the mind, forgets the session and starts again", async () => {
+  const sessions = sessionsOf({ known: [PLANTED], signedIn: [PLANTED], connected: [MIND] });
+  const mind = mindAnswering({ refuses: ["a-bearer"] });
+  // the page was refused in its session of the mind's API, and left for the gate's sign-in
+  const first = await login(sessions.namespace, cookie(PLANTED));
+  // not back to the page on the stored bearer's word, but on to the mind's issuer
+  expect(first?.headers.get("location")).toBe(`https://${MIND}/oauth2/auth?state=s`);
+  expect(sessions).toMatchObject({ discarded: [PLANTED], began: [PLANTED] });
+  expect(mind).toMatchObject({ asked: ["a-bearer"] });
+
+  // the sign-in that followed stored a bearer that the mind takes: the page gets it, and stays
+  sessions.signIn(PLANTED, "a-new-bearer");
+  const second = await login(sessions.namespace, cookie(PLANTED));
+  expect(second?.headers.get("location")).toBe("/x");
+  expect(sessions).toMatchObject({ discarded: [PLANTED], began: [PLANTED] });
+  expect(mind).toMatchObject({ asked: ["a-bearer", "a-new-bearer"] });
+});
+
+test.for([
+  ["takes the bearer", {}],
+  ["cannot be reached", { unreachable: true }],
+  ["answers no socket", { noSocket: true }],
+  ["fails in another way", { fails: "UNAVAILABLE" }],
+] as const)(
+  "a mind that %s keeps the browser's session: a page of another origin that sends a browser to the sign-in signs nobody out",
+  async ([, answers]) => {
+    const sessions = sessionsOf({ known: [PLANTED], signedIn: [PLANTED], connected: [MIND] });
+    mindAnswering(answers);
+    // a top-level navigation from anywhere: the request says nothing that the gate acts on
+    const response = await login(sessions.namespace, cookie(PLANTED), {
+      referer: "https://elsewhere.example/",
+      "sec-fetch-site": "cross-site",
+    });
+    expect(response?.headers.get("location")).toBe("/x");
+    expect(sessions).toMatchObject({ discarded: [], began: [] });
+  },
+);
+
+// ── the fixture: an app origin, a mind, and the app's sessions as plain objects ─────────────────
+
+const APP = "https://agents.example.org";
+const MIND = "iterate.example.com";
+const PLANTED = "00000000-0000-4000-8000-000000000000";
+
+function cookie(id: string) {
+  return `${sessionCookieName(new URL(APP))}=${id}`;
+}
+
+/** The app's `sessions` namespace, with plain objects for the browser's record and its sessions:
+ *  `known` says which cookie ids have a record, and `began` collects the ids a sign-in began under. */
+function sessionsOf({
+  known = [] as string[],
+  signedIn = [] as string[],
+  /** The minds that the browser's record names. */
+  connected = [] as string[],
+} = {}) {
+  const began: string[] = [];
+  /** The cookie ids whose session the gate forgot. */
+  const discarded: string[] = [];
+  const bearers = new Map(signedIn.map((cookieId) => [cookieId, "a-bearer"]));
+  const namespace = {
+    getByName: (name: string) => {
+      const [, cookieId = "", address] = /^https:\/\/[^:]+:([^:]+)(?::(.+))?$/.exec(name) || [];
+      return {
+        known: async () => known.includes(cookieId),
+        minds: async () => ({
+          minds: connected.map((mind) => ({ address: mind })),
+          lastUsed: null,
+        }),
+        expect: async () => {},
+        touch: async () => {},
+        bearer: async () => (address && bearers.get(cookieId)) || null,
+        discard: async () => {
+          discarded.push(cookieId);
+          bearers.delete(cookieId);
+        },
+        begin: async () => {
+          began.push(cookieId);
+          return { url: `https://${MIND}/oauth2/auth?state=s`, state: "s" };
+        },
+      };
+    },
+  } as unknown as DurableObjectNamespace<BrowserSession>;
+  return {
+    namespace,
+    began,
+    discarded,
+    /** A sign-in completed: the session of `cookieId` holds `bearer`. */
+    signIn: (cookieId: string, bearer: string) => void bearers.set(cookieId, bearer),
+  };
+}
+
+/** `GET /.auth/login` for the mind, back to `/x`: where a page sends the browser to sign in again. */
+function login(
+  sessions: DurableObjectNamespace<BrowserSession>,
+  sentCookie: string,
+  headers: Record<string, string> = {},
+) {
+  return appAuth(
+    new Request(`${APP}/.auth/login?${new URLSearchParams({ mind: MIND, next: "/x" })}`, {
+      headers: { cookie: sentCookie, ...headers },
+    }),
+    { sessions },
+  );
+}
+
+/** THE MIND, AS THE GATE'S `fetch` REACHES IT: its API (a capnweb session over a WebSocket, whose
+ *  `authenticate` refuses the bearers of `refuses`, or fails with the code of `fails`) and its
+ *  discovery documents. `asked`: each bearer that a session authenticated with. */
+function mindAnswering(
+  answers: { refuses?: string[]; unreachable?: true; noSocket?: true; fails?: string } = {},
+) {
+  const asked: unknown[] = [];
+  class Root extends RpcTarget {
+    authenticate(bearer: unknown) {
+      asked.push(bearer);
+      const code = answers.refuses?.includes(String(bearer)) ? "UNAUTHENTICATED" : answers.fails;
+      if (code) throw Object.assign(new Error("refused"), { code });
+      return { mind: null };
+    }
+  }
+  vi.stubGlobal("fetch", async (input: Request | string | URL, init?: RequestInit) => {
+    const url = new URL(input instanceof Request ? input.url : String(input));
+    if (url.pathname === "/api") {
+      if (answers.unreachable) throw new TypeError("fetch failed");
+      if (answers.noSocket) return new Response("no socket here", { status: 426 });
+      expect(new Headers(init?.headers).get("upgrade")).toBe("websocket");
+      const pair = new WebSocketPair();
+      pair[1].accept();
+      // capnweb's own half of its pair, which in workerd is the runtime's `WebSocket`
+      newWebSocketRpcSession(pair[1] as unknown as WebSocket, new Root());
+      return upgradeWebSocketResponse(pair[0]);
+    }
+    if (url.pathname.includes("oauth-protected-resource"))
+      return Response.json({
+        resource: `https://${MIND}/api`,
+        authorization_servers: [`https://${MIND}`],
+      });
+    return Response.json({
+      issuer: `https://${MIND}`,
+      authorization_endpoint: `https://${MIND}/oauth2/auth`,
+      token_endpoint: `https://${MIND}/oauth2/token`,
+      client_id_metadata_document_supported: true,
+      code_challenge_methods_supported: ["S256"],
+    });
+  });
+  return { asked };
+}
+
+/** The connect page's POST for the mind, with the cookie the browser sent. The mind's discovery
+ *  documents are answered here: its API names its issuer, and the issuer its endpoints. */
+function connect(sessions: DurableObjectNamespace<BrowserSession>, sentCookie: string) {
+  vi.stubGlobal("fetch", async (input: Request | string | URL) => {
+    const url = new URL(input instanceof Request ? input.url : String(input));
+    if (url.pathname.includes("oauth-protected-resource"))
+      return Response.json({
+        resource: `https://${MIND}/api`,
+        authorization_servers: [`https://${MIND}`],
+      });
+    return Response.json({
+      issuer: `https://${MIND}`,
+      authorization_endpoint: `https://${MIND}/oauth2/auth`,
+      token_endpoint: `https://${MIND}/oauth2/token`,
+      client_id_metadata_document_supported: true,
+      code_challenge_methods_supported: ["S256"],
+    });
+  });
+  return appAuth(
+    new Request(`${APP}/.auth/connect`, {
+      method: "POST",
+      headers: { origin: APP, "sec-fetch-site": "same-origin", cookie: sentCookie },
+      body: new URLSearchParams({ mind: MIND }),
+    }),
+    { sessions },
+  );
+}
+
+/** The session cookie's id in an answer's `Set-Cookie`. */
+function idIn(response: Response | null) {
+  return new RegExp(`${sessionCookieName(new URL(APP))}=([0-9a-f-]{36})`).exec(
+    response?.headers.get("set-cookie") || "",
+  )?.[1];
+}
A core/lib/src/app-server.ts
@@ -0,0 +1,321 @@
+// app-server.ts — THE BROWSER-AUTH GATE every app Worker runs first: the OAuth client (one CIMD
+// client id per app origin, PKCE, the `__Host-` cookie), the `/api` proxy, and the gate's own JSON.
+// An app is hosted apart from any mind (tasks/mind-stack.md, "Headless Workers"). A person
+// points it at a mind by the mind's address (mind-api.ts), and may be connected to several
+// at once: one cookie per browser, and behind it one `BrowserSession` per mind, each with its own
+// issuer, found by discovery (`discoverMind`), and its own tokens (app-session.ts).
+//
+// Connecting is deliberate: a browser is bound to a mind only by a same-origin POST to
+// `/.auth/connect`, from the app's connect page where the person typed the address — never by a
+// link alone, because a link would be a forced login: it could bind a browser to a mind of the
+// linker's choosing, and the app would then show that mind's world as the person's. A link may
+// only sign the browser in again to a mind it is already connected to (`/.auth/login`).
+import { newWebSocketRpcSession } from "capnweb";
+import type { ControlPlaneApi } from "./api.ts";
+import type { BrowserSession } from "./app-session.ts";
+import { type DiscoveredMind, discoverMind } from "./client/oauth.ts";
+import {
+  cookieValueOf,
+  errorCode,
+  isLocalOrigin,
+  isSameOriginBrowserRequest,
+  sameOriginPath,
+  withTimeout,
+} from "./lib.ts";
+import { mindAddressAsTyped, mindAddressGiven, mindAddressOf, mindApiUrlOf } from "./mind-api.ts";
+
+/** The app's page where a person types a mind's address (packages/ui `ConnectMind`). The
+ *  gate sends a browser there for a mind it is not connected to. */
+export const CONNECT_PAGE_PATH = "/connect";
+
+/** The port separates local apps sharing localhost's cookie jar. */
+export function sessionCookieName(url: URL) {
+  return `__Host-itx-session${url.port ? `-${url.port}` : ""}`;
+}
+
+const COOKIE_ID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
+
+/** The id the browser's cookie carries, or null. */
+function cookieIdOf(request: Request): string | null {
+  const id = cookieValueOf(request.headers.get("cookie"), sessionCookieName(new URL(request.url)));
+  return id && COOKIE_ID.test(id) ? id : null;
+}
+
+/** THE ADDRESS THAT A QUERY PARAMETER NAMES: null when it names none, else the address and
+ *  whether it is spelled exactly so. A parameter is written by a page or a link, never typed
+ *  into the connect page's field, so it is the mind's address as it is (iterate/mind-api
+ *  `mindAddressGiven`): `example.com` names the mind whose control plane is `example.com`, and
+ *  never `iterate.example.com`. */
+function addressParamOf(url: URL, name = "mind"): { address: string; exact: boolean } | null {
+  const value = url.searchParams.get(name);
+  const address = value && mindAddressGiven(value);
+  return address ? { address, exact: address === value } : null;
+}
+
+/** `next` with a `/minds/<segment>` that spells `address` in other letter case spelled as
+ *  `address`, so a mind has one URL in the app. */
+function nextFor(next: string, address: string) {
+  const match = /^\/minds\/([^/?#]+)(.*)$/s.exec(next);
+  if (!match) return next;
+  let segment: string;
+  try {
+    segment = decodeURIComponent(match[1]!);
+  } catch {
+    return next;
+  }
+  return mindAddressGiven(segment) === address ? `/minds/${address}${match[2]}` : next;
+}
+
+/** WHETHER THE MIND AT `address` REFUSES `bearer` NOW: one session of its API (./api.ts
+ *  `ControlPlaneApi`), where the mind checks a credential, opened for the one question and
+ *  closed. True for the mind's own refusal alone, UNAUTHENTICATED. A mind that cannot be reached,
+ *  answers no socket, answers late or fails in another way has refused nothing: an outage never
+ *  signs a browser out. */
+async function mindRefuses(address: string, bearer: string): Promise<boolean> {
+  const answer = await fetch(mindApiUrlOf(address), { headers: { upgrade: "websocket" } }).catch(
+    () => null,
+  );
+  const socket = answer?.webSocket;
+  if (!socket) return false;
+  socket.accept();
+  using api = newWebSocketRpcSession<ControlPlaneApi>(socket);
+  try {
+    using _session = await withTimeout(
+      Promise.resolve(api.authenticate(bearer)),
+      5_000,
+      `Asking ${address} about a session`,
+    );
+    return false;
+  } catch (error) {
+    return errorCode(error) === "UNAUTHENTICATED";
+  } finally {
+    socket.close(1000, "asked");
+  }
+}
+
+const noStore = { "Cache-Control": "no-store" };
+const redirect = (location: string, status = 303, headers: Record<string, string> = {}) =>
+  new Response(null, { status, headers: { Location: location, ...noStore, ...headers } });
+
+type AppAuth = {
+  /** Public app branding; relative logo paths resolve against this app's origin. */
+  client?: { name: string; logoUri: string };
+  sessions: DurableObjectNamespace<BrowserSession>;
+};
+
+/** The OAuth client and `/api` proxy of an app Worker. Null passes the request on to the app. */
+export async function appAuth(request: Request, config: AppAuth): Promise<Response | null> {
+  const url = new URL(request.url);
+  if (!url.pathname.startsWith("/.auth/") && url.pathname !== "/api") return null;
+  const { sessions } = config;
+  const client = config.client && {
+    name: config.client.name,
+    logoUri: new URL(config.client.logoUri, url.origin).href,
+  };
+  const id = cookieIdOf(request);
+  /** The browser's record of its minds. */
+  const record = (cookieId: string) => sessions.getByName(`${url.origin}:${cookieId}`);
+  /** The browser's session for one mind. */
+  const sessionOf = (cookieId: string, address: string) =>
+    sessions.getByName(`${url.origin}:${cookieId}:${address}`);
+
+  /** Start a sign-in to `address`: discovery, then the code flow at the issuer it found. A browser
+   *  already signed in there goes on to `next`. The cookie is written again with each start, so
+   *  its thirty days run from the last sign-in. */
+  const discover = (address: string) => discoverMind(address, { local: isLocalOrigin(url.origin) });
+  const signIn = async (
+    address: string,
+    next: string,
+    discovered?: DiscoveredMind,
+  ): Promise<{ location: string; setCookie: string } | { error: string }> => {
+    // THE COOKIE'S ID IS KEPT ONLY WHEN THIS APP KNOWS IT: an id with no record was not written by
+    // a sign-in here, so somebody planted it, and tokens stored under it would be theirs to use.
+    const cookieId = id && (await record(id).known()) ? id : crypto.randomUUID();
+    const setCookie = `${sessionCookieName(url)}=${cookieId}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=2592000`;
+    // "SIGNED IN ALREADY" IS THE MIND'S TO SAY, NOT THE STORED BEARER'S. A page comes here with a
+    // live session when the mind refused the session's bearer in its API (iterate/app `adopt`):
+    // a grant that ended elsewhere. Sent back on the stored bearer's word, the page would be
+    // refused again and come here again, for as long as the token lives. So the gate asks the
+    // mind, and forgets a session whose bearer the mind itself refuses (`mindRefuses`). Nothing
+    // in the request can make it forget one: a page of another origin that sends a browser here
+    // makes the gate ask, and a session that the mind takes stays.
+    const session = id === cookieId ? sessionOf(id, address) : null;
+    const bearer = session && (await session.bearer());
+    if (session && bearer) {
+      if (!(await mindRefuses(address, bearer))) return { location: next, setCookie };
+      await session.discard();
+    }
+    const mind = discovered || (await discover(address));
+    if ("error" in mind) return mind;
+    const { url: location, state } = await sessionOf(cookieId, address).begin(
+      { origin: url.origin, mind, client },
+      next,
+    );
+    await record(cookieId).expect(state, address);
+    return { location, setCookie };
+  };
+  // the page puts `mind` in its field, where a person's shorthand is read: so it is spelled as
+  // that reading takes it
+  const connectPage = (address: string, next: string) =>
+    `${CONNECT_PAGE_PATH}?${new URLSearchParams({ mind: mindAddressAsTyped(address), next })}`;
+
+  if (url.pathname === "/.auth/client.json")
+    return Response.json(
+      {
+        client_id: `${url.origin}/.auth/client.json`,
+        client_name: client?.name || url.host,
+        client_uri: url.origin,
+        logo_uri: client?.logoUri,
+        redirect_uris: [`${url.origin}/.auth/callback`],
+        token_endpoint_auth_method: "none",
+        grant_types: ["authorization_code", "refresh_token"],
+        response_types: ["code"],
+      },
+      { headers: { "Cache-Control": "public, max-age=300" } },
+    );
+
+  if (url.pathname === "/.auth/minds.json") {
+    // the minds this browser is connected to, by address: for the app's own pages alone
+    if (request.method !== "GET") return new Response("Method not allowed", { status: 405 });
+    const site = request.headers.get("sec-fetch-site");
+    if ((site && site !== "same-origin") || !isSameOriginBrowserRequest(request))
+      return new Response("Cross-site request refused", { status: 403 });
+    const answer = id ? await record(id).minds() : { minds: [], lastUsed: null };
+    return Response.json(answer, { headers: noStore });
+  }
+
+  if (url.pathname === "/.auth/connect") {
+    // The connect page's form, sent by the page's own script: the answer is JSON, the authorization
+    // URL to leave for or a reason the page shows beside the field.
+    if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
+    if (!isSameOriginBrowserRequest(request) || !request.headers.get("origin"))
+      return new Response("Cross-site request refused", { status: 403 });
+    const form = await request.formData();
+    const typed = mindAddressOf(String(form.get("mind") ?? ""));
+    if ("error" in typed) return Response.json(typed, { status: 400, headers: noStore });
+    const mind = await discover(typed.address);
+    if ("error" in mind) return Response.json(mind, { status: 400, headers: noStore });
+    const { address } = mind;
+    const next = nextFor(
+      sameOriginPath(String(form.get("next") || `/minds/${address}`), url.origin),
+      address,
+    );
+    const started = await signIn(address, next, mind);
+    if ("error" in started) return Response.json(started, { status: 400, headers: noStore });
+    return Response.json(
+      { location: started.location },
+      { headers: { ...noStore, "Set-Cookie": started.setCookie } },
+    );
+  }
+
+  if (url.pathname === "/.auth/login") {
+    // Sign in again to a mind this browser is connected to: a link may do that. A mind it is
+    // not connected to goes to the connect page, which asks.
+    if (request.method !== "GET") return new Response("Method not allowed", { status: 405 });
+    const linked = sameOriginPath(url.searchParams.get("next") || "/", url.origin);
+    const typed = addressParamOf(url);
+    if (!typed) return redirect(CONNECT_PAGE_PATH);
+    const { address } = typed;
+    const connected = id ? (await record(id).minds()).minds.map((p) => p.address) : [];
+    if (!connected.includes(address)) return redirect(connectPage(address, linked));
+    const next = nextFor(linked, address);
+    const started = await signIn(address, next);
+    // discovery failed: the connect page posts the same address and shows why
+    if ("error" in started) return redirect(connectPage(address, next));
+    return redirect(started.location, 302, {
+      "Set-Cookie": started.setCookie,
+      "Referrer-Policy": "no-referrer",
+    });
+  }
+
+  if (url.pathname === "/.auth/callback") {
+    if (request.method !== "GET") return new Response("Method not allowed", { status: 405 });
+    const state = url.searchParams.get("state");
+    const address = id && state ? await record(id).addressOf(state) : null;
+    const result = id && address ? await sessionOf(id, address).complete(url.search) : null;
+    if (!id || !address || !result || "error" in result)
+      return new Response(
+        result && "error" in result
+          ? result.error
+          : "This sign-in expired or does not match this browser. Connect the mind again.",
+        { status: 400, headers: { ...noStore, "Referrer-Policy": "no-referrer" } },
+      );
+    await record(id).connected(address);
+    return redirect(result.next, 303, { "Referrer-Policy": "no-referrer" });
+  }
+
+  if (url.pathname === "/.auth/logout") {
+    // Sign out of one mind: its session ends at the issuer when the issuer can revoke, and the
+    // browser is no longer connected to it. Other minds stay signed in.
+    if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
+    if (!isSameOriginBrowserRequest(request))
+      return new Response("Cross-site request refused", { status: 403 });
+    const address = addressParamOf(url)?.address;
+    if (!address) return new Response("Name the mind to sign out of", { status: 400 });
+    if (id) {
+      try {
+        await sessionOf(id, address).end();
+      } catch {
+        console.error("oauth.app_logout_failed", { origin: url.origin, mind: address });
+        return new Response(
+          "Sign-out could not complete. Your session is still present; go back and try again.",
+          { status: 503 },
+        );
+      }
+      await record(id).forget(address);
+    }
+    return redirect(sameOriginPath(url.searchParams.get("next") || "/", url.origin));
+  }
+
+  if (url.pathname === "/api") {
+    // The page's capnweb connection to one mind, a WebSocket, with the bearer of this browser's
+    // session there on its request: the mind's API reads it at the page's `authenticate()`
+    // (iterate/api `ControlPlaneApi`). THE COOKIE'S AUTHORITY IS SAME-ORIGIN ONLY (CSRF): a request
+    // from another origin, or with no Origin at all, gets the 401 a browser with no session gets.
+    const named = addressParamOf(url);
+    if (!named) return new Response("Name the mind: /api?mind=<address>", { status: 400 });
+    const { address } = named;
+    // another spelling gets no session: the page signs in again, and the gate sends it to the
+    // mind's one URL (`nextFor`)
+    const session =
+      named.exact && id && request.headers.get("origin") === url.origin
+        ? sessionOf(id, address)
+        : null;
+    const bearer = session ? await session.bearer() : null;
+    if (!id || !session || !bearer)
+      return new Response(`Sign in to ${address}`, { status: 401, headers: noStore });
+    // THE PAGE'S PROBE (iterate/app `createIterateClient`): any request that is no upgrade. The
+    // gate answers it: this browser has a session for the mind. The mind's API has no other
+    // transport than the socket, and checks the bearer there.
+    if (request.headers.get("upgrade")?.toLowerCase() !== "websocket")
+      return new Response(null, { status: 204, headers: noStore });
+    const headers = new Headers(request.headers);
+    headers.delete("cookie");
+    // The same-origin gate above already ran. Provider CORS reconstruction loses 101.
+    headers.delete("origin");
+    headers.set("authorization", `Bearer ${bearer}`);
+    // where the credential goes is the mind's API, by the address its session is named for
+    const [response] = await Promise.all([
+      fetch(new Request(mindApiUrlOf(address), new Request(request, { headers }))),
+      // the last used mind is where the app's home goes (`/.auth/minds.json`); best effort
+      record(id)
+        .touch(address)
+        .catch(() => {}),
+    ]);
+    // THE MIND'S ANSWER SETS NOTHING IN THIS BROWSER. A mind is not this app: its `Set-Cookie`
+    // would be a cookie of the app's origin, so a hostile mind could plant the session cookie's id
+    // and hold the id under which the person next signs in to a mind of their own. Its
+    // `Clear-Site-Data` would sign the browser out of every mind.
+    const kept = new Headers(response.headers);
+    kept.delete("set-cookie");
+    kept.delete("clear-site-data");
+    return new Response(response.body, {
+      status: response.status,
+      statusText: response.statusText,
+      headers: kept,
+      webSocket: response.webSocket,
+    });
+  }
+
+  return new Response("Not found", { status: 404 });
+}
A core/lib/src/app-session.ts
@@ -0,0 +1,414 @@
+// app-session.ts — WHAT AN APP'S GATE KEEPS for one browser (app-server.ts): one object per browser
+// and mind, `<app origin>:<cookie id>:<address>`, holding that mind's discovered issuer and the
+// browser's tokens there, and one small record per browser, `<app origin>:<cookie id>`, of the
+// minds it is connected to. Both are this one class, because each app's Worker binds one namespace
+// (`BROWSER_SESSION`); an object only ever plays one of the two parts.
+import { DurableObject } from "cloudflare:workers";
+import * as oauth from "oauth4webapi";
+import { z } from "zod";
+import {
+  authorizationCodeRequest,
+  authorizationServerOf,
+  type DiscoveredMind,
+} from "./client/oauth.ts";
+import { isLocalOrigin } from "./lib.ts";
+import { fetchResendingNotRoutedYet } from "./platform-retry.ts";
+
+/** What a sign-in to one mind starts from: the app's origin and branding, and the mind as
+ *  discovery found it. The scope is `iterate`, the one a mind's issuer grants for its API. */
+export type MindSignIn = {
+  origin: string;
+  mind: DiscoveredMind;
+  client?: { name: string; logoUri: string };
+};
+type Base = {
+  origin: string;
+  mind: DiscoveredMind;
+  clientId: string;
+  next: string;
+  until: number;
+};
+type Pending = Base & { phase: "pending"; state: string; verifier: string };
+type Active = Base & {
+  phase: "active";
+  accessToken: string;
+  refreshToken: string;
+  expiresAt: number;
+};
+type StoredSession = Pending | Active;
+
+/** A mind the browser is connected to, as `/.auth/minds.json` answers it. */
+export type ConnectedMind = { address: string; lastUsedAt: number };
+/** The record: the connected minds, and the sign-ins still waiting at an issuer, by `state`. */
+type StoredRecord = {
+  minds: ConnectedMind[];
+  pending: { state: string; address: string; until: number }[];
+  until: number;
+};
+
+const PENDING_MS = 10 * 60_000;
+const SESSION_MS = 30 * 24 * 3600_000;
+
+/** Each app binds this same class. Token exchange, refresh and revocation use the discovered
+ *  issuer's public endpoints, so separately deployed apps need no platform bindings. One queue
+ *  serializes sign-in, refresh, sign-out and expiry across tabs (`#serial`). */
+export class BrowserSession extends DurableObject {
+  /** The operation that runs last, settled either way: the next one starts after it. */
+  #last: Promise<unknown> = Promise.resolve();
+
+  // ── the record: which minds this browser is connected to ──
+
+  /** The connected minds, the last used first. */
+  async minds(): Promise<{ minds: ConnectedMind[]; lastUsed: string | null }> {
+    const minds = [...(await this.#record()).minds].sort((a, b) => b.lastUsedAt - a.lastUsedAt);
+    return { minds, lastUsed: minds[0]?.address ?? null };
+  }
+
+  /** Whether a sign-in began or completed under this record's cookie id: it names a connected
+   *  mind, or a sign-in still waiting at an issuer. */
+  async known(): Promise<boolean> {
+    const record = await this.#record();
+    return record.minds.length > 0 || record.pending.some((flow) => flow.until > Date.now());
+  }
+
+  /** A sign-in to `address` left for its issuer with `state`: the callback finds it by that. */
+  async expect(state: string, address: string) {
+    const record = await this.#record();
+    const now = Date.now();
+    record.pending = [
+      ...record.pending.filter((flow) => flow.until > now),
+      { state, address, until: now + PENDING_MS },
+    ];
+    await this.#saveRecord(record);
+  }
+
+  /** The mind a pending sign-in is for, or null. */
+  async addressOf(state: string): Promise<string | null> {
+    const record = await this.#record();
+    return (
+      record.pending.find((flow) => flow.state === state && flow.until > Date.now())?.address ??
+      null
+    );
+  }
+
+  /** A sign-in to `address` completed: it is connected and the last used, and its pending flows
+   *  are done. */
+  async connected(address: string) {
+    const record = await this.#record();
+    record.pending = record.pending.filter((flow) => flow.address !== address);
+    record.minds = [
+      ...record.minds.filter((mind) => mind.address !== address),
+      { address, lastUsedAt: Date.now() },
+    ];
+    await this.#saveRecord(record);
+  }
+
+  /** `address` was used just now. A write at most once a minute per mind, and none for a mind
+   *  the browser is not connected to. */
+  async touch(address: string) {
+    const record = await this.#record();
+    const mind = record.minds.find((item) => item.address === address);
+    if (!mind || mind.lastUsedAt > Date.now() - 60_000) return;
+    mind.lastUsedAt = Date.now();
+    await this.#saveRecord(record);
+  }
+
+  /** The browser signed out of `address`: it is no longer connected. */
+  async forget(address: string) {
+    const record = await this.#record();
+    record.minds = record.minds.filter((mind) => mind.address !== address);
+    record.pending = record.pending.filter((flow) => flow.address !== address);
+    await this.#saveRecord(record);
+  }
+
+  async #record(): Promise<StoredRecord> {
+    return (
+      (await this.ctx.storage.get<StoredRecord>("record")) || {
+        minds: [],
+        pending: [],
+        until: 0,
+      }
+    );
+  }
+
+  /** The record lives as long as a session may: thirty days from its last change. */
+  async #saveRecord(record: StoredRecord) {
+    record.until = Date.now() + SESSION_MS;
+    await this.ctx.storage.put("record", record);
+    await this.ctx.storage.setAlarm(record.until);
+  }
+
+  // ── a session: one mind's sign-in ──
+
+  /** Start the OAuth code flow with PKCE at the mind's issuer, for the mind's API as the
+   *  resource (RFC 8707). Whatever this object held for the mind before is replaced. Answers the
+   *  authorization URL and the flow's `state`. */
+  begin(signIn: MindSignIn, next: string) {
+    return this.#serial(async () => {
+      const { origin, mind, client } = signIn;
+      const local = isLocalOrigin(origin);
+      if (new URL(origin).protocol !== "https:" && !local)
+        throw new Error("Browser login requires HTTPS");
+      let clientId = `${origin}/.auth/client.json`;
+      // An issuer cannot fetch a local app's client metadata document: the local app registers
+      // (RFC 7591) where the issuer allows it.
+      if (local && mind.endpoints.registration) {
+        const response = await fetch(mind.endpoints.registration, {
+          method: "POST",
+          headers: { "content-type": "application/json" },
+          body: JSON.stringify({
+            client_name: client?.name || new URL(origin).host,
+            client_uri: origin,
+            logo_uri: client?.logoUri,
+            redirect_uris: [`${origin}/.auth/callback`],
+            token_endpoint_auth_method: "none",
+            grant_types: ["authorization_code", "refresh_token"],
+            response_types: ["code"],
+          }),
+          signal: AbortSignal.timeout(10_000),
+        });
+        if (!response.ok) throw new Error(`Local client registration failed (${response.status})`);
+        clientId = z
+          .object({ client_id: z.string().min(1) })
+          .parse(await response.json()).client_id;
+      }
+      const { url, state, verifier } = await authorizationCodeRequest({
+        issuer: mind.issuer,
+        authorizationEndpoint: mind.endpoints.authorization,
+        clientId,
+        redirectUri: `${origin}/.auth/callback`,
+        resources: [mind.resource],
+      });
+      const data: Pending = {
+        origin,
+        mind,
+        next,
+        clientId,
+        phase: "pending",
+        state,
+        verifier,
+        until: Date.now() + PENDING_MS,
+      };
+      await this.ctx.storage.deleteAll();
+      await this.ctx.storage.put("session", data);
+      await this.ctx.storage.setAlarm(data.until);
+      return { url: url.href, state };
+    });
+  }
+
+  /** The issuer's redirect back to `/.auth/callback`, its query string. oauth4webapi validates it
+   *  (the state matches this browser's pending flow, the `iss` matches the issuer, no `error`), then
+   *  exchanges the code for tokens. */
+  complete(callbackQuery: string) {
+    return this.#serial(async (): Promise<{ next: string } | { error: string }> => {
+      const data = await this.ctx.storage.get<StoredSession>("session");
+      if (!data || data.phase !== "pending" || data.until <= Date.now())
+        return {
+          error: "This sign-in expired or does not match this browser. Connect the mind again.",
+        };
+      const as = authorizationServerOf(data.mind);
+      const client: oauth.Client = { client_id: data.clientId };
+      let callback: URLSearchParams;
+      try {
+        callback = oauth.validateAuthResponse(
+          as,
+          client,
+          new URLSearchParams(callbackQuery),
+          data.state,
+        );
+      } catch (error) {
+        // A provider `error=` (the person declined) ends the flow; a state/iss mismatch leaves the
+        // pending flow to be retried from a genuine browser.
+        if (error instanceof oauth.AuthorizationResponseError) {
+          await this.#clear();
+          return { error: "Authorization was declined." };
+        }
+        return {
+          error: "This sign-in expired or does not match this browser. Connect the mind again.",
+        };
+      }
+      const started = Date.now();
+      let tokens: oauth.TokenEndpointResponse;
+      try {
+        const response = await oauth.authorizationCodeGrantRequest(
+          as,
+          client,
+          oauth.None(),
+          callback,
+          `${data.origin}/.auth/callback`,
+          data.verifier,
+          this.#tokenOptions(data),
+        );
+        tokens = await oauth.processAuthorizationCodeResponse(as, client, response);
+      } catch (error) {
+        await this.#endOnDeadGrant(error);
+        return { error: "Sign-in could not complete. Connect the mind again." };
+      }
+      await this.#activate(data, tokens, started);
+      return { next: data.next };
+    });
+  }
+
+  /** A live access token for the mind's API, refreshed when it is about to expire; null when
+   *  there is no live session. */
+  bearer() {
+    return this.#serial(() => this.#bearer());
+  }
+
+  /** Forget a session whose bearer the mind itself refused (./app-server.ts `mindRefuses`): this
+   *  credential no longer grants access, and a sign-in replaces it. Nothing is revoked at the
+   *  issuer, which ended the grant already. */
+  discard() {
+    return this.#serial(() => this.#clear());
+  }
+
+  /** Sign out: revoke the refresh token at the issuer's revocation endpoint (RFC 7009) when it has
+   *  one, then forget the session. A failure to reach the issuer keeps the session and throws, so
+   *  the person can try again. */
+  end() {
+    return this.#serial(async () => {
+      const data = await this.ctx.storage.get<StoredSession>("session");
+      if (data?.phase === "active" && data.mind.endpoints.revocation) {
+        const as = authorizationServerOf(data.mind);
+        const client: oauth.Client = { client_id: data.clientId };
+        const response = await oauth.revocationRequest(
+          as,
+          client,
+          oauth.None(),
+          data.refreshToken,
+          {
+            additionalParameters: { token_type_hint: "refresh_token" },
+            signal: AbortSignal.timeout(10_000),
+            [oauth.allowInsecureRequests]: isLocalOrigin(data.origin),
+          },
+        );
+        await oauth.processRevocationResponse(response);
+      }
+      await this.#clear();
+    });
+  }
+
+  async alarm() {
+    // A record ends thirty days after its last change. A pending flow expires in ten minutes; an
+    // active grant has an absolute thirty-day lifetime here, whatever the issuer allows. An expiry
+    // that waited in the queue behind a sign-in or a refresh reads the bound that one set: a
+    // session it renewed is kept, and the alarm moves to its new bound.
+    await this.#serial(async () => {
+      const held =
+        (await this.ctx.storage.get<StoredSession>("session")) ||
+        (await this.ctx.storage.get<StoredRecord>("record"));
+      if (held && held.until > Date.now()) await this.ctx.storage.setAlarm(held.until);
+      else await this.#clear();
+    });
+  }
+
+  async #bearer() {
+    const data = await this.ctx.storage.get<StoredSession>("session");
+    if (!data || data.phase !== "active") return null;
+    if (data.until <= Date.now()) {
+      await this.#clear();
+      return null;
+    }
+    if (data.expiresAt > Date.now() + 30_000) return data.accessToken;
+    const as = authorizationServerOf(data.mind);
+    const client: oauth.Client = { client_id: data.clientId };
+    const started = Date.now();
+    let tokens: oauth.TokenEndpointResponse;
+    try {
+      const response = await oauth.refreshTokenGrantRequest(
+        as,
+        client,
+        oauth.None(),
+        data.refreshToken,
+        this.#tokenOptions(data),
+      );
+      tokens = await oauth.processRefreshTokenResponse(as, client, response);
+    } catch (error) {
+      await this.#endOnDeadGrant(error);
+      return null;
+    }
+    return (await this.#activate(data, tokens, started)).accessToken;
+  }
+
+  /** The token request's shared options: the audience (RFC 8707 resource), a bounded timeout, a
+   *  request Cloudflare answered itself sent again (an issuer's brand-new workers.dev hostname that
+   *  the server reached does not route yet), and — only for a LOCAL APP (`begin` already admits
+   *  http there) — oauth4webapi's opt-out of its HTTPS-only default. Keyed on the app's origin,
+   *  never the issuer's: a mind a person typed can not talk a deployed app into sending its
+   *  codes in the clear. */
+  #tokenOptions(data: StoredSession): oauth.TokenEndpointRequestOptions {
+    const options: oauth.TokenEndpointRequestOptions = {
+      additionalParameters: { resource: data.mind.resource },
+      signal: AbortSignal.timeout(10_000),
+      [oauth.customFetch]: fetchResendingNotRoutedYet({
+        area: "app-session",
+        name: "token-request",
+      }),
+    };
+    if (isLocalOrigin(data.origin)) options[oauth.allowInsecureRequests] = true;
+    return options;
+  }
+
+  /** Write the active session from a token response. A refresh reuses the prior refresh token when
+   *  the issuer does not rotate it. */
+  async #activate(
+    data: StoredSession,
+    tokens: oauth.TokenEndpointResponse,
+    started: number,
+  ): Promise<Active> {
+    const refreshToken =
+      tokens.refresh_token || (data.phase === "active" ? data.refreshToken : undefined);
+    if (!refreshToken) throw new Error("The sign-in provider returned no refresh token.");
+    const { origin, mind, clientId, next } = data;
+    const stored: Active = {
+      origin,
+      mind,
+      clientId,
+      next,
+      phase: "active",
+      accessToken: tokens.access_token,
+      refreshToken,
+      expiresAt: started + (tokens.expires_in ?? 0) * 1000,
+      until: data.phase === "pending" ? started + SESSION_MS : data.until,
+    };
+    await this.ctx.storage.put("session", stored);
+    await this.ctx.storage.setAlarm(stored.until);
+    return stored;
+  }
+
+  /** A dead code or refresh token (`invalid_grant`) ends the session; other failures are transient.
+   *  A token endpoint that answered anything but its token — an OAuth error body, or a response
+   *  oauth4webapi could not read as one (an uncaught 500) — throws one message naming its status,
+   *  which reads the same on the far side of the Durable Object's RPC. */
+  async #endOnDeadGrant(error: unknown): Promise<void> {
+    if (error instanceof oauth.ResponseBodyError && error.error === "invalid_grant") {
+      await this.#clear();
+      return;
+    }
+    const status =
+      error instanceof oauth.ResponseBodyError
+        ? error.status
+        : error instanceof oauth.OperationProcessingError && error.cause instanceof Response
+          ? error.cause.status
+          : null;
+    throw status === null ? error : new Error(`Token exchange failed (${status}). Try again.`);
+  }
+
+  /** `work`, once every operation before it settled, so two tabs never spend one refresh token.
+   *  Its failure is its caller's alone. A queue in memory, because the object is one instance and a
+   *  reset ends the queue with it. Not `blockConcurrencyWhile`, so the object serves other requests
+   *  while a refresh waits on the network. */
+  #serial<T>(work: () => Promise<T>): Promise<T> {
+    const result = this.#last.then(work);
+    this.#last = result.then(
+      () => {},
+      () => {},
+    );
+    return result;
+  }
+
+  async #clear() {
+    await this.ctx.storage.deleteAll();
+    await this.ctx.storage.deleteAlarm();
+  }
+}
A core/lib/src/app.test.ts
@@ -0,0 +1,102 @@
+// The browser client (./app.ts) against a real mind API on this machine: an HTTP server with a
+// `ws` socket server, each speaking capnweb. Node's own `fetch` and `WebSocket` are the
+// browser's; `window` and `document` are the few members that the client reads.
+import { createServer } from "node:http";
+import { newWebSocketRpcSession, RpcTarget } from "capnweb";
+import { expect, onTestFinished, test, vi } from "vitest";
+import { WebSocketServer } from "ws";
+import { createIterateClient } from "./app.ts";
+
+test("disposing of the page's itx ends its session, and the next read is on a new one", async () => {
+  const mind = await mindOnThisMachine();
+  const { itx, read } = await createIterateClient({ mind: "example.com" }).authenticate();
+  expect(await itx.whoami()).toEqual({ session: 1 });
+
+  itx[Symbol.dispose]();
+  // the session's socket closes, with all that the session held
+  expect(await mind.closed(1)).toBe(true);
+  // a read while no socket is open opens a new session: the API has no other transport
+  expect(await read((over) => over.whoami())).toEqual({ session: 2 });
+  // and a call on the same itx is on that session
+  expect(await itx.whoami()).toEqual({ session: 2 });
+  // the page authenticates with no token: the credential is on the socket's own request
+  expect(mind).toMatchObject({ authenticatedWith: [[undefined], [undefined]] });
+});
+
+test("a bearer that the gate holds and the mind refuses sends the browser to the gate's sign-in, once: a page that is refused again within the minute stays and fails", async () => {
+  const mind = await mindOnThisMachine({ refuses: true });
+  const client = createIterateClient({ mind: "example.com" });
+  const { itx } = await client.authenticate("/here");
+  await expect(Promise.resolve(itx.whoami())).rejects.toMatchObject({ code: "UNAUTHENTICATED" });
+  const signIn = `/.auth/login?${new URLSearchParams({ mind: "example.com", next: mind.href })}`;
+  await vi.waitFor(() => expect(mind).toMatchObject({ left: [signIn] }));
+
+  // the page as it comes back from that sign-in, in the same tab, and is refused again
+  itx[Symbol.dispose]();
+  const back = await createIterateClient({ mind: "example.com" }).authenticate("/here");
+  await expect(Promise.resolve(back.itx.whoami())).rejects.toMatchObject({
+    code: "UNAUTHENTICATED",
+  });
+  await new Promise((resolve) => setTimeout(resolve, 20));
+  expect(mind).toMatchObject({ left: [signIn] });
+});
+
+/** A mind's `/api` on this machine, with the page's `window` and `document` pointed at it. Each
+ *  socket is a session with a number, which its mind answers to `whoami`. The HTTP server is the
+ *  app's gate, which answers the page's probe itself. */
+async function mindOnThisMachine(options: { refuses?: true } = {}) {
+  const authenticatedWith: unknown[][] = [];
+  class Root extends RpcTarget {
+    readonly #session: number;
+    constructor(session: number) {
+      super();
+      this.#session = session;
+    }
+    authenticate(...args: unknown[]) {
+      authenticatedWith.push(args);
+      if (options.refuses)
+        throw Object.assign(new Error("sign in again"), { code: "UNAUTHENTICATED" });
+      const session = this.#session;
+      class Mind extends RpcTarget {
+        whoami() {
+          return { session };
+        }
+      }
+      class Session extends RpcTarget {
+        get mind() {
+          return new Mind();
+        }
+      }
+      return new Session();
+    }
+  }
+  const http = createServer((_request, response) => void response.writeHead(204).end());
+  const sockets = new WebSocketServer({ server: http });
+  const closed = new Map<number, Promise<boolean>>();
+  sockets.on("connection", (socket) => {
+    const session = closed.size + 1;
+    closed.set(session, new Promise((resolve) => socket.once("close", () => resolve(true))));
+    // ws implements the DOM event/send/close interface that capnweb takes
+    newWebSocketRpcSession(socket as unknown as WebSocket, new Root(session));
+  });
+  await new Promise<void>((resolve) => http.listen(0, "127.0.0.1", resolve));
+  onTestFinished(() => {
+    for (const socket of sockets.clients) socket.terminate();
+    http.close();
+  });
+  const { port } = http.address() as { port: number };
+  const listens = { addEventListener() {}, removeEventListener() {} };
+  const href = `http://127.0.0.1:${port}/`;
+  const left: string[] = [];
+  const stored = new Map<string, string>();
+  vi.stubGlobal("window", {
+    ...listens,
+    location: { href, assign: (to: string) => void left.push(to) },
+    sessionStorage: {
+      getItem: (key: string) => stored.get(key) ?? null,
+      setItem: (key: string, value: string) => void stored.set(key, value),
+    },
+  });
+  vi.stubGlobal("document", { ...listens, visibilityState: "visible" });
+  return { closed: (session: number) => closed.get(session), authenticatedWith, left, href };
+}
A core/lib/src/app.ts
@@ -0,0 +1,195 @@
+import { newWebSocketRpcSession, type RpcStub } from "capnweb";
+import type { ControlPlaneApi, IterateContextApi } from "./api.ts";
+import { connectedMind } from "./client/connected-mind.ts";
+import { errorCode } from "./lib.ts";
+import { startHeartbeat, type Heartbeat } from "./client/heartbeat.ts";
+import { openSocketWithRetry, socketOnceOpen } from "./client/socket.ts";
+
+/** What `authenticate` resolves to: the mind's root context as a capnweb stub (pipelined;
+ *  disposable), and a read of plain data. Declared, so the package's declarations stay
+ *  serializable. */
+export type AuthenticatedApp = {
+  /** The mind's root context, `/`, as the person signed in: `itx.cd(path)` reaches the rest. A
+   *  proxy to the current connection, so a dropped socket costs a reconnect, not the page. It is
+   *  usable at once: a call made before the socket has opened goes with the first frames. */
+  itx: RpcStub<IterateContextApi>;
+  /** Plain data, read over the page's one socket: the mind's API has no other transport. `fn`
+   *  makes its calls at once, pipelined, and returns data. A context it addresses on the way is
+   *  held with `using` (`using agents = itx.cd("/agents")`): a call's result stays held until
+   *  disposed. Anything the page keeps, such as a context to subscribe to, comes from `itx`. */
+  read<T>(fn: (itx: RpcStub<IterateContextApi>) => PromiseLike<T>): Promise<T>;
+};
+export type IterateClient = { authenticate(next?: string): Promise<AuthenticatedApp> };
+
+/** The browser leaves for the gate's sign-in (a document navigation) and this never settles — no
+ *  framework in the loop: a TanStack `beforeLoad` awaiting it ends the way a thrown
+ *  `redirect({ reloadDocument: true })` did, a plain page simply navigates. */
+function leaveForLogin(login: string): Promise<never> {
+  window.location.assign(login);
+  return new Promise<never>(() => {});
+}
+
+/** Where the tab keeps when it last left for a sign-in after a refusal (`adopt`). */
+const LEFT_FOR_SIGN_IN = "iterate:left-for-sign-in";
+
+/** Read, or with `value` write, one entry of the tab's `sessionStorage`. Storage is refused in
+ *  some frames and private windows: a read then answers null, and a write does nothing. */
+function sessionValue(key: string, value?: string): string | null {
+  try {
+    if (value) window.sessionStorage.setItem(key, value);
+    return window.sessionStorage.getItem(key);
+  } catch {
+    return null;
+  }
+}
+
+/** One socket to `/api?mind=<address>`, the bearer attached by the app's gate. The `itx` is the
+ *  `mind` of the session that the root answers to `authenticate()` (iterate/api
+ *  `ControlPlaneApi`), which reads the bearer that the gate put on the socket's request: the
+ *  mind's root context as the person, usable before the socket has even opened, calls queue until it has.
+ *  `dispose` forgets the connection and ends its session. */
+type Connection = { itx: RpcStub<IterateContextApi>; socket: WebSocket; dispose(): void };
+
+/** Create once per mind a page shows — a TanStack route's client-only `beforeLoad`, or a plain
+ *  page's entry. `mind` is the mind's address (iterate/mind-api). Every loader and action
+ *  of the page shares the returned connection.
+ *
+ *  Signing in waits for HTTP only: the probe. The socket's upgrade runs beside it and nothing waits
+ *  for it — the connection is adopted on a socket that becomes the upgraded one
+ *  (client/socket.ts `socketOnceOpen`), and its calls queue until then. The upgrade tries for a
+ *  while (≈16 s of attempts) before its calls fail.
+ *  The `itx` the page holds is a proxy to the CURRENT connection: when the socket closes, the next
+ *  call opens a fresh one and pipelines onto it. A reconnect the mind refuses (the session ended
+ *  elsewhere) rejects that call; the page's retry runs `authenticate` again — a fresh one, the
+ *  socket's close forgot the last — whose probe sends the browser to sign in. A bearer that the
+ *  gate holds and the mind refuses sends the browser there too (`adopt`). */
+export function createIterateClient(options: { mind: string }): IterateClient {
+  const { mind } = options;
+  let live: Connection | null = null;
+  let connecting: Promise<AuthenticatedApp> | undefined;
+  /** Where the browser signs in to this mind again, coming back to the page it is on. */
+  const login = (next: string) => `/.auth/login?${new URLSearchParams({ mind, next })}`;
+  const apiUrl = () => {
+    const url = new URL("/api", window.location.href);
+    url.searchParams.set("mind", mind);
+    return url;
+  };
+  const socketUrl = () => {
+    const url = apiUrl();
+    url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
+    return url;
+  };
+  /** Adopt a connection as the live one until its socket closes or its heartbeat finds it dead
+   *  (client/heartbeat.ts; a browser cannot send a WebSocket ping). Either also forgets the settled
+   *  `authenticate` — the next one probes `/api` again, so a session that ended elsewhere sends the
+   *  browser to sign in instead of a retry that can only fail. A page back in the foreground, or a
+   *  network back, beats at once. */
+  function adopt(socket: WebSocket): Connection {
+    const api = newWebSocketRpcSession<ControlPlaneApi>(socket);
+    const connection: Connection = { itx: connectedMind(api), socket, dispose };
+    live = connection;
+    // THE GATE'S BEARER, REFUSED BY THE MIND (a grant that ended elsewhere): the gate's probe
+    // cannot see it, since the mind checks the bearer inside the session. The session's first
+    // call says so, and the browser leaves for the gate's sign-in, where the gate asks the mind
+    // itself, forgets the session that the mind refuses and starts a new one (app-server.ts
+    // `mindRefuses`). ONCE: a page that comes back from that sign-in and is refused again does
+    // not leave again within the minute. Its calls fail, and the page says so, where a second
+    // leave would be a loop that no person could read.
+    Promise.resolve(connection.itx.whoami()).catch((error: unknown) => {
+      if (errorCode(error) !== "UNAUTHENTICATED" || live !== connection) return;
+      const leftAt = Number(sessionValue(LEFT_FOR_SIGN_IN));
+      if (Date.now() - leftAt < 60_000) return;
+      sessionValue(LEFT_FOR_SIGN_IN, String(Date.now()));
+      void leaveForLogin(login(window.location.href));
+    });
+    let heartbeat: Heartbeat | undefined;
+    const beatNow = () => heartbeat?.beatNow();
+    const onVisible = () => document.visibilityState === "visible" && beatNow();
+    const forget = () => {
+      heartbeat?.stop();
+      window.removeEventListener("pagehide", dispose);
+      window.removeEventListener("online", beatNow);
+      document.removeEventListener("visibilitychange", onVisible);
+      if (live !== connection) return;
+      live = null;
+      connecting = undefined;
+    };
+    // The session's root is disposed of last: that shuts the session down and closes its socket.
+    function dispose() {
+      forget();
+      connection.itx[Symbol.dispose]();
+      api[Symbol.dispose]();
+    }
+    // from the open on: the upgrade's own attempts are client/socket.ts's to bound
+    socket.addEventListener(
+      "open",
+      () => {
+        heartbeat = startHeartbeat({
+          beat: () => connection.itx.whoami(),
+          onDead: (reason) => {
+            console.warn(`The connection to ${mind} is dead (${reason}). Reconnecting.`);
+            dispose();
+          },
+        });
+      },
+      { once: true },
+    );
+    socket.addEventListener("close", forget, { once: true });
+    window.addEventListener("pagehide", dispose, { once: true });
+    window.addEventListener("online", beatNow);
+    document.addEventListener("visibilitychange", onVisible);
+    return connection;
+  }
+  // Every property read goes to the live connection — or to a fresh one when the last socket
+  // closed (a new WebSocket, no wait: capnweb queues the call until it opens). What comes back is
+  // capnweb's own stub for that property — a method stub carries its path, so it is returned as
+  // is, never bound or otherwise touched (a capnweb stub answers `.bind` with another stub).
+  //
+  // Disposing of this `itx` ends the session it is on: the connection is forgotten and its socket
+  // closed, with every capability that the session held. The next read opens a new one.
+  const itx = new Proxy({} as RpcStub<IterateContextApi>, {
+    get(_target, property) {
+      if (property === Symbol.dispose) return () => live?.dispose();
+      const connection = live || adopt(new WebSocket(socketUrl()));
+      return Reflect.get(connection.itx as object, property);
+    },
+  });
+  async function connect(next: string): Promise<AuthenticatedApp> {
+    // Two requests at once: the probe and the socket's upgrade, which nothing here waits for
+    // (client/socket.ts `socketOnceOpen`). A socket the probe does not lead to is closed unused.
+    const opening = live ? undefined : openSocketWithRetry(socketUrl());
+    const discard = () =>
+      void opening?.then(
+        (socket) => socket.close(),
+        () => {},
+      );
+    // HTTP distinguishes 401 from outages; a failed WebSocket is not evidence
+    // that the visitor needs to sign in. Errors reach the route's error boundary. The gate
+    // answers the probe itself (app-server.ts): whether this browser has a session for the mind.
+    const probe = await fetch(apiUrl(), {
+      method: "POST",
+      body: "",
+      signal: AbortSignal.timeout(10_000),
+    }).catch((error: unknown) => {
+      discard();
+      throw error;
+    });
+    await probe.body?.cancel();
+    if (!probe.ok) discard();
+    if (probe.status === 401) return leaveForLogin(login(next));
+    if (!probe.ok) throw new Error(`${mind} is unavailable (${probe.status}). Please retry.`);
+    // another read may have opened the live connection meanwhile (`itx`): then this one goes
+    if (opening && !live) adopt(socketOnceOpen(opening));
+    else discard();
+    return { itx, read: async (fn) => await fn(itx) };
+  }
+  return {
+    authenticate(next = "/") {
+      connecting ||= connect(next).catch((error) => {
+        connecting = undefined;
+        throw error;
+      });
+      return connecting;
+    },
+  };
+}
A core/lib/src/cause.ts
@@ -0,0 +1,107 @@
+// cause.ts — the SDK's half of the loop guard, INTERNAL: no export names it and no signature takes
+// it (core/itx/src/cause.ts explains the guard). A host's `callWithCause` (every loaded entrypoint
+// has one, sdk/loaded-worker.ts), and its `fetch` under a Request's mark, run their code under the
+// cause the platform handed them, and this carries that cause, unread, to every `getItx` scope
+// and, in a loaded isolate, every outbound `fetch`.
+// Any other code runs, in a loaded isolate, under the newest cause its isolate saw, and in the
+// platform's own, shared by every mind, under none. Shared by name
+// (`Symbol.for("iterate.cause")`), so every copy of the SDK in an isolate reaches the same one.
+
+// The SDK is typed against the Cloudflare types, never Node's: workerd hands this module to loaded
+// workers under `nodejs_als` alone (core/mind-worker/src/context/worker-loader.ts), Node to the unit tests.
+// @ts-ignore -- without Node's types the import has none; it is typed right below
+import { AsyncLocalStorage as NodeAsyncLocalStorage } from "node:async_hooks";
+import { ITERATE_CAUSE_HEADER, loopLimitOf } from "./lib.ts";
+
+type Carrier = {
+  run<T>(cause: unknown, code: () => T, newest?: "clear"): T;
+  current(): unknown;
+  carryOnFetch(): void;
+};
+
+const carrier = ((globalThis as Record<symbol, Carrier | undefined>)[
+  Symbol.for("iterate.cause")
+] ??= newCarrier());
+
+function newCarrier(): Carrier {
+  const AsyncLocalStorage = NodeAsyncLocalStorage as new <T>() => {
+    run<R>(store: T, code: () => R): R;
+    getStore(): T | undefined;
+  };
+  const running = new AsyncLocalStorage<{ cause: unknown }>();
+  /** Set in a loaded isolate (`carryOnFetch`): only there is the newest cause kept. */
+  let loaded = false;
+  let newest: unknown;
+  const current = () => {
+    const store = running.getStore();
+    return store ? store.cause : newest;
+  };
+  return {
+    run(cause, code, clear) {
+      // what a call needs only for itself (its hops, the delivery its writes are keyed by) is not
+      // kept; the cause is carried unread (`unknown`), so only the fields kept are named
+      const { chain, depth, at, parent } = (cause ?? {}) as {
+        chain?: unknown;
+        depth?: unknown;
+        at?: unknown;
+        parent?: unknown;
+      };
+      if (loaded) newest = clear || chain === undefined ? undefined : { chain, depth, at, parent };
+      return running.run({ cause }, code);
+    },
+    current,
+    carryOnFetch() {
+      if (loaded) return;
+      loaded = true;
+      const outbound = globalThis.fetch;
+      globalThis.fetch = async (input, init) => {
+        const request = new Request(input, init);
+        const mark = causeMarkOf(current());
+        if (mark) request.headers.set(ITERATE_CAUSE_HEADER, mark);
+        const answer = await outbound(request);
+        // a request refused past the loop limit answers 508, marked: it throws as the refusal it is
+        const refused = await loopLimitOf(answer);
+        if (refused) throw refused;
+        return answer;
+      };
+    },
+  };
+}
+
+/** THE MARK OF `cause` that a Request carries in `ITERATE_CAUSE_HEADER`, or none. The cause is
+ *  carried unread, so its fields are read here alone: the mark, never what only a call needs (the
+ *  delivery its writes are keyed by). A header is bytes, so a parent in other characters than
+ *  printable ASCII stays behind. */
+export function causeMarkOf(cause: unknown): string | undefined {
+  // the cast: a cause is the platform's object, carried unread (`Carrier.current`)
+  const carried = cause as
+    | { chain?: unknown; depth?: unknown; at?: unknown; hops?: unknown; parent?: unknown }
+    | undefined;
+  if (!carried) return undefined;
+  const { chain, depth, at, hops, parent } = carried;
+  const ascii = typeof parent === "string" && /^[\x20-\x7e]*$/.test(parent);
+  return JSON.stringify({ chain, depth, at, hops, ...(ascii && { parent }) });
+}
+
+/** Run `code` under `cause` — the platform's word for why, or none (the platform then begins a
+ *  chain for what it does). `"clear"`: a request's fetch leaves no newest cause behind, so code
+ *  outside any call after it runs under none (a visitor's request and the mind's own alike). */
+export const runCausedBy = <T>(cause: unknown, code: () => T, newest?: "clear"): T =>
+  carrier.run(cause, code, newest);
+
+/** The cause the running code runs under, for the platform. */
+export const currentCause = (): unknown => carrier.current();
+
+/** In a LOADED isolate: every outbound `fetch` carries the cause it runs under (the platform's
+ *  egress turns it into our mark) — installed before any of the loaded code's own module runs
+ *  (sdk/loaded-worker.ts); the platform's isolate never is. */
+export const carryCauseOnFetch = (): void => carrier.carryOnFetch();
+
+/** The cause a Request carries, or none. */
+export function causeOfRequest(request: Request): unknown {
+  try {
+    return JSON.parse(request.headers.get(ITERATE_CAUSE_HEADER) ?? "null") ?? undefined;
+  } catch {
+    return undefined;
+  }
+}
A core/lib/src/cli/README.md
@@ -0,0 +1,754 @@
+# The iterate CLI
+
+The `iterate` command: each call talks to one mind, addressed by its control-plane hostname
+(`iterate/mind-api`; `example.com` is read as `iterate.example.com`),
+and a machine keeps a [profile](#profiles) for each mind it uses.
+Requires Node >=22 (Node 24.7+ for creating or verifying ML-DSA-65 identity keys); no Bun runtime. It is part of the SDK's package, [`iterate`](../../README.md),
+and every connection it makes is the Node client's ([`iterate/node`](../node.ts)).
+
+```sh
+npx iterate                               # offline help
+npx iterate deploy                        # a new mind in your own Cloudflare account
+npx iterate cloudflare sign-in --file f  # a kept sign-in, for deploys with nobody at the page
+npx iterate identity show example.com     # the mind's id, and where its identity key is
+npx iterate login example.com             # sign in, and make it the profile's mind
+npx iterate login example.com --device    # approve from a phone, when the issuer offers it
+npx iterate whoami
+npx iterate repl --context /notes         # local Node REPL
+npx iterate itx run --eval 'return await itx.whoami();'
+npx iterate mcp claude                    # the command that adds the mind's MCP server to Claude Code; also codex, grok, agy
+npx iterate use-my-computer --name myComputer
+npx iterate tunnel 5173 --name blog       # a local port on blog.<address>
+npx iterate provide ./whatsapp.ts         # a local file's functions as itx.whatsapp
+npx iterate chatgpt connect example.com   # a ChatGPT plan pays for the mind's Responses requests
+npx iterate git setup git.example.com     # plain git at the mind's git host, with this computer's sign-in
+npx iterate logout
+npx iterate fs read ./notes.md            # a file's bytes on stdout; also write, stat, lstat, ls, mkdir, mv, rm
+```
+
+`--mind <address>` names another mind for one command. A mind's API is
+`https://<address>/api`, and its issuer is whatever the API's protected-resource metadata
+names (RFC 9728): the CLI finds it, registers itself there (RFC 7591), and signs in with PKCE and a
+loopback callback for the API as the resource (RFC 8707). The sign-in is kept per resource in
+`${XDG_CONFIG_HOME:-~/.config}/iterate/sessions.json`, mode 600, and refreshed before a connection
+when it ends within the minute. `ITERATE_MIND_TOKEN` supplies a token for scripts and replaces
+the sign-in. `ITERATE_SKIP_BROWSER_OPEN=1` prints the sign-in URL without opening a browser.
+`logout` ends the sign-ins at the issuer, when it can revoke, and forgets them.
+
+In a sandbox of a mind the CLI needs no sign-in and no profile. The platform sets `ITERATE_MIND`
+(the mind's address) and `ITERATE_SANDBOX` (the sandbox's context path) for each command. With
+both set, and no `--mind` and no `ITERATE_MIND_TOKEN`, the CLI sends no bearer, and the sandbox's
+egress serves the API as the code of the sandbox's own context. The variables are a hint and no
+credential: on any other computer they give a 401. `provide` there lends on the sandbox's context
+and prints `itx.cd("<sandbox path>").<name>`. A sandbox whose requests the mind filters (a rule for
+`itx.fetch`) gets no such session, and the CLI says so. `tunnel` does not work from that session
+yet: its fetch route rides a member's lend on `/`.
+
+### Login without a browser
+
+`iterate login --device` signs in a computer whose browser nobody sees, such as a remote machine or
+an agent's, when the mind's issuer offers the device flow (RFC 8628,
+`device_authorization_endpoint` in its metadata). The person opens the printed page on any device,
+or scans the QR code, checks the code and approves. It is the default over SSH (`SSH_CONNECTION`),
+on Linux with no display, and under a coding agent; `ITERATE_LOGIN_FLOW=browser` or `=device`
+overrides that. With an issuer that does not offer it, the CLI prints the loopback flow's URL
+instead, which needs this machine's localhost. Every login prints whom it signed in.
+`--expect-user` ends and discards a session for anyone else.
+
+In a terminal with colors, the QR code is drawn as `qrencode -t ANSI` draws it; without colors (a
+pipe, `NO_COLOR`, `TERM=dumb`) as half blocks in the text color. `FORCE_COLOR=1` forces the colors.
+The link under the code works everywhere.
+
+## Git with the mind's sign-in
+
+`iterate git setup git.example.com` lets plain `git clone`, `git pull` and `git push` work at a
+host where a mind serves its repos. It signs this computer in to the mind when it is not signed in
+(the mind is the host without its first label; `--mind` names another), and writes two things
+into git's global config for that one host:
+
+- the credential helper `iterate git-credential`, with the inherited helpers cleared for this
+  host, so no keychain and no password window is asked for it;
+- the request header `X-Iterate-Git: 1`, which is public and proves nothing: it tells the host
+  that this git has the helper, so the host answers 401 and git asks it.
+
+The helper hands git a token for that one hostname, which the mind's issuer exchanges the CLI's
+session for (RFC 8693; `core/auth-worker/src/host-tokens.ts`). It opens nothing else of the mind,
+it ends within the hour, and the issuer asks at every use whether the session is still held and
+its person still a member. It is kept in `sessions.json` beside the session, under the host's
+origin, and git sends it as the password of Basic.
+
+With no sign-in, the helper signs in while git waits when a person is at the terminal. With
+nobody there (no terminal, `GIT_TERMINAL_PROMPT=0`, a coding agent) it prints the setup command
+and git stops without asking for a password. Run under `npx`, the setup names the helper as
+`npx --yes iterate git-credential`; otherwise by the Node and the file that ran it.
+
+In a sandbox of the mind, `iterate git setup <host>` signs nobody in. The helper there reaches
+the mind as the code of the sandbox's own context, mints a write token for the one repo that git
+names (`itx.cfArtifacts`, five minutes, kept nowhere) and hands it to git, and the host passes it
+on. A sandbox whose requests the mind filters has no such session, and so no git.
+
+Not tried on macOS or Windows.
+
+## Deploy a mind
+
+`iterate deploy` puts a mind into your own Cloudflare account, at its own domain. It is one
+program with no model in it: it asks for the account and the domain, writes the one input of the
+stack's script ([core/alchemy](../../../alchemy/README.md)), and runs that script from this
+computer. Its code is [deploy.ts](deploy.ts) and [cloudflare-access.ts](cloudflare-access.ts).
+
+```sh
+npx iterate deploy                                   # a person at a terminal: two questions
+npx iterate deploy --new-account --domain ada-labs.com --buy
+CLOUDFLARE_API_TOKEN=… npx iterate deploy --account <id> --domain example.com --owner you@example.org
+```
+
+What it does, in order:
+
+1. **Cloudflare.** You approve a code on Cloudflare's page (the device flow, with the `cf` CLI's
+   public client: no secret, no server of iterate's). The access lives about an hour and is not
+   renewed. It is kept in the CLI's config folder until a deploy works, then revoked, so a second
+   run asks for no second approval. Pass `--new-sign-in` to drop it and sign in with another
+   Cloudflare login. `CLOUDFLARE_API_TOKEN` replaces the sign-in.
+   - The sign-in asks for what one deploy of the stack needs and for nothing more (never "Account
+     API Token Provisioning"): `STACK_SCOPES` in [cloudflare-access.ts](cloudflare-access.ts) says
+     which resource needs each scope. One scope more is asked for and not needed: AI Gateway's
+     read (`CARD_SCOPE`), which says whether the account has a payment card. A kept sign-in
+     (`iterate cloudflare sign-in`) does not ask for it.
+2. **The account.** One that you selected on Cloudflare's page, or a new one in your name
+   (`--new-account`): one Cloudflare login can own several accounts (up to five extra), giving the
+   mind a clean, separate place. An approval covers only the accounts selected on that page, so for
+   a new account, or one you did not select, Cloudflare asks once more.
+   - **A payment card comes first.** When Cloudflare says that the account has no card on file
+     and Workers Paid is off, the command's first step is the card: it opens the account's
+     billing page and waits until the card is there, before the domain and before Workers Paid.
+     The card is typed on Cloudflare's page. The command takes no card and buys nothing at this
+     step. If it stopped (or nobody is at the terminal), it prints the command that goes on:
+     `npx iterate@latest deploy --account <id>`. An account with a card is asked nothing. When
+     the card cannot be read (a kept sign-in or a token without the scope), the command goes on
+     as before, and the step for Workers Paid says that Cloudflare's page asks for a card.
+3. **The domain.** One unified list puts **Buy a brand new domain** at the top (available names
+   made from your name with their yearly price, plus **Enter a brand new domain name and buy
+   that** to type a domain or keywords) and **Use an existing cloudflare zone** right below it. If
+   a typed domain is taken and not yours at another registrar, the command checks alternatives made
+   from its stem and shows them in the same picker. It
+   asks before it buys, with the price; `--buy` is the yes. Cloudflare charges the account's
+   payment method and registers the domain to the account's contact. Both are set on Cloudflare's
+   own pages: an account that never registered a domain is sent to the page for its contact details
+   first, and a purchase that Cloudflare refuses says why and opens the page where that is set.
+   A domain from another registrar you add on Cloudflare's own page, and the command waits until
+   the account has it; once the zone appears as pending, it prints the nameservers to set and
+   reminds you to turn DNSSEC off at the current registrar first. The mind takes a whole domain that
+   nothing else uses, so it can be the domain's site, mail and apps (a new one is best; a subdomain
+   works when it is a zone of its own). A domain of the account with a route of
+   another Worker, or with an A, AAAA, CNAME or MX record, is in use: the command says what is
+   there and asks before it goes on. With your yes (or `--erase-records`) it erases every DNS
+   record and Workers route of that domain, right before the deploy and after every other check.
+   Every run, a new mind's and a later one's, leaves each domain of the mind with HTTP/3 on and
+   0-RTT Connection Resumption off: it reads both settings and writes one that differs, before
+   the deploy and before it erases anything ([zone-protocols.ts](zone-protocols.ts) says why).
+   The settings are the whole domain's. `--plan` says what a deploy would turn, and writes
+   nothing.
+4. **Telemetry: no token.** The deploy makes no telemetry tables (`events`, `logs`, `spans`), and
+   no bucket or Pipelines stream for them. The mind reads Cloudflare's own datasets and `metrics` through
+   `itx.telemetry.query`, with no token (`onboarding/telemetry.md` of `/repos/onboarding`). A mind
+   whose tables an earlier deploy made with a token keeps that token in the stack's state.
+5. **Workers Paid, R2 and Zero Trust.** It opens the page for each one that is off and waits
+   until it is on. Off means Cloudflare refused the read, and the account's line shows its words.
+   A read that failed is not a fact: a 429 or a 5xx is read again, and after three the command
+   stops with nothing changed and says to run it again.
+   - **The command offers to turn Workers Paid and R2 on itself**, for a person at the terminal
+     who signed in at Cloudflare's page. For each of the two that is off, it reads the rate plan
+     in Cloudflare's public catalog (`GET /billing/rate_plans/workers_paid`, `…/r2_paid`), shows
+     the plan's name and its fixed monthly fee, and asks. The default answer is no. After a yes,
+     Cloudflare asks once more for an approval, of the scope `billing:write` alone
+     (`BILLING_SCOPE`, `briefAccess`): that access is in no file, makes the subscriptions
+     (`POST /accounts/<id>/subscriptions`) and is ended at Cloudflare at once. No sign-in that is
+     kept ever holds that scope.
+   - **What the request is bound to.** Cloudflare's API takes the plan's name and no price, and
+     has no quote to agree to. So right before each request the command reads the product again
+     (one that came on meanwhile is not subscribed to twice) and the plan's terms again: terms
+     that changed after the yes make no subscription. A price in Cloudflare's answer that is not
+     the price agreed to is said, with where to cancel. A price that changes in the moment
+     between that read and the request is not caught.
+   - **An answer that does not arrive** (a 5xx, a dropped connection) may still be a subscription:
+     the command reads the account for up to two minutes, and sends the person to the account's
+     subscriptions before any purchase by hand. A revocation that Cloudflare does not confirm
+     after three tries is said: the access then ends by itself within the hour.
+   - **The way by hand stays.** With a no, with terms that the command could not read for
+     certain, with an API token or a kept sign-in, with nobody at the terminal, or when
+     Cloudflare refuses the approval or the subscription, the command opens the product's page
+     and waits, as before.
+
+   An owner proves their address through Cloudflare Access, which needs the
+   account's Zero Trust organization. When the account has none, the command first sets one up
+   through Cloudflare's API, as the script would, with a team name that Cloudflare picks. When
+   Cloudflare refuses that because Zero Trust was never turned on, it opens the account's Zero
+   Trust page (`https://one.dash.cloudflare.com/<account id>/`): choose a team name and the Free
+   plan there. Cloudflare may ask for a payment method and charges nothing for the Free plan.
+   With nobody at the terminal it stops with that page's address. Whether Cloudflare allows the
+   set-up through the API on an account that never had Zero Trust is not yet seen.
+
+6. **The config**, which is the script's one input, written to
+   `${XDG_CACHE_HOME:-~/.cache}/iterate/deploys/<stage>/config.json` and printed (with any
+   sensitive keys redacted) to stdout after the deploy:
+   - `controlPlaneHostname`: `iterate.<domain>`. `--control-plane-hostname` names another: the
+     domain itself, or one label under it.
+   - `ownerEmails`: the owner, who is the Cloudflare login unless `--owner` names another address.
+     The address must not be at the mind's own domain.
+   - `mcpTarget`: none, unless `--mcp-target mcp` names the method of the config's class that
+     says what the mind's own MCP server offers (the default config's is `mcp`)
+   - `ownerEmailPatterns`: none, unless `--owner-email-patterns '*@company.example'` names some
+     (a comma between two; `none` takes them away). A pattern makes every address at exactly
+     that domain an owner: the person proves the address with Cloudflare Access and adds a
+     passkey. The domain must not be the mind's own.
+   - `alchemy.stageName`, the middle of every resource's name (`iterate-<stage>-auth`): never
+     asked. It is the domain with `-` for each dot, cut to 32 characters, with `z` first when
+     the domain starts with a digit.
+   - `topology: "full-cloudflare"`, and `cloudflare`: the account and the one domain.
+   - `mail`: absent, unless `--mail-forward-to <address>` names where each mail to the mind is
+     forwarded as it arrived ([core/alchemy](../../../alchemy/README.md#the-one-input)). The
+     address must be a verified destination address of the account's Email Routing, which a
+     person adds in the dashboard; while it is not, every mail to the mind fails for its sender.
+     Every mail is on the log before the forward: a refused forward does not cost the mail its
+     place there.
+   - `cloudflare.egressGatewayWorker`: absent, unless `--egress-gateway <Worker name>` names a
+     Worker of the account that carries what a mind's `itx.fetch` sends out of the stack, each
+     request with its secret in ([core/alchemy](../../../alchemy/README.md) says what does not
+     go through it). With none, the stack binds no gateway and Cloudflare's own fetch sends.
+   - `mindId`: for a new mind, the id of the identity that the command makes right before the
+     deploy ([The mind's identity key](#the-minds-identity-key)). A mind that is there already
+     keeps its own.
+7. **The kernel.** Which one a deploy builds:
+   - **A new mind:** the repo that `--kernel-repo <address>` names, at its `main`
+     (`--ref <branch>` takes another branch). With no flag it is iterate's own,
+     `https://git.iterate.com/repos/kernel`. The mind clones the same repo at birth, so its own
+     `/repos/kernel` holds the commit that it runs. The command fetches it into
+     `${XDG_CACHE_HOME:-~/.cache}/iterate/kernel` with git, sending no credential.
+     The mind's `/repos/config` is cloned at birth from `--config-repo <address>`, with no flag
+     from `https://git.iterate.com/repos/config-template`, and each repo that its package.json
+     names (`"@repos/stdlib": "../stdlib"`) from beside that address. The mind clones with no
+     credential. So before anything changes the command asks each of those addresses for its
+     `main` with none, and stops with the ones that did not answer.
+   - **A mind that is there:** its own `/repos/kernel`, read with the Cloudflare access the
+     command holds. Nothing is fetched from outside the mind. So a deploy for another reason
+     builds the same kernel again, and a new kernel arrives by a pull or a merge into that repo
+     first. `--kernel-repo` and `--config-repo` are refused here: they are for a birth.
+   - **`--source <folder>`:** a checkout on this computer, whatever it holds, over any mind. For
+     someone who works on the kernel, and for the mind that hosts the source.
+
+   The folder the command runs in is never the kernel by itself. The kernel is installed with
+   pnpm (using local `pnpm` when its major version matches `packageManager`, otherwise
+   `npx --yes <packageManager>`).
+   A source from before the one Alchemy script is refused, before anything changes.
+   When the source holds `core/repos/onboarding`, the command builds the mind Worker with
+   `ITERATE_SEED_REPOS` naming it, and one line says that a new mind starts with
+   `/repos/onboarding`: the onboarding page, its agent's guides and the cards of the Tasks board.
+   A new mind commits that folder as the repo's first commit at its birth, after its config. A
+   mind that has the repo already keeps it as it is.
+
+8. **The deploy**: `pnpm run deploy --stage <stage> --yes` of core/alchemy. Its output goes to
+   `deploy.log` beside the config. A new state store can refuse the run that made it ("State
+   store request failed"): the command then deploys once more by itself. So it does, a minute
+   later, when Alchemy did not see the event queue's new consumer bound to the boundary Worker
+   (`ConsumerScriptUnbound`): Alchemy reads it back for 60 seconds only, and on a slow Cloudflare
+   API the consumer is there and the next run finds it. While the deploy runs, a line each 30
+   seconds names the resources still being made. Any other failure, or a second one, prints
+   the log's last lines and its path. Run the command again on the same computer: it goes on
+   with that deploy ("A deploy that stopped", below). Then it reads the boundary Worker's
+   settings again, up to five times two seconds apart, and checks that `DEPLOY_CONFIG` is the
+   config it deployed and that `MAIL_FORWARD_TO` is there exactly when the config names
+   `mail.forwardTo`. When all is held, one line says so, with the forward's address. When no read
+   answers, a warning says that the check did not run; the deploy succeeded. A miss is a fault of
+   the release, which a second run does not mend: its error comes at once, the command still does
+   every later step, and then it ends non-zero with the same error, which asks for a report. Then the command waits for
+   the mind's first pages ("No page is opened until it loads", below). On a dev zone the whole
+   command took 2 min 14 s (18 Nov 2026): the deploy 1 min 50 s, the wait 20 s.
+
+**A mind that is there already.** When a route of the domain names a mind's boundary Worker, the
+command reads that mind's own config from Cloudflare (the boundary Worker's variable `ITERATE`),
+shows it, and deploys over it. The deploy starts from the whole config that the mind was deployed
+with, which the stack keeps in the boundary Worker's variable `DEPLOY_CONFIG`, so every field
+stays, the sandboxes' image, the mail forward and the egress gateway among them. `--owner`,
+`--control-plane-hostname`, `--mail-forward-to`, `--egress-gateway` and `--zones` each replace what
+the mind has; `--mail-forward-to none` removes the forward, and `--egress-gateway none` the gateway.
+`--zones a.example,b.example` is the mind's whole list of domains, its first domain first: the
+stack makes a new domain's records, routes and mail (it takes over an Email Sending domain that is
+there), and deletes those of a domain that left the list. It
+asks first; `--yes` is the yes. No file of an earlier deploy is needed. A run over a mind with a
+sandbox image planned no changes and took 29 s (18 Nov 2026).
+
+- A mind deployed before the stack kept `DEPLOY_CONFIG` is refused, with nothing changed: deploy
+  it once with core/alchemy's script and its own config, then the command works over it.
+- A mind of iterate's earlier stack (its boundary Worker has no variable `ITERATE`) is refused
+  too. The command does not move such a mind, and never offers to erase its domain: iterate
+  moves it.
+
+**A deploy that stopped** before its end (a failure, or Ctrl-C) leaves the stack's state store
+(the Worker `iterate-<stage>-state`) and what else it made, the domain's records among them, and
+no mind yet. A destroy leaves the store too ([Erase a mind](#erase-a-mind)). When the account has
+the store and no mind's boundary Worker, the next run decides by what is there:
+
+- **This computer holds the config of that stage, account and domain** (`config.json` above,
+  written by the earlier run): it says "This computer holds the config of an earlier deploy of
+  this mind (…), and the account holds its stack's state store: going on with that config", and
+  deploys with it: the same mind id, owners and hostname, but for what a flag names. It asks
+  nothing about the domain's records and erases none. Its deploy takes over (Alchemy's
+  `--adopt`) what the earlier one made and had not yet recorded in the state, such as a
+  telemetry stream that was under way at the stop.
+- **No such config, and nothing else of the stack**: the domain is not in use (a destroy leaves
+  only a `_dmarc` record, which is no use) and the account holds none of the stack's other
+  Workers. The store is a destroy's leftover: the command deploys a new mind there, with a new
+  identity. This deploy takes over too: a stack that stopped before its first Worker and its
+  first record reads the same from outside, and after a real destroy nothing is there to take
+  over.
+- **No such config, and more of the stack** (the deploy began on another computer, or the cache
+  is gone): the command makes no second identity for the mind. It says what is there and stops,
+  with nothing changed. Run it on the computer that began the deploy, or erase the half-made
+  stack ("Erase a mind", with a config of that stage and account); the command then deploys a
+  new mind there. `--erase-records` erases no record of a half-made stack.
+
+When a deploy stops after the boundary Worker already exists, `${XDG_CACHE_HOME:-~/.cache}/iterate/deploys/<stage>/deploying.json`
+stays on disk until `deployStack` finishes. Rerunning the same command on this computer resumes
+that unfinished deploy without asking for `--yes`, passes `--adopt` to take over any resource
+that was under way at the stop, and reports the mind as deployed (not updated) when finishing a
+first deploy. Running from another computer (without `deploying.json`) treats it as a deploy over
+an existing mind and asks before going on.
+
+**No page is opened until it loads.** A deploy that Cloudflare took is not yet a mind that a
+browser reaches: a new domain's DNS records, its certificate and its routes can come late. So
+after the deploy the command reads, from this computer, over HTTPS and with no redirect followed,
+the pages that a browser asks first, every 3 seconds, until all of them worked five times in a
+row:
+
+- `https://<control plane>/sign-in` answers 200.
+- `https://<zone>/` answers below 400.
+- `https://dash.<zone>/` answers: for a new mind below 400 or the app's own 401 (the command's
+  read is no browser navigation), with the Dash's description at `/.well-known/iterate-app`
+  answering 200; over a mind that was there anything below 500.
+- `https://onboarding.<zone>/` answers anything below 500. A mind's config may have no
+  onboarding app, and its 404 is then the mind's own answer.
+
+Setup goes on in the onboarding app when the mind's config serves one (its
+`/.well-known/iterate-app` answers 200), else in the Dash: where this text says
+`https://onboarding.<zone>/` below, such a mind has `https://dash.<zone>/`.
+
+- For a new mind, `https://<control plane>/sign-in/access` redirects to the account's Cloudflare
+  Access sign-in. It is the first owner's one way in, and until the Access application is live
+  the page there refuses.
+
+Each 30 seconds a line names the page that does not work yet and its answer (`answered 522`,
+`gave no answer (ENOTFOUND)`, a certificate's error). After 10 minutes the command says so and
+asks whether to wait 10 minutes more, as often as you like. With nobody at the terminal, or
+after a no, it still posts the mind's identity and prints the config, then prints setup's
+address, opens nothing and ends non-zero. Run the command again to check again: it deploys over
+the mind. The check is this computer's view: a browser with another resolver can still differ.
+
+After the deploy, once the mind is answering and its identity is posted, **the way to setup also
+signs this computer in to the mind**, so `iterate` commands reach it at once. The command prints a
+short link to this computer's own sign-in listener (`http://localhost:<port>/start`), waits for
+Enter and opens it. On a new mind the browser goes to `https://<control plane>/sign-in/access`:
+Cloudflare Access mails the owner a code, the owner adds their first passkey, and the browser goes
+on to the mind's consent page for the CLI, signed in. After **Allow** the browser comes back to the
+listener, which sends it on to `https://onboarding.<zone>/`. Over SSH or headless Linux, or for a
+coding agent, the device sign-in prints the same way in, ending at the approval page with its code
+filled in. The command waits up to 30 minutes for the browser (the device code lasts 5). A failed
+sign-in does not fail the deploy: the command says to run `iterate login <control plane>`. A
+computer with no mind in any profile takes the new mind as its default profile's.
+
+A redeploy from a computer that has a sign-in to the mind opens `https://onboarding.<zone>/`.
+`--no-sign-in` keeps the old end: setup's page alone. With `--no-setup`, or with nobody at the
+terminal and no coding agent (a CI job), nothing is signed in and the command prints setup's address
+without waiting or opening a browser.
+
+**On a first deploy, the command offers the mind's MCP server to the coding agents on this
+computer**: Claude Code, Codex, Grok and Antigravity, each one whose command (`claude`, `codex`,
+`grok`, `agy`) is on `PATH`, all ticked. Each gets the server for all your folders under the name
+`iterate-<control plane with - for .>` (`iterate mcp <client>` prints the command), and signs in to
+it itself at its first use: one **Allow** in a browser that is signed in to the mind. `--mcp
+claude,codex` (or `all`, or `none`) answers the question, also for a coding agent or a redeploy.
+
+**It handles the expected way alone.** A run that stops says why. Run it again on the same
+computer: each step reads what the account has, and a deploy keeps what it made. A coding agent
+can run and supervise it: with nobody at the terminal each choice comes from its flag
+(`iterate deploy --help`), and a missing one is named.
+
+### Deploy with nobody at Cloudflare's page: a kept sign-in
+
+A CI job, or a script that updates your minds, deploys by the same command and the same sign-in
+as a person. The person signs in once and keeps the sign-in; each deploy then renews it.
+Hand a kept sign-in only to code that no pull request can change: the CLI and the stack from a
+checkout of your own default branch (`node <checkout>/core/lib/bin/iterate.js deploy --source
+<checkout>`), or a CLI release that only your default branch can publish. A CI run of a pull
+request that can publish a package or push a mirror can also put its own code there.
+
+```sh
+npx iterate cloudflare sign-in --file ~/.iterate-cloudflare-sign-in.json      # once, a person
+ITERATE_CLOUDFLARE_SIGN_IN_FILE=~/.iterate-cloudflare-sign-in.json \
+  npx iterate deploy --account <id> --domain example.com --yes --no-setup < /dev/null
+npx iterate cloudflare sign-out --file ~/.iterate-cloudflare-sign-in.json     # the end of it
+```
+
+- **`iterate cloudflare sign-in`** opens the deploy's page with the deploy's scopes and
+  `offline_access`. Select only the mind's account.
+  A grant that lacks a scope, or comes with no refresh token, is revoked and nothing is kept.
+  `--file <path>` keeps it in a new file of mode 600. `--print` prints it as one JSON document
+  on standard output, for a pipe into a secret store (`| doppler secrets set NAME > /dev/null`,
+  `| gh secret set NAME`); it refuses a terminal. The tokens never go through a flag's value,
+  which stays in the shell's history and in the list of processes.
+- **`iterate deploy`** with `ITERATE_CLOUDFLARE_SIGN_IN_FILE=<file>` uses it as a sign-in: the
+  same check of the granted scopes, the same words. It does not revoke it at its end.
+  `CLOUDFLARE_API_TOKEN` set as well is refused. An account that the sign-in does not cover is a
+  stop: nobody is there to approve another.
+- **`iterate cloudflare sign-out`** revokes both tokens at Cloudflare and deletes the file (or
+  reads the JSON on standard input: a secret store's copy is yours to delete). It lists the API
+  tokens that deploys made in the accounts it reached (`iterate-<stage>-telemetry-catalog` and
+  `-analytics`): **a token made through a sign-in outlives the sign-in's revocation** until you
+  delete it. Deleting them turns off the mind's telemetry until its next deploy.
+- **`iterate deploy --plan`** changes nothing: over a mind that is there, with the same sign-in,
+  source and config as a deploy, it writes the stack's plan (one line a resource: `noop`,
+  `update`, `create`, `delete`, …) to `plan.log` beside the deploy's config. A caller with nobody
+  at the terminal reads it before it deploys.
+
+**What a kept sign-in can do: everything that a deploy can, in the accounts you selected.** It
+writes Workers, DNS records and every other resource of the stack, and cannot mint API tokens or
+OAuth clients. Keep it where you keep a production secret: a file of mode 600 on a computer that
+only you use, or a secret store. End it with `iterate cloudflare sign-out` when you no longer need
+it.
+
+**Each renewal replaces the refresh token** (Cloudflare's rotation, measured 18 Nov 2026). So:
+
+- The command renews the access token when it has less than 20 minutes left, and writes the
+  renewed sign-in to the file (a temporary file and a rename) before it uses it. From then on
+  the earlier refresh token is stale: **copy the file back to your secret store after every
+  run**, whatever its exit code.
+- When the file cannot be written, the renewed sign-in goes to the CLI's config folder
+  (`cloudflare-sign-in-renewed-<time>.json`) and the command stops: the words name both files.
+  When that write fails too, the renewed sign-in is revoked and you sign in again.
+- **One command at a time on one sign-in.** The command holds `<file>.lock` while it runs and
+  refuses a second one. The lock sees only this computer: a secret store's caller runs one deploy
+  for a sign-in at a time (GitHub Actions: one `concurrency` group for the jobs that use it).
+- **A sign-in that no longer works** stops the command with exit code 3 and "The kept sign-in
+  at Cloudflare in <file> no longer works (Cloudflare: …)". A person signs in again. An outage
+  at Cloudflare exits 1 and leaves the file as it is.
+- Not known: whether Cloudflare keeps the earlier refresh token alive for a while after a
+  renewal, and how long a refresh token lives unused. Deploy at least once a week, and watch
+  for exit code 3.
+
+## Erase a mind
+
+The CLI has no erase command. The stack's own script erases a mind, from the source that
+`iterate deploy` fetched, with the config that it wrote. It cannot be undone: the mind's contexts,
+files, repos, members and secrets are gone.
+
+```sh
+cd "${XDG_CACHE_HOME:-$HOME/.cache}/iterate/kernel/core/alchemy"
+export ITERATE_MIND_CONFIG="${XDG_CACHE_HOME:-$HOME/.cache}/iterate/deploys/<stage>/config.json"
+export CLOUDFLARE_API_TOKEN=…   # a token of the mind's account, or: pnpm exec alchemy login
+pnpm run destroy --stage <stage> --yes
+```
+
+`<stage>` is the mind's domain with `-` for each dot (`ada-labs-com`): the folder name under
+`deploys/`. `--yes` is for a run with nobody at the terminal. What a destroy leaves (the state
+store, a `_dmarc` record, the account's Zero Trust team, the zones) is in
+[core/alchemy's README](../../../alchemy/README.md#what-a-destroy-leaves).
+
+## Recover an owner
+
+`iterate recover --domain <domain> --owner <email>` is for an owner who has no passkey left. The
+mind itself has no way back for an owner: whoever holds an owner's mailbox must not hold the
+mind. So the proof is the mind's Cloudflare account, as it is for a deploy. Its code is
+[recover.ts](recover.ts).
+
+The command signs in to Cloudflare as `iterate deploy` does, and asks for much less: it reads the
+domain, its routes and the boundary Worker's settings, and it writes to D1. It finds the mind by
+its domain (pass `--account <id>` when the domain is in more than one account), checks that the
+address is one of the mind's owners, asks for a yes (`--yes`), and then runs two statements on the
+auth Worker's database, `iterate-<stage>-auth-db`:
+
+1. It revokes every passkey of that owner. A link opens nothing while one is live.
+2. It adds one sign-in link, of which the database holds only the SHA-256 of its random ticket.
+
+It prints the link, `https://<control plane>/keys/first#<ticket>`. The link works once, within 24
+hours, and whoever opens it adds the owner's new passkey: pass it on as you would a password.
+What the owner was signed in to (apps, terminals) stays signed in, and the owner ends it on the
+mind's page `/sessions`.
+
+## The mind's identity key
+
+A mind's id is the SHA-256 of its first signed identity record, the genesis
+([`iterate/mind-identity`](../mind-identity.ts)). The id stays when the mind's domain, its
+Cloudflare account or its keys change. A root key that signed the genesis proves that the mind is
+yours. Its code is [identity.ts](identity.ts).
+
+`iterate deploy` makes the identity of a new mind with no question, after your last answer and
+before anything is deployed. It needs Node 24.7 or newer for that, and says so at its start. It
+writes two files to `${XDG_CONFIG_HOME:-~/.config}/iterate/identities/`, each mode 600 in a folder
+of mode 700:
+
+- `<mind id>.key.json`: the one root key, an ML-DSA-65 key, as its 32-byte seed. It has no
+  passphrase. **Keep a copy of this file**: whoever has it can change the mind's root keys, and
+  without it nobody can. The command prints its path once, at the end of the first deploy. The
+  key is never printed and never leaves the computer.
+- `<mind id>.json`: the signed records, oldest first. The genesis names that key alone, with
+  threshold 1, and the control plane's hostname. The second lists the stack's working key.
+
+Once the mind answers, the command posts the records that the mind does not publish yet to
+`POST https://<control plane>/.well-known/iterate`. No sign-in is needed: a record proves itself.
+After a 5xx answer or a fault of the network it asks again after 1, 2, 4, 8 and 16 seconds, and
+after nothing else: a 4xx is the mind's last word. A post that fails does not fail the deploy: the
+command says what failed, and `iterate identity post` posts again.
+
+Then the command lists the stack's working key. The stack makes an ML-DSA-65 key in the deploy and
+shows it at `https://<control plane>/keys/stack.json` as a candidate: until a record lists it, the
+mind signs nothing as itself and takes no statement from another mind. When the last record does
+not list that key, the command writes the next record (the last one's content, with that key as
+its working key for statements), signs it with the key file, saves it with the others, and posts
+it. A stack on a new database shows a new key, and the next post lists it in place of the old one.
+The key is read over TLS from the mind's own hostname: whoever answers there gets their key
+listed.
+
+A deploy over a mind that has an id passes the id on, signs nothing and makes no key. From a
+computer that holds the mind's records it posts what is missing, and the last record again even
+when the mind has it: the mind then answers that it knows the record, and that request makes its
+stack deliver the events that it still owes the mind's own log. From any other computer it asks
+nothing and says nothing. `iterate recover` reads the mind's config and deploys nothing, so the id stays.
+
+```sh
+npx iterate identity show example.com   # the id, the last record's hostnames, the records here and published, the key file
+npx iterate identity post example.com   # post the records here that the mind lacks, and the last one again
+```
+
+Both read the id from the log that the mind publishes, so the mind must answer.
+
+## Files of this machine
+
+`iterate fs <op>` is one file operation on the machine it runs on (`read`, `write` from stdin, `stat`,
+`lstat`, `ls`, `mkdir [--recursive]`, `mv`, `rm [--recursive] [--force]`). A failure is one JSON line on
+stderr, `{"code":"ENOENT","message":"…"}`, and exit code 1. It needs no sign-in. A sandbox's `files`
+(`itx.sandboxes.get(path).files`) is this command run inside its container, over `exec`:
+[fs.ts](fs.ts) is standalone (`node fs.ts <op>`), which is how the platform puts it there. The same
+operations, as functions, are `files` of [`use-my-computer`](#use-my-computer): one implementation,
+two entry points, so a file is streamed by one code path.
+
+## Running scripts
+
+`itx run` executes a JavaScript function body in the mind with `itx` in scope. Use `return` for
+the result. The mind records the run and its settlement; the CLI never retries a script. Scripts
+execute in the mind, so local Node APIs and local files are unavailable.
+
+```sh
+iterate itx run --context /notes --eval '
+  await itx.append({ type: "note", payload: { text: "hello" } });
+  return await itx.readEvents(0, 10);
+'
+iterate itx run --file ./script.js
+cat script.js | iterate itx run --file -
+```
+
+Specify exactly one of `--eval` or `--file`. `--context` is a path in the mind (default `/`).
+
+## Use my computer
+
+`use-my-computer` shares this computer as a live capability of the mind until Ctrl-C. It is
+[`provide`](#provide) of `use-my-computer.ts` (`iterate provide use-my-computer.ts --name
+jonasComputer` lends the same object), with a friendly default name:
+
+- `itx.myComputer.exec(argv, { cwd?, env?, stdin?, timeoutMs? })`: run a command; answers
+  `{ exitCode, stdout, stderr }` as bytes.
+- `itx.myComputer.files.read(path)` (a stream), `.write(path, content)`, `.stat`, `.lstat`,
+  `.readDirectory`, `.mkdir`, `.rename`, `.remove`: the same code as `iterate fs`, which a
+  sandbox runs in its container.
+- On a Mac: `itx.myComputer.mac.ask({ question, buttons? })`, `.notify({ message, title? })`
+  and `.runSwift({ code })` (AppleScript and Swift, with the owner's local permissions).
+- `itx.myComputer.__describe()`: usage instructions and method signatures.
+
+Share only with a mind you trust: its callers can run local code, and `files` reaches
+everything you can. The capability belongs to the live connection and is released on exit. A
+disconnect reconnects as `provide` does; when every attempt fails the command ends with an error.
+
+## Tunnel
+
+`tunnel <port>` serves `http://localhost:<port>` on a host of the mind until Ctrl-C, WebSocket
+upgrades included (a Vite dev server's hot module reloading works through it):
+
+```sh
+iterate tunnel 5173 --name blog
+# https://blog.example.com/ → http://localhost:5173 (mind members only). Press Ctrl-C to stop.
+iterate tunnel 3000 --public   # anyone may use it; the name is random
+iterate tunnel 3000 --name hello --hostname hello.tunnels.example.com
+```
+
+The URL alone goes to stdout; everything else goes to stderr. The tunnel lends the local port to
+the mind as `itx.tunnels.<name>` with the fetch route `tunnel-<name>` (`itx.fetchRoutes`) whose
+target is it. The route matches one hostname (`requestMatcher: { url: { hostname } }`):
+`<name>.<the mind's first zone>`, or the one `--hostname` names. By default only signed-in visitors
+get through. The route lives as long as the lend: Ctrl-C deletes it, and a
+tunnel that dies without it leaves the host answering 502 until the mind notices, then the
+route is gone too.
+
+### Without the CLI
+
+A tunnel is one capnweb session: lend the mind a fetch-shaped `RpcTarget` with a fetch route
+to it (`provide`'s `fetchRoute`, which ends with the lend), and delete the route on exit.
+This is the whole thing (`npm install capnweb@npm:@iterate-com/capnweb`):
+
+```js
+class LocalSite extends RpcTarget {
+  async fetch(request) {
+    const url = new URL(request.url);
+    // a WebSocket upgrade: dial ws://localhost:<port>, bridge it through a WebSocketPair and answer
+    // upgradeWebSocketResponse(visitor, { headers: { "Sec-WebSocket-Protocol": local.protocol } })
+    // Node's fetch decodes a compressed body but keeps its content-encoding: ask for none
+    const headers = new Headers(request.headers);
+    headers.set("accept-encoding", "identity");
+    return fetch(`http://localhost:${port}${url.pathname}${url.search}`, {
+      method: request.method,
+      headers,
+      body: request.body,
+      duplex: "half",
+    });
+  }
+}
+// the route rides the lend: set again when the platform re-attaches it, gone when it ends
+// `mind.url()` is the apex of the mind's first zone
+const hostname = `${name}.${new URL(await mind.url()).hostname}`;
+await mind.provide(`itx.tunnels.${name}`, new LocalSite(), {
+  fetchRoute: {
+    fetchRouteName: `tunnel-${name}`,
+    requestMatcher: { url: { hostname } },
+    authRequirement: null,
+  },
+});
+console.log(`https://${hostname}/`);
+```
+
+## Provide
+
+`provide <file>` lends a local file's functions to a mind as `itx.<name>` until Ctrl-C, for
+code that has to run on this computer: a device on its network, a session tied to its IP, local
+state. The file is `.ts`, `.mts`, `.mjs` or `.js` alike, imported by Node itself (which strips a
+TypeScript file's types), and its default export answers the functions:
+
+```ts
+// whatsapp.ts
+import makeWASocket from "baileys"; // from this file's own folder's node_modules
+
+export const description = "My WhatsApp: sendMessage(jid, content) …"; // the line a model reads
+
+let socket; // module scope lives as long as the process, across reconnects
+export default function provide({ itx }) {
+  // called on every connection with that connection's mind
+  socket ??= makeWASocket({/* … */});
+  return {
+    sendMessage: (jid, content) => socket.sendMessage(jid, content),
+    async note(text) {
+      await itx.append({ type: "whatsapp/note-added", payload: { text } });
+    },
+  };
+}
+```
+
+```sh
+iterate provide ./whatsapp.ts                    # itx.whatsapp (the file's name)
+iterate provide ./dummy.ts --name whatsappDummy
+```
+
+`itx.<name>` alone goes to stdout once it is live; everything else goes to stderr. The mind's
+scripts and agents call it like any capability (`await itx.whatsapp.sendMessage(…)`); the file
+reaches the mind through the `itx` it was handed.
+
+- **Dependencies are the file's folder's.** Node resolves the file's bare imports from its own
+  folder's `node_modules`, never the CLI's: install them there first (`npm install`, `pnpm
+install`). A missing one is refused before any sign-in, naming the folder to install in. The CLI
+  installs nothing.
+- **Plain functions, no capnweb.** The CLI wraps the functions in its own `RpcTarget`: capnweb lends
+  only its own copy's, which a file's own `capnweb` install is not. A plain object's own functions
+  are lent, or a class instance's methods (never its fields). Arguments and answers cross as they
+  are, so they must be plain data, bytes or stubs.
+- **Every connection calls it again.** The CLI reconnects when its connection closes or the lend
+  ends under it (for about five minutes, as `tunnel` does), calls the default export with the new
+  connection's mind, and lends the answer at the same name. Keep long-lived state in module
+  scope and reach the mind through the newest `itx`.
+- **Share only with a mind you trust.** Its callers run the file's functions with this
+  computer's authority. A killed or stopped `provide` takes the name with it: the mind's calls
+  answer `NO_ITX_EXPRESSION_MATCH`, as before it was lent.
+
+For a machine that stays up, the stored sign-in refreshes itself, and the issuer keeps the grant
+for as long as it does: a grant ends after 7 days with no refresh, when its person stops being a
+member, or when it is revoked. `ITERATE_MIND_TOKEN` takes a token as it stands.
+
+#### A bridge that is not a person: `--key`
+
+A stored sign-in acts as its person, with everything that person may do. A bridge that should
+lend one capability and nothing else gets a key of its own:
+
+```sh
+iterate provide ./whatsapp.ts --key ~/.iterate/whatsapp.key --mind example.com
+```
+
+- **The first run** makes a P-256 key pair, writes the private half to the file (mode 600) and
+  prints a link to `<mind>/keys/enrol`. A member of the mind opens it, signs in and presses
+  Allow, which asks for their passkey: the passkey signs the key and what it may do. The bridge
+  waits for that, for 15 minutes, and then connects.
+- **Every later run** connects with no person. Each connection asks the mind for a token with a
+  statement the key signs. The token lives one hour and there is no refresh token: when it ends,
+  the connection closes and `provide` connects again with a new one.
+- **The key may do one thing:** lend `itx.<name>`, the name it was allowed for. Its `itx` has
+  `provide` and nothing else, so the file cannot read or write the mind through it. With
+  `--paths /integrations/whatsapp/` the link also asks for those paths, and the file's default
+  export gets `append(path, { type, payload })`: it adds an event there, signed by the key.
+- **The key has no end date.** The member who allowed it sees it on `<mind>/keys`, with
+  what it may do and the day it last asked for a token, and removes it there. After a removal the
+  mind gives it no new token, and its open connection ends when its token does, within the hour.
+- **The file is the bridge.** Whoever can read the key file can lend that name. Keep it on the
+  bridge's machine alone. The private key is read in one function (`signer` in `bridge-key.ts`):
+  a TPM, a Secure Enclave or the OS keychain would go there, so the key never leaves the hardware.
+
+## A ChatGPT plan
+
+`chatgpt connect [address]` lets a person's ChatGPT plan pay for the mind's Responses API
+requests, with OpenAI's
+[Sign in with ChatGPT](https://developers.openai.com/siwc/token-sharing-open-source). It needs a
+personal Plus or Pro account. The sign-in must end at `http://127.0.0.1:1455/auth/callback` on the
+computer the browser runs on, so the CLI listens there, opens OpenAI's consent page, and gives the
+code to the mind. One `itx.run` script in the mind trades the code for tokens and keeps them
+in `/secrets/chatgpt`, pinned to OpenAI's origins, and the secret refreshes itself. The tokens never
+reach this computer. A Codex sign-in uses the same port: close it first. Without a sign-in to the
+mind, the command runs `iterate login` first. Then it sends one test request on the plan, unless
+`--no-test`. A new sign-in replaces the plan that the mind had.
+
+## Profiles
+
+One machine can hold several minds side by side. A profile names one mind. Profiles live in
+`${XDG_CONFIG_HOME:-~/.config}/iterate/minds.json`, and the sign-ins in `sessions.json` beside it,
+one per mind, so a sign-in to one mind never replaces another's. Selection order is `--config`,
+the profile the current folder or a parent of it is mapped to, the default profile, the only
+profile, then `default`. `iterate login <address>` points the selected profile at the mind.
+`--mind <address>` names another mind for one command, with that mind's own sign-in.
+
+```sh
+iterate login example.com                  # the profile `default`
+iterate config set --name lab              # a second profile
+iterate --config lab login example.org     # sign it in; the first sign-in stays
+iterate whoami                             # iterate.example.com
+iterate --config lab whoami                # iterate.example.org
+iterate --config lab provide ./whatsapp.ts # both can run at once, each in its own terminal
+iterate config set --name lab --set-workspace   # in a folder: commands there use `lab`
+iterate config use lab                     # make it the default
+iterate config list
+iterate config get
+```
+
+A command that needs a sign-in starts one when the profile's mind has none, `whoami` included.
+
+## Node REPL
+
+`iterate repl` opens a local Node REPL with the mind's context as `itx` (`--context`, default
+`/`) and the transport's `RpcTarget` constructor. Top-level `await`, Node APIs and `.load` are
+available. The bindings remain available after `.clear`; `.exit` releases the context and the
+connection. A lost connection ends the REPL visibly; it never silently repeats your commands.
+
+## Development
+
+In this repository `pnpm exec iterate` runs the source (`src/cli.ts`); the launcher uses the
+published build when installed through `npx`, or when `ITERATE_FORCE_BUILT_PACKAGE=1`.
A core/lib/src/cli/bridge-key.test.ts
@@ -0,0 +1,209 @@
+import { mkdtempSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, test, vi } from "vitest";
+import {
+  type Envelope,
+  KEY_TOKEN_STATEMENT_TYPE,
+  statementOf,
+  verifySignature,
+} from "../signed.ts";
+import { bridgeAppend, bridgeKeyOf, bridgeToken, enrolUrlOf } from "./bridge-key.ts";
+import { finalStateOf, ProvideRefusal, ProvideState } from "./provide-state.ts";
+
+const MIND = "iterate.example.com";
+const timing = { waitMs: 1_000, askEveryMs: 1 };
+
+test("the first run makes the key in a file only its owner reads, and every later run uses it", async () => {
+  const file = join(mkdtempSync(join(tmpdir(), "bridge-key-")), "keys", "whatsapp.key");
+  const made = await bridgeKeyOf(file);
+  expect(statSync(file).mode & 0o777).toBe(0o600);
+  expect(await bridgeKeyOf(file)).toMatchObject({ key: made.key, publicKey: made.publicKey });
+});
+
+test("the link asks a member to allow the key for one capability, and for paths when given", async () => {
+  const { publicKey } = await key();
+  const link = new URL(enrolUrlOf({ address: MIND, name: "whatsapp.jonas", publicKey }));
+  expect(`${link.origin}${link.pathname}`).toBe("https://iterate.example.com/keys/enrol");
+  expect(Object.fromEntries(link.searchParams)).toEqual({
+    actor: "bridge-whatsapp-jonas",
+    label: expect.stringMatching(/^whatsapp\.jonas on /),
+    publicKey,
+    provide: "whatsapp.jonas",
+  });
+  const withPaths = enrolUrlOf({
+    address: MIND,
+    name: "x",
+    publicKey,
+    paths: ["/integrations/x/"],
+  });
+  expect(new URL(withPaths).searchParams.get("paths")).toBe("/integrations/x/");
+});
+
+test("the first run prints the link once and asks until a member has allowed the key", async () => {
+  const bridge = await key();
+  const sent = answers([refusal("invalid_client"), refusal("invalid_client"), token("whatsapp")]);
+  const printed: string[] = [];
+  const got = await bridgeToken({
+    address: MIND,
+    name: "whatsapp",
+    key: bridge,
+    wait: (line) => printed.push(line),
+    timing,
+  });
+  expect(got).toBe("a-token");
+  expect(printed).toEqual([expect.stringContaining("https://iterate.example.com/keys/enrol?")]);
+  expect(sent.map(({ url }) => url)).toEqual(
+    Array(3).fill("https://iterate.example.com/keys/token"),
+  );
+  // each ask is a new statement of the token type at `/`, for this mind, that ends within minutes
+  const statements = sent.map(({ envelope }) => statementOf(envelope.statement));
+  expect(new Set(sent.map(({ envelope }) => envelope.statement))).toHaveProperty("size", 3);
+  for (const [index, statement] of statements.entries()) {
+    expect(statement).toMatchObject({ mind: MIND, path: "/", type: KEY_TOKEN_STATEMENT_TYPE });
+    if ("refused" in statement) throw new Error(statement.refused);
+    expect(statement.expires - Date.now()).toBeLessThanOrEqual(60_000);
+    expect(
+      await verifySignature(sent[index]!.envelope, bridge.publicKey, { origin: "", rpId: "" }),
+    ).toEqual({});
+  }
+});
+
+test("a later connection does not wait: a key that was removed is refused, with the link", async () => {
+  answers([refusal("invalid_client")]);
+  await expect(bridgeToken({ address: MIND, name: "whatsapp", key: await key() })).rejects.toThrow(
+    /not allowed on iterate.example.com: .*keys\/enrol\?/,
+  );
+});
+
+test("a key allowed for another name says so", async () => {
+  answers([token("herdr")]);
+  await expect(bridgeToken({ address: MIND, name: "whatsapp", key: await key() })).rejects.toThrow(
+    /allowed to lend itx.herdr, not itx.whatsapp/,
+  );
+});
+
+test("a refusal that no consent mends ends the run", async () => {
+  answers([refusal("invalid_grant")]);
+  await expect(
+    bridgeToken({ address: MIND, name: "whatsapp", key: await key(), wait: () => {}, timing }),
+  ).rejects.toThrow(/no token: the reason the mind gave/);
+});
+
+test("--json: each refusal is a state — waiting for a member, removed, not in time, another name, and a CLI the mind does not agree with", async () => {
+  const stateOf = (error: unknown) => ProvideState.parse(finalStateOf(error));
+  const link = expect.stringContaining("https://iterate.example.com/keys/enrol?");
+  const reported: ProvideState[] = [];
+  answers([refusal("invalid_client"), token("whatsapp")]);
+  const bridge = await key();
+  await bridgeToken({
+    address: MIND,
+    name: "whatsapp",
+    key: bridge,
+    wait: () => {},
+    report: (state) => reported.push(ProvideState.parse(state)),
+    timing,
+  });
+  expect(reported).toEqual([
+    { state: "notAllowed", why: "No member has allowed this key yet.", link, waiting: true },
+  ]);
+
+  answers([refusal("invalid_client")]);
+  const removed = await bridgeToken({ address: MIND, name: "whatsapp", key: bridge }).catch(
+    stateOf,
+  );
+  expect(removed).toEqual({
+    state: "notAllowed",
+    why: "the reason the mind gave.",
+    link,
+    waiting: false,
+  });
+
+  answers(Array.from({ length: 5 }, () => refusal("invalid_client")));
+  const late = await bridgeToken({
+    address: MIND,
+    name: "whatsapp",
+    key: bridge,
+    wait: () => {},
+    timing: { waitMs: 3, askEveryMs: 1 },
+  }).catch(stateOf);
+  expect(late).toEqual({
+    state: "notAllowed",
+    why: "Nobody allowed this key in time.",
+    link,
+    waiting: false,
+  });
+
+  answers([token("herdr")]);
+  expect(
+    await bridgeToken({ address: MIND, name: "whatsapp", key: bridge }).catch(stateOf),
+  ).toEqual({
+    state: "notAllowed",
+    why: "This key was allowed to lend itx.herdr, not itx.whatsapp.",
+    waiting: false,
+  });
+
+  for (const why of [
+    "the statement is for another mind",
+    `the statement is not ${KEY_TOKEN_STATEMENT_TYPE} at /`,
+  ]) {
+    answers([Response.json({ error: "invalid_grant", error_description: why }, { status: 400 })]);
+    const refused = await bridgeToken({ address: MIND, name: "whatsapp", key: bridge }).catch(
+      (error: unknown) => error,
+    );
+    expect(refused).toBeInstanceOf(ProvideRefusal);
+    expect((refused as Error).message).toContain("update the CLI");
+    expect(stateOf(refused)).toEqual({
+      state: "incompatible",
+      why: `${why}: this iterate CLI and the mind do not agree on the protocol`,
+    });
+  }
+
+  // a refusal that a later try may mend is no state of its own: it stops the run, or a reconnect
+  // tries again
+  answers([refusal("invalid_grant")]);
+  expect(
+    await bridgeToken({ address: MIND, name: "whatsapp", key: bridge }).catch(stateOf),
+  ).toEqual({
+    state: "stopped",
+    why: "The mind gave this bridge's key no token: the reason the mind gave.",
+  });
+});
+
+test("the file's append posts one event as a statement the key signs, and a refusal throws", async () => {
+  const bridge = await key();
+  const sent = answers([
+    new Response("{}"),
+    Response.json({ refused: "this key adds no events" }, { status: 403 }),
+  ]);
+  const append = bridgeAppend(MIND, bridge);
+  const event = { type: "whatsapp/message-received", payload: { text: "hello" } };
+  await append("/integrations/whatsapp/jonas", event);
+  expect(sent[0]).toMatchObject({ url: "https://iterate.example.com/statements" });
+  expect(statementOf(sent[0]!.envelope.statement)).toMatchObject({
+    mind: MIND,
+    path: "/integrations/whatsapp/jonas",
+    ...event,
+  });
+  await expect(append("/agents/x", event)).rejects.toThrow(/this key adds no events/);
+});
+
+const key = () => bridgeKeyOf(join(mkdtempSync(join(tmpdir(), "bridge-key-")), "bridge.key"));
+
+const token = (provide: string) =>
+  Response.json({ access_token: "a-token", token_type: "Bearer", expires_in: 3600, provide });
+
+const refusal = (error: string) =>
+  Response.json({ error, error_description: "the reason the mind gave" }, { status: 400 });
+
+/** The mind's answers, in order; what the bridge sent is read back from the list it returns. */
+function answers(responses: Response[]) {
+  const sent: { url: string; envelope: Envelope }[] = [];
+  vi.stubGlobal("fetch", async (url: string, init: { body: string }) => {
+    sent.push({ url, envelope: JSON.parse(init.body) as Envelope });
+    const answer = responses.shift();
+    if (!answer) throw new Error("the bridge asked more often than the test answers");
+    return answer;
+  });
+  return sent;
+}
A core/lib/src/cli/bridge-key.ts
@@ -0,0 +1,217 @@
+// bridge-key.ts — `iterate provide <file> --key <key file>`: A BRIDGE WITH A KEY OF ITS OWN. A
+// person's sign-in acts as that person, and a bridge should lend one capability and nothing else.
+// So the bridge makes a P-256 key pair once and keeps the private half in a file. A member of the
+// mind allows the key once, on the mind's own page, for one capability name. From then on the key
+// signs a statement and gets a token for the mind's API that lives an hour
+// (core/auth-worker/src/key-tokens.ts), each time `provide` connects. The key has no end date: a
+// member ends it on `<mind>/keys`.
+//
+// THE PRIVATE KEY IS A FILE (mode 600). Whoever can read the file is the bridge. `signer` below is
+// the one place that touches it: a TPM, a Secure Enclave or the OS keychain would take its place
+// there, with a key that never leaves the hardware, and nothing else here would change.
+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { hostname } from "node:os";
+import { dirname, resolve } from "node:path";
+import {
+  base64url,
+  type Envelope,
+  KEY_TOKEN_PATH,
+  KEY_TOKEN_STATEMENT_TYPE,
+  keyIdOf,
+  signedP256,
+  type Statement,
+  STATEMENTS_PATH,
+  statementText,
+} from "../signed.ts";
+import { ProvideRefusal, type ProvideState } from "./provide-state.ts";
+
+const P256 = { name: "ECDSA", namedCurve: "P-256" } as const;
+/** How long the first run waits for a member to allow the key. */
+const APPROVAL_WAIT_MS = 15 * 60_000;
+
+/** A bridge's key: its id and public half, and `sign`, which makes a statement's envelope. */
+export type BridgeKey = {
+  key: string;
+  publicKey: string;
+  sign(fields: Pick<Statement, "mind" | "path" | "type" | "payload">): Promise<Envelope>;
+};
+
+/** The key in `file`, made on the first run. The file holds the private key as a JWK. */
+export async function bridgeKeyOf(file: string): Promise<BridgeKey> {
+  const path = resolve(file);
+  if (!existsSync(path)) {
+    const pair = await crypto.subtle.generateKey(P256, true, ["sign", "verify"]);
+    mkdirSync(dirname(path), { recursive: true });
+    writeFileSync(path, JSON.stringify(await crypto.subtle.exportKey("jwk", pair.privateKey)), {
+      mode: 0o600,
+    });
+    // `mode` above is cut by the umask on some systems: this is not
+    chmodSync(path, 0o600);
+  }
+  return signer(JSON.parse(readFileSync(path, "utf8")) as JsonWebKey);
+}
+
+async function signer(jwk: JsonWebKey): Promise<BridgeKey> {
+  const privateKey = await crypto.subtle.importKey("jwk", jwk, P256, false, ["sign"]);
+  const { kty, crv, x, y } = jwk;
+  const open = await crypto.subtle.importKey("jwk", { kty, crv, x, y }, P256, true, ["verify"]);
+  const publicKey = base64url(new Uint8Array(await crypto.subtle.exportKey("spki", open)));
+  const key = await keyIdOf(publicKey);
+  return {
+    key,
+    publicKey,
+    sign: (fields) => {
+      const at = Date.now();
+      // a minute: the mind takes a token's statement that ends within five
+      const statement = statementText({ ...fields, at, expires: at + 60_000 });
+      return signedP256(statement, privateKey, key);
+    },
+  };
+}
+
+/** The page where a member allows the key: it may lend `itx.<name>`, and add events under `paths`
+ *  when it names some (under `/integrations/` alone: the mind's rule for a key allowed by a link). */
+export function enrolUrlOf(input: {
+  address: string;
+  name: string;
+  publicKey: string;
+  paths?: string[];
+}): string {
+  const query = new URLSearchParams({
+    // a service's name on the mind: lowercase letters, digits and hyphens
+    actor: `bridge-${input.name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`.slice(0, 63),
+    label: `${input.name} on ${hostname()}`.slice(0, 100),
+    publicKey: input.publicKey,
+    provide: input.name,
+    ...(input.paths?.length && { paths: input.paths.join(",") }),
+  });
+  return `https://${input.address}/keys/enrol?${query}`;
+}
+
+/** One ask for a token. `seconds` asks for less than the hour (a test's). */
+async function askForToken(input: {
+  address: string;
+  key: BridgeKey;
+  seconds?: number;
+}): Promise<{ token: string; provide: string } | { refused: string; why: string }> {
+  const envelope = await input.key.sign({
+    mind: input.address,
+    path: "/",
+    type: KEY_TOKEN_STATEMENT_TYPE,
+    ...(input.seconds && { payload: { seconds: input.seconds } }),
+  });
+  const answer = await fetch(`https://${input.address}${KEY_TOKEN_PATH}`, {
+    method: "POST",
+    headers: { "content-type": "application/json" },
+    body: JSON.stringify(envelope),
+    signal: AbortSignal.timeout(20_000),
+  });
+  const body = (await answer.json().catch(() => ({}))) as {
+    access_token?: string;
+    provide?: string;
+    error?: string;
+    error_description?: string;
+  };
+  if (answer.ok && body.access_token && body.provide)
+    return { token: body.access_token, provide: body.provide };
+  return {
+    refused: body.error || `HTTP ${answer.status}`,
+    why: body.error_description || "the mind gave no reason",
+  };
+}
+
+/** The refusals of /keys/token (core/auth-worker/src/keys.ts, key-tokens.ts) that say the CLI
+ *  signed what this stack does not take: no retry and no member changes them. */
+const protocolRefusals = new Set([
+  "the statement is for another mind",
+  `the statement is not ${KEY_TOKEN_STATEMENT_TYPE} at /`,
+]);
+
+/** A TOKEN FOR THE BRIDGE at `address`, to lend `itx.<name>`. A key the mind does not know yet is
+ *  not an error on the first run (`wait`): the link to allow it is printed once, and this asks
+ *  again until a member has allowed it. Later a refusal is the answer: the key was removed. */
+export async function bridgeToken(input: {
+  address: string;
+  name: string;
+  key: BridgeKey;
+  paths?: string[];
+  seconds?: number;
+  /** wait for a member to allow the key, and print the link with this */
+  wait?: (line: string) => void;
+  /** `--json`: the state while it waits */
+  report?: (state: ProvideState) => void;
+  /** a test's timing */
+  timing?: { waitMs: number; askEveryMs: number };
+}): Promise<string> {
+  const { waitMs, askEveryMs } = input.timing || { waitMs: APPROVAL_WAIT_MS, askEveryMs: 5_000 };
+  const link = enrolUrlOf({ ...input, publicKey: input.key.publicKey });
+  const waitUntil = Date.now() + waitMs;
+  for (let asked = false; ; asked = true) {
+    const answer = await askForToken(input);
+    if ("token" in answer) {
+      if (answer.provide !== input.name)
+        throw new ProvideRefusal(
+          `This key was allowed to lend itx.${answer.provide}, not itx.${input.name}. Use --name ${answer.provide}, or another key file.`,
+          {
+            state: "notAllowed",
+            why: `This key was allowed to lend itx.${answer.provide}, not itx.${input.name}.`,
+            waiting: false,
+          },
+        );
+      return answer.token;
+    }
+    if (protocolRefusals.has(answer.why))
+      // The CLI signed for the hostname it asked, and that hostname's stack answers that the
+      // statement is not for it, or not of a type it takes: the two disagree on the protocol (a
+      // stack names itself by its control-plane hostname). A --mind that names another hostname
+      // of the mind reads the same, so the message names both.
+      throw new ProvideRefusal(
+        `The mind refused this bridge's key: ${answer.why}. This iterate CLI and the mind do not agree: update the CLI, or check that --mind names the mind's control-plane hostname.`,
+        {
+          state: "incompatible",
+          why: `${answer.why}: this iterate CLI and the mind do not agree on the protocol`,
+        },
+      );
+    if (answer.refused !== "invalid_client" && answer.refused !== "invalid_scope")
+      throw new Error(`The mind gave this bridge's key no token: ${answer.why}.`);
+    if (!input.wait)
+      throw new ProvideRefusal(
+        `This bridge's key is not allowed on ${input.address}: ${answer.why}. A member allows it at ${link}`,
+        { state: "notAllowed", why: `${answer.why}.`, link, waiting: false },
+      );
+    if (!asked) {
+      input.wait(
+        `This bridge's key is not allowed on ${input.address} yet. A member of the mind opens this link and signs with a passkey:\n\n  ${link}\n\nWaiting for that...`,
+      );
+      input.report?.({
+        state: "notAllowed",
+        why: "No member has allowed this key yet.",
+        link,
+        waiting: true,
+      });
+    }
+    if (Date.now() + askEveryMs > waitUntil)
+      throw new ProvideRefusal(
+        `Nobody allowed this bridge's key in time. Open ${link} and run this again.`,
+        { state: "notAllowed", why: "Nobody allowed this key in time.", link, waiting: false },
+      );
+    await new Promise((resolved) => setTimeout(resolved, askEveryMs));
+  }
+}
+
+/** `append` for the bridge's file: one event at `path`, as a statement the key signs. It lands
+ *  with the key as its signer, under the paths a member allowed the key and nowhere else. */
+export const bridgeAppend =
+  (address: string, key: BridgeKey) =>
+  async (path: string, event: { type: string; payload?: Record<string, unknown> }) => {
+    const envelope = await key.sign({ mind: address, path, ...event });
+    const answer = await fetch(`https://${address}${STATEMENTS_PATH}`, {
+      method: "POST",
+      headers: { "content-type": "application/json" },
+      body: JSON.stringify(envelope),
+      signal: AbortSignal.timeout(20_000),
+    });
+    if (answer.ok) return;
+    const { refused } = (await answer.json().catch(() => ({}))) as { refused?: string };
+    throw new Error(`The mind did not take the event at ${path}: ${refused || answer.status}`);
+  };
A core/lib/src/cli/chatgpt.test.ts
@@ -0,0 +1,290 @@
+// chatgpt.test.ts — `iterate chatgpt connect` without OpenAI: the consent URL, what the callback
+// listener does with each request, the Cloud's page it sends the browser to, and the finish
+// script's text.
+import { createHash } from "node:crypto";
+import { setTimeout as sleep } from "node:timers/promises";
+import { expect, onTestFinished, test, vi } from "vitest";
+import type { MindItx } from "../node.ts";
+import {
+  authorizeUrl,
+  connectChatgpt,
+  connectedUrl,
+  finishScript,
+  hostScript,
+  waitForCallback,
+} from "./chatgpt.ts";
+
+test("the consent URL asks OpenAI for the plan's usage, for this mind's host id, with PKCE", () => {
+  const url = authorizeUrl({
+    hostId: "urn:uuid:1",
+    address: "iterate.example.com",
+    state: "the-state",
+    verifier: "the-verifier",
+    nonce: "the-nonce",
+  });
+  expect(url.origin + url.pathname).toBe("https://auth.openai.com/api/accounts/authorize");
+  expect(Object.fromEntries(url.searchParams)).toEqual({
+    client_id: "dynamic_agent_client",
+    agent_name_hint: "iterate.example.com",
+    ext_agent_host_id: "urn:uuid:1",
+    response_type: "code",
+    redirect_uri: "http://127.0.0.1:1455/auth/callback",
+    resource: "https://api.openai.com/v1",
+    scope: "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct",
+    state: "the-state",
+    code_challenge: createHash("sha256").update("the-verifier").digest("base64url"),
+    code_challenge_method: "S256",
+    nonce: "the-nonce",
+  });
+});
+
+test("the listener answers another sign-in's callback 400, then holds the code's request until the terminal step answers it", async () => {
+  const { promise: listening, resolve } = Promise.withResolvers<void>();
+  const port = 41455;
+  const callback = waitForCallback("s", resolve, port);
+  await listening;
+  const base = `http://127.0.0.1:${port}/auth/callback`;
+  const stray = await fetch(`${base}?state=other&code=c&client_id=x`);
+  const answered = fetch(`${base}?state=s&code=c&client_id=oaiapp_1`, { redirect: "manual" });
+  const { answer, ...handed } = await callback;
+  // the browser waits while the mind stores the secret
+  const early = await Promise.race([answered.then(() => "answered"), sleep(50).then(() => "held")]);
+  answer({ kind: "redirect", to: new URL("https://cloud.example.com/connected?ai=chatgpt") });
+  const response = await answered;
+  expect({
+    stray: stray.status,
+    early,
+    status: response.status,
+    location: response.headers.get("location"),
+    handed,
+  }).toEqual({
+    stray: 400,
+    early: "held",
+    status: 303,
+    location: "https://cloud.example.com/connected?ai=chatgpt",
+    handed: { code: "c", clientId: "oaiapp_1" },
+  });
+});
+
+test("with no Cloud the listener's own page says whether ChatGPT connected", async () => {
+  const pageAfter = async (port: number, failed: boolean) => {
+    const { promise: listening, resolve } = Promise.withResolvers<void>();
+    const callback = waitForCallback("s", resolve, port);
+    await listening;
+    const answered = fetch(`http://127.0.0.1:${port}/auth/callback?state=s&code=c&client_id=x`);
+    (await callback).answer({ kind: "page", failed });
+    const text = await (await answered).text();
+    return text.match(/<h1>(.*?)<\/h1>/)?.[1];
+  };
+  expect([await pageAfter(41457, false), await pageAfter(41458, true)]).toEqual([
+    "ChatGPT is connected",
+    "ChatGPT did not connect",
+  ]);
+});
+
+test("the Cloud's page is on the origin the mind names, and only on an origin", () => {
+  expect(connectedUrl("https://cloud.example.com", "example.com", { state: "passed" })?.href).toBe(
+    "https://cloud.example.com/connected?ai=chatgpt&domain=example.com&test=passed",
+  );
+  expect(
+    [null, "", "cloud.example.com", "https://cloud.example.com/x", "javascript:alert(1)"].map(
+      (cloud) => connectedUrl(cloud, "example.com", { state: "passed" }),
+    ),
+  ).toEqual([null, null, null, null, null]);
+});
+
+test("the Cloud's page says the test's outcome: OpenAI's words for a failed one, cut at 300", () => {
+  const failed = connectedUrl("https://cloud.example.com", "example.com", {
+    state: "failed",
+    why: `OpenAI answered 403: ${"x".repeat(400)}`,
+  });
+  expect(failed?.searchParams.get("test")).toBe("failed");
+  expect(failed?.searchParams.get("why")).toHaveLength(300);
+  expect(failed?.searchParams.get("why")).toMatch(/^OpenAI answered 403: x+$/);
+  const skipped = connectedUrl("https://cloud.example.com", "example.com", { state: "skipped" });
+  expect(skipped?.searchParams.get("test")).toBe("skipped");
+  expect(skipped?.searchParams.has("why")).toBe(false);
+});
+
+test("the listener ends with OpenAI's description when the sign-in was refused", async () => {
+  const { promise: listening, resolve } = Promise.withResolvers<void>();
+  const port = 41456;
+  const callback = waitForCallback("s", resolve, port);
+  void callback.catch(() => {});
+  await listening;
+  await fetch(
+    `http://127.0.0.1:${port}/auth/callback?state=s&error=access_denied&error_description=No+plan`,
+  );
+  await expect(callback).rejects.toThrow("ChatGPT did not connect: No plan");
+});
+
+test("the finish script keeps every value inside its JSON string", async () => {
+  const clientId = `oaiapp_"); globalThis.leaked = ("`;
+  const script = finishScript({ code: "c\nd", clientId, verifier: "v" });
+  // the script runs as the mind would run it, with fetch and itx recorded
+  const seen: { body?: string; material?: unknown; account?: string } = {};
+  const fakeFetch = async (_url: string, init: { body: string }) => {
+    seen.body = init.body;
+    const claims = btoa(JSON.stringify({ sub: "u1", email: "a@example.com" }));
+    return Response.json({
+      access_token: "at",
+      refresh_token: "rt",
+      id_token: `h.${claims}.s`,
+      scope: "openid chatgpt.tokens.use.direct",
+    });
+  };
+  const itx = {
+    secrets: { set: async (_path: string, material: unknown) => void (seen.material = material) },
+    kv: {
+      put: async (_key: string, value: string) => void (seen.account = value),
+      delete: async () => {},
+    },
+  };
+  vi.stubGlobal("fetch", fakeFetch);
+  onTestFinished(() => void vi.unstubAllGlobals());
+  const module = await import(
+    `data:text/javascript,${encodeURIComponent(`export default ${script}`)}`
+  );
+  const run = module.default as (itx: unknown) => Promise<unknown>;
+  expect(await run(itx)).toEqual({ email: "a@example.com" });
+  expect({
+    leaked: "leaked" in globalThis,
+    body: Object.fromEntries(new URLSearchParams(seen.body)),
+    material: seen.material,
+    account: JSON.parse(seen.account!).id,
+  }).toEqual({
+    leaked: false,
+    body: {
+      grant_type: "authorization_code",
+      client_id: clientId,
+      code: "c\nd",
+      code_verifier: "v",
+      redirect_uri: "http://127.0.0.1:1455/auth/callback",
+      resource: "https://api.openai.com/v1",
+    },
+    material: { accessToken: "at", refreshToken: "rt", clientId },
+    account: "u1",
+  });
+});
+
+test("the host script names the Cloud of the newest enrolment the Cloud signed, and none when no Cloud enrolled the mind", async () => {
+  const module = await import(
+    `data:text/javascript,${encodeURIComponent(`export default ${hostScript()}`)}`
+  );
+  const run = module.default as (itx: unknown) => Promise<{ cloud: string | null }>;
+  const itxWith = (read: () => Promise<unknown>) => ({
+    kv: { get: async () => "1", put: async () => {} },
+    secrets: { list: async () => [] },
+    cd: (path: string) => ({
+      readEvents: path === "/integrations/cloud" ? read : async () => ({ events: [] }),
+    }),
+  });
+  const enrolled = (cloud: unknown, actor = "iterate-cloud") => ({
+    type: "events.iterate.com/cloud/deployment-enrolled",
+    payload: { cloud },
+    source: { signer: { principal: { actor }, key: "k" } },
+  });
+  const unsigned = {
+    type: "events.iterate.com/cloud/deployment-enrolled",
+    payload: { cloud: "https://unsigned.example.com" },
+  };
+  const clouds = await Promise.all(
+    [
+      async () => ({
+        events: [
+          enrolled("https://a.example.com"),
+          { type: "other" },
+          enrolled("https://b.example.com"),
+        ],
+      }),
+      async () => ({ events: [] }),
+      async () => ({ events: [enrolled(42)] }),
+      async () => Promise.reject(new Error("no such context")),
+      // an unsigned statement, or one another key signed, is ignored, even when it is newer
+      async () => ({
+        events: [
+          enrolled("https://a.example.com"),
+          unsigned,
+          enrolled("https://other.example.com", "someone-else"),
+        ],
+      }),
+      async () => ({ events: [unsigned, enrolled("https://other.example.com", "someone-else")] }),
+    ].map(async (read) => (await run(itxWith(read))).cloud),
+  );
+  expect(clouds).toEqual([
+    "https://b.example.com",
+    null,
+    null,
+    null,
+    "https://a.example.com",
+    null,
+  ]);
+});
+
+test("the test request runs before the browser moves on, and the Cloud's page says how it went", async () => {
+  const connectWith = async (port: number, answerOfTest: () => string) => {
+    const calls: string[] = [];
+    const itx = {
+      run: async (script: string) => {
+        if (script.includes("Reply with the single word")) {
+          calls.push("test");
+          return answerOfTest();
+        }
+        if (script.includes("authorization_code")) {
+          calls.push("finish");
+          return { email: "ada@example.com", plan: "plus" };
+        }
+        calls.push("host");
+        return { hostId: "urn:uuid:h", connected: false, cloud: "https://cloud.example.com" };
+      },
+    } as unknown as MindItx;
+    let browser: Promise<{ location: string | null; callsThen: string[] }> | undefined;
+    const connected = await connectChatgpt({
+      itx,
+      address: "example.com",
+      test: true,
+      port,
+      print: () => {},
+      openBrowser: (url) => {
+        const state = url.searchParams.get("state");
+        browser = fetch(
+          `http://127.0.0.1:${port}/auth/callback?state=${state}&code=c&client_id=x`,
+          {
+            redirect: "manual",
+          },
+        ).then((response) => ({
+          location: response.headers.get("location"),
+          callsThen: [...calls],
+        }));
+      },
+    }).catch((error: Error) => ({ error: error.message }));
+    return { connected, browser: await browser };
+  };
+  expect(await connectWith(41459, () => "ready")).toMatchObject({
+    connected: {
+      message: expect.stringContaining(
+        "The plan pays for chat, not for voice calls: voice needs an OpenAI API key or iterate Cloud credit.",
+      ),
+      test: "ready",
+    },
+    browser: {
+      callsThen: ["host", "finish", "test"],
+      location: "https://cloud.example.com/connected?ai=chatgpt&domain=example.com&test=passed",
+    },
+  });
+  const failed = await connectWith(41460, () => {
+    throw new Error("OpenAI answered 401: no plan");
+  });
+  const back = new URL(failed.browser?.location || "about:blank");
+  expect({
+    connected: failed.connected,
+    callsThen: failed.browser?.callsThen,
+    test: back.searchParams.get("test"),
+    why: back.searchParams.get("why"),
+  }).toEqual({
+    connected: { error: "OpenAI answered 401: no plan" },
+    callsThen: ["host", "finish", "test"],
+    test: "failed",
+    why: "OpenAI answered 401: no plan",
+  });
+});
A core/lib/src/cli/chatgpt.ts
@@ -0,0 +1,447 @@
+// chatgpt.ts — `iterate chatgpt connect`: A PERSON'S CHATGPT PLAN PAYS FOR THE MIND'S RESPONSES
+// API REQUESTS, with nothing to paste. OpenAI's Sign in with ChatGPT for open-source tools
+// (https://developers.openai.com/siwc/token-sharing-open-source) ends at a loopback address,
+// http://127.0.0.1:1455/auth/callback, on the computer the browser runs on. A mind runs
+// elsewhere, so this process listens there and hands the code to the mind:
+//
+//   1. the mind says its host id (made once, kept in its kv)
+//   2. this process listens on 127.0.0.1:1455 and opens OpenAI's consent in the browser
+//   3. OpenAI sends the browser back here with a code and the client it registered
+//   4. the mind trades the code for tokens and keeps them, in one `itx.run` script
+//   5. the mind sends one test request on the plan (not with `--no-test`)
+//   6. the browser's request waits for steps 4 and 5, then goes to the Cloud's `/connected` page
+//      with the test's outcome, so the wizard tab sees that the connect ended and whether the plan
+//      answered (or, with no Cloud, it gets a page that says so)
+//
+// The tokens are made inside the mind and never reach this computer. This process holds the
+// PKCE verifier and the code for one sign-in, and sends both to the mind once. The names below
+// are the ChatGPT integration's (the `iterate-chatgpt` package), which reads and writes the same.
+import { createHash, randomBytes } from "node:crypto";
+import { createServer } from "node:http";
+import type { MindItx } from "../node.ts";
+import { standalonePage } from "../standalone-page.ts";
+
+const ISSUER = "https://auth.openai.com";
+const AUTHORIZE_URL = `${ISSUER}/api/accounts/authorize`;
+const TOKEN_URL = `${ISSUER}/api/accounts/oauth/token`;
+/** There is nothing to register: the sign-in starts as this client, and OpenAI registers a public
+ *  client for the person during the consent and names it in the callback (`client_id`). */
+const DYNAMIC_CLIENT_ID = "dynamic_agent_client";
+/** The only redirect a public client gets. */
+const REDIRECT_URI = "http://127.0.0.1:1455/auth/callback";
+/** Requests for this resource are what the plan pays for. The code exchange is refused without it. */
+const RESOURCE = "https://api.openai.com/v1";
+/** The secret that holds the tokens: `accessToken`, `refreshToken` and `clientId`. */
+const SECRET = "/secrets/chatgpt";
+/** The only origins the tokens are ever sent to. */
+const PIN = ["https://api.openai.com", "https://auth.openai.com"];
+const HOST_KEY = "chatgpt/host";
+/** Where the iterate Cloud's statement lands when it enrols the mind: the payload of its
+ *  `deployment-enrolled` names the Cloud's origin (`cloud`). The mind takes that name only with the
+ *  key of the Cloud its config names (auth-worker key-rules.ts), so this is the config's
+ *  `cloud.origin` as the mind sees it. */
+const CLOUD_PATH = "/integrations/cloud";
+const ACCOUNT_KEY = "chatgpt/account";
+/** A sign-in the integration's Connect page has open, which this one ends. */
+const PENDING_KEY = "chatgpt/pending";
+/** The agents' default model: `llm.model` in agents/contract.ts. The contract module is not
+ *  imported, so the CLI's bundle stays without the agents' code. */
+const TEST_MODEL = "gpt-6.2-sol";
+const WAIT_MS = 15 * 60_000;
+
+export type Account = { id: string; email?: string; plan?: string; at: string };
+
+/** The account an id token names: its OpenID `sub`, its address, and the plan when the token says.
+ *  The claims are not verified: the token comes straight from OpenAI's token endpoint over TLS, and
+ *  they only label the account. The function runs in the mind (`finishScript` puts its text
+ *  there), so it refers to nothing outside itself. */
+function accountOf(idToken: string | undefined): Account {
+  let claims: Record<string, any> = {};
+  const part = idToken?.split(".")[1];
+  if (part) {
+    try {
+      const base64 = part.replace(/-/g, "+").replace(/_/g, "/");
+      const bytes = Uint8Array.from(
+        atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")),
+        (character) => character.charCodeAt(0),
+      );
+      claims = JSON.parse(new TextDecoder().decode(bytes));
+    } catch {}
+  }
+  if (typeof claims.sub !== "string" || claims.sub === "")
+    throw new Error("OpenAI's answer names no account");
+  const plan: unknown = claims["https://api.openai.com/auth"]?.chatgpt_plan_type;
+  return {
+    id: claims.sub,
+    ...(typeof claims.email === "string" && { email: claims.email }),
+    ...(typeof plan === "string" && { plan }),
+    at: new Date().toISOString(),
+  };
+}
+
+/** The exchange code the secret refreshes itself with (the platform runs it in a jail whose only
+ *  egress is the secret's pin): trade the refresh token for new tokens with the client OpenAI
+ *  registered. OpenAI rotates the refresh token, so the answer's is kept. */
+const EXCHANGE_SOURCE = `const TOKEN_URL = ${JSON.stringify(TOKEN_URL)};
+const RESOURCE = ${JSON.stringify(RESOURCE)};
+export async function exchange(material, fetch) {
+  if (!material.refreshToken || !material.clientId)
+    throw new Error("the secret holds no refresh token or client id");
+  const response = await fetch(TOKEN_URL, {
+    method: "POST",
+    headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
+    body: new URLSearchParams({
+      grant_type: "refresh_token",
+      client_id: material.clientId,
+      refresh_token: material.refreshToken,
+      resource: RESOURCE,
+    }).toString(),
+  });
+  if (!response.ok) {
+    const body = await response.json().catch(() => ({}));
+    const code = (body.error && body.error.code) || body.code || body.error || "";
+    throw new Error(
+      "ChatGPT refused the refresh (" + response.status + (typeof code === "string" && code ? " " + code : "") +
+        "): connect ChatGPT again",
+    );
+  }
+  const tokens = await response.json();
+  if (!tokens.access_token) throw new Error("ChatGPT's refresh answered with no access token");
+  return {
+    ...material,
+    accessToken: tokens.access_token,
+    refreshToken: tokens.refresh_token || material.refreshToken,
+  };
+}
+`;
+
+const random = () => randomBytes(32).toString("base64url");
+
+/** OpenAI's consent page for one sign-in. `hostId` is the mind's `urn:uuid:` id: OpenAI
+ *  attributes the plan's usage to it. `address` is the mind's address (`iterate.example.com`):
+ *  the page suggests it as the name, so that a person with two minds tells their connections
+ *  apart. */
+export function authorizeUrl(input: {
+  hostId: string;
+  address: string;
+  state: string;
+  verifier: string;
+  nonce: string;
+}): URL {
+  const url = new URL(AUTHORIZE_URL);
+  url.search = new URLSearchParams({
+    client_id: DYNAMIC_CLIENT_ID,
+    // what the consent page calls the app; the person may rename it there
+    agent_name_hint: input.address,
+    ext_agent_host_id: input.hostId,
+    response_type: "code",
+    redirect_uri: REDIRECT_URI,
+    resource: RESOURCE,
+    scope: "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct",
+    state: input.state,
+    code_challenge: createHash("sha256").update(input.verifier).digest("base64url"),
+    code_challenge_method: "S256",
+    nonce: input.nonce,
+  }).toString();
+  return url;
+}
+
+/** What a request to the callback says: another sign-in's (or a stray request), OpenAI's refusal,
+ *  or the code and the client OpenAI registered. */
+export type Callback =
+  | { kind: "other" }
+  | { kind: "error"; message: string }
+  | { kind: "code"; code: string; clientId: string };
+
+function readCallback(url: URL, state: string): Callback {
+  if (url.pathname !== new URL(REDIRECT_URI).pathname || url.searchParams.get("state") !== state)
+    return { kind: "other" };
+  const error = url.searchParams.get("error");
+  if (error)
+    return {
+      kind: "error",
+      message: `ChatGPT did not connect: ${url.searchParams.get("error_description") ?? error}`,
+    };
+  const code = url.searchParams.get("code");
+  const clientId = url.searchParams.get("client_id")?.trim();
+  if (!code || !clientId)
+    return { kind: "error", message: "OpenAI's address holds no code or names no client." };
+  return { kind: "code", code, clientId };
+}
+
+/** How the browser's request to the callback ends, once the terminal step is over: a redirect to
+ *  the Cloud's page, or a page of its own. */
+export type Answer = { kind: "redirect"; to: URL } | { kind: "page"; failed: boolean };
+
+/** The local page the browser sees when there is no Cloud to send it to, or the connect failed. */
+function callbackPage(failed: boolean): string {
+  return failed
+    ? standalonePage({
+        title: "ChatGPT did not connect",
+        head: "",
+        body: "<h1>ChatGPT did not connect</h1><p>The terminal says why. You can close this tab.</p>",
+      })
+    : standalonePage({
+        title: "ChatGPT is connected",
+        head: "",
+        body: "<h1>ChatGPT is connected</h1><p>Your mind uses your ChatGPT plan now. You can close this tab.</p>",
+      });
+}
+
+/** Listen on 127.0.0.1:1455 until OpenAI's callback for `state` comes, or 15 minutes pass.
+ *  `onListening` runs once the port is ours, so the browser opens only then. A refusal is
+ *  answered at once. A code is handed over with `answer`: the browser's request stays open until
+ *  `answer` runs, so the tab shows what the terminal step did. */
+export function waitForCallback(
+  state: string,
+  onListening: () => void,
+  port = Number(new URL(REDIRECT_URI).port),
+): Promise<{ code: string; clientId: string; answer: (answer: Answer) => void }> {
+  const { promise, resolve, reject } = Promise.withResolvers<{
+    code: string;
+    clientId: string;
+    answer: (answer: Answer) => void;
+  }>();
+  const server = createServer((request, response) => {
+    const callback = readCallback(new URL(request.url || "/", REDIRECT_URI), state);
+    if (callback.kind === "other") {
+      response
+        .writeHead(400, { "content-type": "text/plain; charset=utf-8" })
+        .end("This address belongs to another sign-in.\n");
+      return;
+    }
+    // no other request is taken; the one held here stays open until it is answered
+    clearTimeout(timeout);
+    server.close();
+    const answer = (answer: Answer) => {
+      response.once("finish", () => server.closeAllConnections());
+      if (answer.kind === "redirect")
+        response.writeHead(303, { location: answer.to.href, "cache-control": "no-store" }).end();
+      else
+        response
+          .writeHead(200, { "content-type": "text/html; charset=utf-8" })
+          .end(callbackPage(answer.failed));
+    };
+    if (callback.kind === "error") {
+      answer({ kind: "page", failed: true });
+      reject(new Error(callback.message));
+      return;
+    }
+    resolve({ code: callback.code, clientId: callback.clientId, answer });
+  });
+  const timeout = setTimeout(() => {
+    close();
+    reject(new Error("Nobody came back from the ChatGPT sign-in within 15 minutes."));
+  }, WAIT_MS);
+  const close = () => {
+    clearTimeout(timeout);
+    server.close();
+    server.closeAllConnections();
+  };
+  server.on("error", (error: NodeJS.ErrnoException) => {
+    close();
+    reject(
+      error.code === "EADDRINUSE"
+        ? new Error(
+            `Port ${port} on 127.0.0.1 is in use, probably by a Codex sign-in. Close it and start again.`,
+          )
+        : error,
+    );
+  });
+  server.listen(port, "127.0.0.1", onListening);
+  return promise;
+}
+
+/** The Cloud's page that tells an open wizard tab that a connect for `address` ended. It carries
+ *  no secret. `cloud` is an origin the mind's log names, so it is checked to be one. */
+/** What the test request found, for the Cloud's page: the iterate Cloud's AI step opens only on
+ *  `passed`. `failed` carries OpenAI's words; `skipped` is `--no-test`. */
+export type TestOutcome =
+  | { state: "passed" }
+  | { state: "failed"; why: string }
+  | { state: "skipped" };
+
+export function connectedUrl(cloud: string | null, address: string, test: TestOutcome): URL | null {
+  if (!cloud) return null;
+  let origin: URL;
+  try {
+    origin = new URL(cloud);
+  } catch {
+    return null;
+  }
+  if (origin.origin !== cloud || !["https:", "http:"].includes(origin.protocol)) return null;
+  const url = new URL("/connected", origin);
+  const search = new URLSearchParams({ ai: "chatgpt", domain: address, test: test.state });
+  if (test.state === "failed") search.set("why", test.why.slice(0, 300));
+  url.search = search.toString();
+  return url;
+}
+
+/** The mind's host id, made once, who is connected now, and the Cloud that enrolled the mind. */
+export function hostScript(): string {
+  return `async (itx) => {
+  let id = await itx.kv.get(${JSON.stringify(HOST_KEY)});
+  if (!id) {
+    id = crypto.randomUUID();
+    await itx.kv.put(${JSON.stringify(HOST_KEY)}, id);
+  }
+  const account = JSON.parse((await itx.kv.get(${JSON.stringify(ACCOUNT_KEY)})) || "null");
+  // the Cloud that enrolled this mind, if one did: the newest statement's origin
+  const enrolled = await itx.cd(${JSON.stringify(CLOUD_PATH)}).readEvents(0, 500).catch(() => null);
+  // only the Cloud's own statement counts: the mind stamps \`source.signer\` on a statement whose key
+  // the auth Worker verified, and drops a writer's own \`source\` (core/itx caller.ts \`stampCaller\`)
+  const cloud = (enrolled?.events || [])
+    .filter((event) => event.type === "events.iterate.com/cloud/deployment-enrolled" && event.source?.signer?.principal?.actor === "iterate-cloud")
+    .at(-1)?.payload?.cloud;
+  return {
+    hostId: "urn:uuid:" + id,
+    connected: (await itx.secrets.list()).some((secret) => secret.path === ${JSON.stringify(SECRET)}),
+    email: account?.email,
+    cloud: typeof cloud === "string" ? cloud : null,
+  };
+}`;
+}
+
+/** The mind trades the code for tokens and keeps them: the secret, its refresh code, and the
+ *  account. It answers only `{ email, plan }`. Every value goes in as JSON. */
+export function finishScript(input: { code: string; clientId: string; verifier: string }): string {
+  return `async (itx) => {
+  const accountOf = ${accountOf.toString()};
+  const answer = await fetch(${JSON.stringify(TOKEN_URL)}, {
+    method: "POST",
+    headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
+    body: new URLSearchParams(${JSON.stringify({
+      grant_type: "authorization_code",
+      client_id: input.clientId,
+      code: input.code,
+      code_verifier: input.verifier,
+      redirect_uri: REDIRECT_URI,
+      resource: RESOURCE,
+    })}).toString(),
+  });
+  if (!answer.ok)
+    throw new Error("OpenAI would not hand over tokens (HTTP " + answer.status + ": " + (await answer.text()).slice(0, 200) + "). Start again.");
+  const tokens = await answer.json();
+  if (!tokens.access_token || !tokens.refresh_token)
+    throw new Error("OpenAI's answer holds no access or refresh token. Start again.");
+  if (!String(tokens.scope || "").split(/\\s+/).includes("chatgpt.tokens.use.direct"))
+    throw new Error("OpenAI did not grant the plan's usage to this sign-in. Is this a Plus or Pro personal account?");
+  const account = accountOf(tokens.id_token);
+  await itx.secrets.set(
+    ${JSON.stringify(SECRET)},
+    { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, clientId: ${JSON.stringify(input.clientId)} },
+    { urls: ${JSON.stringify(PIN)}, refresh: { kind: "worker", source: ${JSON.stringify(EXCHANGE_SOURCE)} } },
+  );
+  await itx.kv.put(${JSON.stringify(ACCOUNT_KEY)}, JSON.stringify(account));
+  await itx.kv.delete(${JSON.stringify(PENDING_KEY)});
+  return { email: account.email, plan: account.plan };
+}`;
+}
+
+/** One Responses request the plan pays for, sent from the mind; it answers the text. */
+function testScript(): string {
+  return `async (itx) => {
+  const response = await fetch(${JSON.stringify(`${RESOURCE}/responses`)}, {
+    method: "POST",
+    headers: {
+      authorization: ${JSON.stringify(`Bearer getSecret(${JSON.stringify(SECRET)}, { field: "accessToken" })`)},
+      "content-type": "application/json",
+    },
+    // a plan's token answers only a stream, keeps nothing, and takes input as a list
+    body: JSON.stringify({
+      model: ${JSON.stringify(TEST_MODEL)},
+      input: [{ role: "user", content: "Reply with the single word: ready" }],
+      reasoning: { effort: "low" },
+      stream: true,
+      store: false,
+    }),
+  });
+  const stream = await response.text();
+  if (!response.ok) throw new Error("OpenAI answered " + response.status + ": " + stream.slice(0, 300));
+  let text = "";
+  for (const line of stream.split("\\n")) {
+    if (!line.startsWith("data:")) continue;
+    try {
+      const event = JSON.parse(line.slice(5));
+      if (event.type === "response.output_text.delta") text += event.delta;
+    } catch {}
+  }
+  return text.trim();
+}`;
+}
+
+/** The whole sign-in against a connected mind. `openBrowser` prints and opens the consent page. */
+export async function connectChatgpt(input: {
+  itx: MindItx;
+  address: string;
+  test: boolean;
+  print: (line: string) => void;
+  openBrowser: (url: URL) => void | Promise<void>;
+  /** The callback's port; only a test changes it (OpenAI redirects to 1455 alone). */
+  port?: number;
+}): Promise<{ message: string; test?: string }> {
+  const { itx, address, print } = input;
+  // `run` answers unknown; the host script above returns this shape
+  const mind = (await itx.run(hostScript())) as {
+    hostId: string;
+    connected: boolean;
+    email?: string;
+    cloud: string | null;
+  };
+  if (mind.connected)
+    print(
+      `${address} has a ChatGPT plan already (${mind.email || "an account it does not name"}). This sign-in replaces it.`,
+    );
+  const state = random();
+  const verifier = random();
+  const url = authorizeUrl({
+    hostId: mind.hostId,
+    address,
+    state,
+    verifier,
+    nonce: random(),
+  });
+  const callback = await waitForCallback(
+    state,
+    () => {
+      print("Sign in with a personal ChatGPT Plus or Pro account, and allow iterate.");
+      void input.openBrowser(url);
+      print("Waiting for the browser to come back (15 minutes at most)...");
+    },
+    input.port,
+  );
+  print(`Signed in. ${address} now gets its tokens from OpenAI...`);
+  let account: { email?: string; plan?: string };
+  try {
+    // `run` answers unknown; the finish script returns this shape
+    account = (await itx.run(finishScript({ ...callback, verifier }))) as typeof account;
+  } catch (error) {
+    callback.answer({ kind: "page", failed: true });
+    throw error;
+  }
+  // only now is the secret stored. The test request goes before the browser moves on, so the
+  // Cloud's page learns whether the plan answered: the Cloud hands a person over to their mind only
+  // once its agent can answer
+  let test: string | undefined;
+  let outcome: TestOutcome = { state: "skipped" };
+  let failure: unknown = null;
+  if (input.test) {
+    print("Connected. A test request on the plan...");
+    try {
+      test = (await itx.run(testScript())) as string;
+      outcome = test
+        ? { state: "passed" }
+        : { state: "failed", why: "OpenAI answered with no text." };
+    } catch (error) {
+      failure = error;
+      outcome = { state: "failed", why: error instanceof Error ? error.message : String(error) };
+    }
+  }
+  const cloudPage = connectedUrl(mind.cloud, address, outcome);
+  callback.answer(
+    cloudPage ? { kind: "redirect", to: cloudPage } : { kind: "page", failed: false },
+  );
+  const message = `Connected ${account.email || "an account"}${account.plan ? ` (${account.plan})` : ""} to ${address}. The mind keeps the tokens in ${SECRET} and refreshes them itself.\nThe plan pays for chat, not for voice calls: voice needs an OpenAI API key or iterate Cloud credit.`;
+  if (failure) throw failure;
+  return input.test ? { message, test } : { message };
+}
A core/lib/src/cli/cli.test.ts
@@ -0,0 +1,109 @@
+import { spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { createCli, os } from "trpc-cli";
+import { expect, test } from "vitest";
+import { z } from "zod";
+import { LoginInput, loginArgvOf, packageVersionOf } from "./cli.ts";
+
+/** `iterate <argv>` as the CLI parses it, with a `login` that signs in nowhere: what the handler
+ *  got, the exit code and what was printed. */
+const parsedLogin = async (argv: string[]) => {
+  const inputs: z.infer<typeof LoginInput>[] = [];
+  const printed: string[] = [];
+  let exitCode: number | undefined;
+  const cli = createCli({
+    name: "iterate",
+    router: {
+      login: os.input(LoginInput).handler(({ input }) => {
+        inputs.push(input);
+        return "signed in";
+      }),
+    },
+  });
+  await cli
+    .run({
+      argv: loginArgvOf(argv),
+      prompts: false,
+      logger: {
+        info: (line) => printed.push(String(line)),
+        error: (line) => printed.push(String(line)),
+      },
+      process: {
+        exit: (code) => {
+          exitCode ??= code;
+          return undefined as never;
+        },
+      },
+    })
+    .catch(() => {});
+  return { inputs, exitCode, printed: printed.join("\n") };
+};
+
+test.for<{ argv: string[]; input: z.infer<typeof LoginInput> }>([
+  { argv: ["login", "--device", "example.com"], input: { address: "example.com", device: true } },
+  { argv: ["login", "example.com", "--device"], input: { address: "example.com", device: true } },
+  { argv: ["login", "example.com"], input: { address: "example.com" } },
+  {
+    argv: ["login", "--device", "true", "example.com"],
+    input: { address: "example.com", device: true },
+  },
+  {
+    argv: ["login", "--device", "false", "example.com"],
+    input: { address: "example.com", device: false },
+  },
+  {
+    argv: ["login", "example.com", "--device", "false"],
+    input: { address: "example.com", device: false },
+  },
+  {
+    argv: ["login", "--device=false", "example.com"],
+    input: { address: "example.com", device: false },
+  },
+  {
+    argv: ["login", "--device", "--expect-user", "a@example.com", "example.com"],
+    input: { address: "example.com", device: true, expectUser: "a@example.com" },
+  },
+])("iterate $argv hands login $input", async ({ argv, input }) => {
+  const { inputs, exitCode } = await parsedLogin(argv);
+  expect({ inputs, exitCode }).toEqual({ inputs: [input], exitCode: 0 });
+});
+
+test.for([["login", "--device"], ["login", "--device", "false"], ["login"]])(
+  "iterate %s names the missing address and signs in nowhere",
+  async (...[argv]) => {
+    const { inputs, exitCode, printed } = await parsedLogin(argv);
+    expect({ inputs, exitCode }).toEqual({ inputs: [], exitCode: 1 });
+    expect(printed).toContain("missing required argument 'address'");
+  },
+);
+
+test("only login's --device is spelled anew", () => {
+  expect(loginArgvOf(["run", "--device", "x"])).toEqual(["run", "--device", "x"]);
+  expect(loginArgvOf(["login", "--device", "example.com"])).toEqual([
+    "login",
+    "--device=true",
+    "example.com",
+  ]);
+});
+
+test("iterate login --help shows the flag as it is taken", async () => {
+  expect((await parsedLogin(["login", "--help"])).printed).toContain("--device [boolean]");
+});
+
+test("iterate --version and -v print the package version and exit 0", () => {
+  const pkg = z
+    .object({ version: z.string().min(1) })
+    .parse(JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")));
+  expect(packageVersionOf()).toBe(pkg.version);
+
+  const bin = fileURLToPath(new URL("../../bin/iterate.js", import.meta.url));
+  for (const flag of ["--version", "-v", "-V"]) {
+    const result = spawnSync(process.execPath, [bin, flag], { encoding: "utf8" });
+    expect({ flag, status: result.status, stdout: result.stdout.trim() }).toEqual({
+      flag,
+      status: 0,
+      stdout: pkg.version,
+    });
+  }
+});
A core/lib/src/cli/cli.ts
@@ -0,0 +1,1099 @@
+// cli.ts — THE `iterate` CLI: sign in to a mind by its address, run scripts in it, and lend it
+// what runs on this machine (a file's functions, a local port, this computer). A profile
+// (./config.ts) names one mind; `--config <name>`, a folder mapped to a profile, the default
+// profile, or the only one picks it, and `--mind <address>` overrides it for one command. Every
+// connection is the Node client's (../node.ts `connectMind`).
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { text as streamText } from "node:stream/consumers";
+import { dirname, join, sep } from "node:path";
+import process from "node:process";
+import repl from "node:repl";
+import { setTimeout as sleep } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { RpcTarget } from "capnweb";
+import { createCli, os, yamlTableConsoleLogger } from "trpc-cli";
+import { z } from "zod";
+import {
+  addressOf,
+  connectMind,
+  discoveredMind,
+  mindToken,
+  openForSignIn,
+  signInToMind,
+} from "../node.ts";
+import {
+  mindApiUrlOf,
+  mindMcpUrlOf,
+  mindProvideConnectResourceOf,
+  ownSandboxOf,
+} from "../mind-api.ts";
+import { MCP_CLIENTS, type McpClient, mcpAddArgvOf } from "./mcp-clients.ts";
+import { connectChatgpt } from "./chatgpt.ts";
+import { isCodingAgent } from "./coding-agent.ts";
+import {
+  endKeptSignIn,
+  KeptSignIn,
+  keptSignInOf,
+  lockKept,
+  parsed,
+  SIGN_IN_FILE,
+  tokensMadeThrough,
+  writeKeptSignIn,
+} from "./cloudflare-access.ts";
+import { deployMind } from "./deploy.ts";
+import {
+  gitCredential,
+  type GitCredentialIo,
+  gitHostOf,
+  isHostOfMind,
+  mindOfGitHost,
+  personIsThere,
+  writeGitConfig,
+} from "./git.ts";
+import { IDENTITIES, type IdentityIo, postIdentity, shownIdentity } from "./identity.ts";
+import { recoverOwner } from "./recover.ts";
+import { runFs } from "./fs.ts";
+import { loginFlowFor, unexpectedUser } from "./device-login/flow.ts";
+import { revokeSession } from "./oauth.ts";
+import { bridgeAppend, bridgeKeyOf, bridgeToken } from "./bridge-key.ts";
+import { importProvidedFile, nameOfFile, type ProvidedFile, runProvide } from "./provide.ts";
+import { finalStateOf, type ProvideState } from "./provide-state.ts";
+import { runTunnel } from "./tunnel.ts";
+import { shareMyComputer } from "./share-my-computer.ts";
+import {
+  CONFIG_PATH,
+  DEFAULT_CONFIG_NAME,
+  readConfig,
+  readConfigFile,
+  readSession,
+  removeSession,
+  setConfigMind,
+  writeConfigFile,
+} from "./config.ts";
+
+const isAgent = isCodingAgent(process.env);
+let configFlagOverride: string | undefined;
+const consumeCliStringFlag = (flagName: string): string | undefined => {
+  const args = process.argv.slice(2);
+  const flagIndex = args.indexOf(flagName);
+  if (flagIndex === -1) return undefined;
+  const value = args[flagIndex + 1];
+  if (!value || value.startsWith("-")) throw new Error(`${flagName} requires a value`);
+  process.argv.splice(flagIndex + 2, 2);
+  return value;
+};
+
+/**
+ * Which profile to use. Priority: --config flag > workspace match (walk up from cwd) > default >
+ * the only profile > `default`.
+ */
+const resolveConfigName = (workspacePath: string): string => {
+  const configFile = readConfigFile();
+  const known = (name: string) =>
+    name === DEFAULT_CONFIG_NAME || Boolean(configFile.configs?.[name]);
+  const available = () => Object.keys(configFile.configs || {}).join(", ") || "(none)";
+  if (configFlagOverride) {
+    if (!known(configFlagOverride))
+      throw new Error(`Profile "${configFlagOverride}" not found. Available: ${available()}`);
+    return configFlagOverride;
+  }
+  for (let dir = workspacePath; dir && dir !== "/"; dir = dirname(dir)) {
+    const match = configFile.workspaces?.[dir];
+    if (!match) continue;
+    if (!known(match))
+      throw new Error(`Workspace "${dir}" maps to profile "${match}", which doesn't exist.`);
+    return match;
+  }
+  if (configFile.default) {
+    if (!known(configFile.default))
+      throw new Error(
+        `Default profile "${configFile.default}" doesn't exist. Available: ${available()}`,
+      );
+    return configFile.default;
+  }
+  const names = Object.keys(configFile.configs || {});
+  return names.length === 1 ? names[0]! : DEFAULT_CONFIG_NAME;
+};
+
+/** THE MIND A COMMAND TALKS TO, AS ITS ADDRESS: `--mind` as a person typed it, read here once
+ *  (node.ts `addressOf`) and as discovery keeps it; else the profile's, which `login` stored.
+ *  What this answers is handed on as it is: a second reading would put `iterate.` before a
+ *  control plane at a zone's apex. */
+const resolveMind = async (given?: string): Promise<string> => {
+  if (given) return (await discoveredMind(addressOf(given))).address;
+  // In a sandbox the platform names the mind (iterate/mind-api `sandboxVariablesOf`): no profile
+  // is needed there. `--config` still picks a profile.
+  const told = process.env.ITERATE_SANDBOX?.trim() && process.env.ITERATE_MIND?.trim();
+  if (told && !configFlagOverride) return addressOf(told);
+  const name = resolveConfigName(process.cwd());
+  const config = readConfig(name);
+  if (config instanceof Error) throw config;
+  if (!config.mind)
+    throw new Error(
+      `Profile "${name}" names no mind. Run \`iterate login <address>\`, e.g. iterate login example.com.`,
+    );
+  return config.mind;
+};
+
+/** A connection to the mind at `address`, as `resolveMind` answered it. */
+const connect = (address: string) => connectMind({ address });
+
+/** When the stored sign-in to the mind at `address` ends, as epoch ms: what a lend hands over
+ *  before (provide.ts, THE HANDOVER). A token given in the environment has no end known here. */
+function signInEndsAt(address: string): number | undefined {
+  if (process.env.ITERATE_MIND_TOKEN?.trim()) return undefined;
+  const ends = Date.parse(readSession(mindApiUrlOf(address))?.expiresAt || "");
+  return Number.isFinite(ends) ? ends : undefined;
+}
+
+/** `iterate provide`'s lend, with a sign-in or (`key`) the bridge's own key, until Ctrl-C. */
+async function provideWith(input: {
+  address: string;
+  file: ProvidedFile;
+  name: string;
+  key?: string;
+  paths?: string;
+  report?: (state: ProvideState) => void;
+}) {
+  const { address, file, name, report } = input;
+  if (!input.key) {
+    // runProvide owns the connection from here, and every one `reconnect` opens
+    await runProvide({
+      connection: await connect(address),
+      reconnect: () => connect(address),
+      file,
+      name,
+      endsAt: () => signInEndsAt(address),
+      report,
+    });
+    return;
+  }
+  // THE BRIDGE'S OWN KEY (bridge-key.ts): each connection asks for a new token, which lives
+  // an hour. The first waits for a member to allow the key. A later one does not: a key that
+  // a member removed is refused, and the bridge says so and ends.
+  const key = await bridgeKeyOf(input.key);
+  const paths = input.paths?.split(",").map((path) => path.trim());
+  // ITERATE_KEY_TOKEN_SECONDS: a test's, to see a token end without waiting an hour
+  const seconds = Number(process.env.ITERATE_KEY_TOKEN_SECONDS) || undefined;
+  let tokenEndsAt = 0;
+  const connectWithKey = async (wait?: (line: string) => void) => {
+    const token = await bridgeToken({ address, name, key, paths, seconds, wait, report });
+    // a key's token lives the hour, or the seconds asked for
+    tokenEndsAt = Date.now() + (seconds || 3600) * 1000;
+    return connectMind({ address, token, signIn: false });
+  };
+  await runProvide({
+    connection: await connectWithKey((line) => console.error(line)),
+    reconnect: () => connectWithKey(),
+    file,
+    name,
+    append: bridgeAppend(address, key),
+    endsAt: () => tokenEndsAt,
+    report,
+  });
+}
+
+/** What `iterate login` takes. */
+export const LoginInput = z.object({
+  address: z.string().meta({ positional: true }).describe("The mind's address, e.g. example.com"),
+  device: z
+    .boolean()
+    .optional()
+    .describe(
+      "Approve from a browser on any device, when the mind's issuer offers it: the default over SSH, on Linux with no display, and under a coding agent",
+    ),
+  expectUser: z.string().optional().describe("Refuse and end a session for anyone but this email"),
+});
+
+/** `--device` takes an optional `true` or `false`, so the parser reads the word after it as its
+ *  value: `iterate login --device example.com` lost its address. Here a `--device` of `login` that
+ *  no `true` or `false` follows is spelled `--device=true`, and the next word stays what it was. */
+export const loginArgvOf = (argv: string[]): string[] =>
+  argv[0] === "login"
+    ? argv.map((arg, index) =>
+        arg === "--device" && !["true", "false"].includes(argv[index + 1] ?? "")
+          ? "--device=true"
+          : arg,
+      )
+    : argv;
+
+/** `iterate login`: sign in to the mind at `address` (as `addressOf` read it from what a person
+ *  typed), check who that is, and make it the profile's mind. `chatgpt connect` signs in by this
+ *  too. */
+const login = async (input: { address: string; device?: boolean; expectUser?: string }) => {
+  const mind = await discoveredMind(input.address);
+  const resource = mindApiUrlOf(mind.address);
+  const session = await signInToMind(mind, resource, {
+    flow: loginFlowFor({ device: input.device, env: process.env, platform: process.platform }),
+  });
+  using connection = await connectMind({ address: mind.address, token: session.token });
+  const who = await connection.itx.whoami();
+  const unexpected = unexpectedUser(who.principal?.email, input.expectUser);
+  if (unexpected) {
+    removeSession(resource);
+    await revokeSession(session).catch(() => {});
+    throw new Error(unexpected);
+  }
+  const name = resolveConfigName(process.cwd());
+  setConfigMind(name, mind.address);
+  return {
+    message: `Signed in to ${mind.address} as ${who.principal?.email || who.principal?.actor || "someone the mind does not name"}`,
+    profile: name,
+    expiresAt: session.expiresAt,
+  };
+};
+
+/** How git's credential helper reaches the CLI's sign-in to the mind at `address` (./git.ts). */
+const gitCredentialIo = (address: string): GitCredentialIo => ({
+  say: (line) => console.error(line),
+  async session({ leastLeftMs, signIn, anew }) {
+    const resource = mindApiUrlOf(address);
+    if (anew) removeSession(resource);
+    const token = await mindToken({
+      address,
+      resource,
+      leastLeftMs,
+      signIn: signIn ? {} : false,
+    });
+    const stored = readSession(resource);
+    if (stored?.token === token) return stored;
+    // a token from the environment (ITERATE_MIND_TOKEN): the issuer is found by discovery
+    const mind = await discoveredMind(address);
+    return { issuer: mind.issuer, tokenEndpoint: mind.endpoints.token, clientId: "", token };
+  },
+  // in a sandbox of this mind: the mind's own token for the repo, by the sandbox's own session
+  ...(ownSandboxOf(process.env, address) && {
+    async repoToken(repo, host) {
+      using connection = await connectMind({ address });
+      const mindUrl = await connection.itx.url();
+      if (!isHostOfMind(host, mindUrl))
+        throw new Error(`${host} is no host of this mind (${mindUrl}), so it gets no token`);
+      const token = await connection.itx.cfArtifacts.get(repo).createToken("write", 300);
+      return token.plaintext;
+    },
+  }),
+});
+
+/** THE COMMAND THAT GIT RUNS AS ITS HELPER for a host of the mind at `address`: this same CLI,
+ *  by the Node and the file that run now. A CLI that npx fetched lives in npx's cache, which npm
+ *  may clear, so that one is named as `npx` finds it again. */
+const gitHelperCommandOf = (address: string) => {
+  const script = realpathSync(process.argv[1]!);
+  const cli = script.includes(`${sep}_npx${sep}`)
+    ? ["npx", "--yes", "iterate"]
+    : [process.execPath, script];
+  return shellCommand([...cli, "git-credential", "--mind", address]);
+};
+
+/** `iterate git-credential --mind <address> <operation>`, as git runs it (./git.ts): its answer
+ *  goes to stdout as it is, with no logger between. */
+const runGitCredential = async (args: string[]): Promise<number> => {
+  const at = args.indexOf("--mind");
+  const address = at >= 0 ? args[at + 1] : undefined;
+  const operation = args.filter((_arg, index) => at < 0 || (index !== at && index !== at + 1))[0];
+  if (!address || !operation) {
+    console.error(
+      "iterate git-credential is git's own helper: `iterate git setup <host>` tells git how to run it.",
+    );
+    return 1;
+  }
+  process.stdout.write(
+    await gitCredential({
+      operation,
+      asked: await streamText(process.stdin),
+      address,
+      interactive: personIsThere(process.env, Boolean(process.stderr.isTTY)),
+      io: gitCredentialIo(address),
+    }),
+  );
+  return 0;
+};
+
+const mindOption = z
+  .string()
+  .optional()
+  .describe("The mind's address, e.g. example.com (default: the profile's)");
+
+/** The same, as a command's one argument. */
+const mindArgument = mindOption.meta({ positional: true });
+
+/** `iterate mcp <client>`: the command that adds the mind's MCP server to that coding agent
+ *  (./mcp-clients.ts), printed, or run with `--exec`. */
+const mcpCommand = (client: McpClient) =>
+  os
+    .input(
+      z.object({
+        mind: mindOption,
+        exec: z.boolean().optional().describe("Run the command instead of printing it"),
+      }),
+    )
+    .meta({
+      description: `The command that adds the mind's MCP server to ${MCP_CLIENTS[client].title}, for all your folders: printed, or run with --exec. ${MCP_CLIENTS[client].title} then signs in with the mind's issuer`,
+    })
+    .handler(async ({ input }) => {
+      const [command, ...args] = mcpAddArgvOf(client, mindMcpUrlOf(await resolveMind(input.mind)));
+      if (!input.exec) {
+        // stdout carries the command alone, so `eval "$(iterate mcp claude)"` runs it
+        console.log(shellCommand([command!, ...args]));
+        return;
+      }
+      const run = spawnSync(command!, args, { stdio: "inherit" });
+      if (run.error)
+        throw new Error(`Could not start ${command}: ${run.error.message}`, { cause: run.error });
+      process.exit(run.status ?? 1);
+    });
+
+/** THE ADDRESS THAT THE TWO `identity` COMMANDS ASK: `--mind` as a person typed it, read here
+ *  alone, with no discovery (no other host is asked first), else the profile's. */
+const identityAddressOf = async (given?: string) => (given ? addressOf(given) : resolveMind());
+
+/** How the two `identity` commands talk with the mind (identity.ts). */
+const identityIo: IdentityIo = {
+  dir: IDENTITIES,
+  fetcher: (request) => fetch(request),
+  pause: (ms) => sleep(ms),
+  say: (line) => console.error(line),
+};
+
+const launcherProcedures = {
+  deploy: os
+    .input(
+      z.object({
+        domain: z
+          .string()
+          .optional()
+          .describe("The mind's domain: a zone of the account, or one to buy or bring"),
+        account: z.string().optional().describe("The Cloudflare account, by id or name"),
+        newAccount: z.boolean().optional().describe("Make a new Cloudflare account for the mind"),
+        newSignIn: z
+          .boolean()
+          .optional()
+          .describe("Drop the kept Cloudflare sign-in and start a new one"),
+        owner: z
+          .string()
+          .optional()
+          .describe(
+            "The owner's email address (default: the Cloudflare login's; for a mind that is there already: the owners it has)",
+          ),
+        ownerEmailPatterns: z
+          .string()
+          .optional()
+          .describe(
+            "More owners by pattern: *@<domain> makes EVERY address at exactly that domain an owner, who proves the address with Cloudflare and adds a passkey; a comma between two; none takes them away. Name a domain only when its mail is the company's own (default: none; for a mind that is there already: what it has)",
+          ),
+        mcpTarget: z
+          .string()
+          .optional()
+          .describe(
+            "The method of the config's class that says what the mind's own MCP server offers: its instructions, the description of run, more tools and skills (the default config has mcp); none takes it away, and the platform's defaults then answer (for a mind that is there already: what it has)",
+          ),
+        controlPlaneHostname: z
+          .string()
+          .optional()
+          .describe(
+            "Where the mind's sign-in, API and MCP server answer: the domain itself, or one label under it (default: iterate.<domain>; for a mind that is there already: the one it has)",
+          ),
+        egressGateway: z
+          .string()
+          .optional()
+          .describe(
+            "The stack's egress gateway: a Worker of the account, by name, that carries what the mind's itx.fetch sends out of the stack, each request with its secret in. It is trusted as the vault is. `none` takes it away (default: none; for a mind that is there already: what it has)",
+          ),
+        mailForwardTo: z
+          .string()
+          .optional()
+          .describe(
+            "Forward each mail to the mind there as it arrived, a verified destination address of the account's Email Routing; none stops it (default: none; for a mind that is there already: the one it has)",
+          ),
+        kernelRepo: z
+          .string()
+          .optional()
+          .describe(
+            "For a new mind: the https address of the kernel repo (default: https://git.iterate.com/repos/kernel, or none with --source). The deploy builds it, and the mind clones it at birth as its own /repos/kernel. Refused over a mind that is there, whose own /repos/kernel is what a deploy builds",
+          ),
+        configRepo: z
+          .string()
+          .optional()
+          .describe(
+            "For a new mind: the https address of the repo that its config starts as (default: https://git.iterate.com/repos/config-template). The mind clones it at birth as its own /repos/config, and the repos that its package.json names from beside it. none starts the mind with empty repos, which get their code by pushes. Refused over a mind that is there",
+          ),
+        zones: z
+          .string()
+          .optional()
+          .describe(
+            "The mind's whole list of domains, each a zone of the account, a comma between two, the mind's first domain first. The mind takes each whole: its hostnames and its mail, with an Email Sending domain that is there already. A domain that leaves the list loses its records, routes and mail (default: the domain; for a mind that is there already: the ones it has)",
+          ),
+        traceSampling: z
+          .string()
+          .optional()
+          .describe(
+            "The share of requests whose trace Cloudflare keeps, from 0 to 1, for every Worker of the mind; default keeps every one (default: 1; for a mind that is there already: the one it has)",
+          ),
+        buy: z
+          .boolean()
+          .optional()
+          .describe("Buy the domain at Cloudflare's price without a question"),
+        yes: z
+          .boolean()
+          .optional()
+          .describe(
+            "Answer yes to the other questions: a domain you bring, a deploy over a mind that is there already",
+          ),
+        eraseRecords: z
+          .boolean()
+          .optional()
+          .describe(
+            "A domain of the account that is in use: erase every DNS record and Workers route on it without a question",
+          ),
+        source: z
+          .string()
+          .optional()
+          .describe(
+            "A checkout of iterate's kernel on this computer to deploy, whatever it holds, over any mind (default: none; a new mind's kernel is the repo that --kernel-repo names, iterate's own with no flag, and a mind that is there builds its own /repos/kernel)",
+          ),
+        ref: z
+          .string()
+          .optional()
+          .describe("A branch of the kernel repo to deploy (default: main)"),
+        plan: z
+          .boolean()
+          .optional()
+          .describe(
+            "Change nothing: over a mind that is there already, write the stack's plan (Alchemy's, of each resource: noop, update, create, delete) to plan.log beside the deploy's config, with the same sign-in, source and config as a deploy",
+          ),
+        setup: z
+          .boolean()
+          .default(true)
+          .meta({ negatable: true })
+          .describe(
+            "With a person at the terminal, after the deploy: wait for Enter and open https://onboarding.<zone>/ in the browser to continue setup",
+          ),
+        signIn: z
+          .boolean()
+          .default(true)
+          .meta({ negatable: true })
+          .describe(
+            "After the deploy, sign this computer in to the mind on the way to setup, so iterate commands reach it (a new owner adds their first passkey on the way)",
+          ),
+        mcp: z
+          .string()
+          .optional()
+          .describe(
+            "The coding agents on this computer that get the mind's MCP server: claude, codex, grok, agy with a comma between, all (those found) or none (default: with a person there, a question on a first deploy; else none)",
+          ),
+      }),
+    )
+    .meta({
+      description:
+        "Deploy a mind into your own Cloudflare account, at its own domain: sign in at Cloudflare, choose the account and the domain, and the stack is deployed from this computer. A mind that is there already is deployed over, with its own config",
+    })
+    .handler(async ({ input }) => deployMind(input)),
+  recover: os
+    .input(
+      z.object({
+        domain: z.string().describe("A domain of the mind"),
+        account: z.string().optional().describe("The Cloudflare account, by id"),
+        owner: z.string().describe("The email address of the owner who has no passkey left"),
+        yes: z.boolean().optional().describe("Revoke and make the link without a question"),
+      }),
+    )
+    .meta({
+      description:
+        "For an owner with no passkey left, run by whoever holds the mind's Cloudflare account: sign in at Cloudflare, revoke that owner's passkeys, and print a link that signs the owner in once to add a new one",
+    })
+    .handler(async ({ input }) => recoverOwner(input)),
+  // A KEPT SIGN-IN AT CLOUDFLARE (cloudflare-access.ts): `iterate deploy` with nobody at
+  // Cloudflare's page, by the same sign-in as a person's. The sign-in goes to a file or to a secret
+  // store through a pipe, never through a flag's value, which stays in the shell's history.
+  cloudflare: {
+    signIn: os
+      .input(
+        z.object({
+          file: z.string().optional().describe("Keep the sign-in in this new file, mode 600"),
+          print: z
+            .boolean()
+            .optional()
+            .describe(
+              "Print the sign-in as one JSON document on standard output, for a pipe into a secret store (e.g. | doppler secrets set NAME > /dev/null, since doppler prints the value it sets); the page and the code go to standard error",
+            ),
+        }),
+      )
+      .meta({
+        description: `Sign in at Cloudflare for \`iterate deploy\` with nobody at Cloudflare's page: the deploy's scopes and offline_access. A deploy uses it with ${SIGN_IN_FILE}=<file>, and rewrites the file at each renewal`,
+      })
+      .handler(async ({ input }) => {
+        if (Boolean(input.file) === Boolean(input.print))
+          throw new Error("Say where the sign-in goes: --file <path>, or --print.");
+        if (input.print && process.stdout.isTTY)
+          throw new Error(
+            "--print writes the sign-in's tokens to standard output: pipe it into a secret store, or use --file.",
+          );
+        if (input.file && existsSync(input.file))
+          throw new Error(
+            `${input.file} is there already. Sign out of the sign-in in it first (iterate cloudflare sign-out --file ${input.file}), or choose another path.`,
+          );
+        const kept = await keptSignInOf(({ url, code, minutes }) =>
+          console.error(
+            `Open this page, check that it shows the code ${code}, select ONLY the mind's account, and approve. The code works for ${minutes} minutes.\n\n  ${url.href}\n`,
+          ),
+        );
+        if (!input.file) {
+          process.stdout.write(`${JSON.stringify(kept)}\n`);
+          return;
+        }
+        try {
+          writeKeptSignIn(input.file, kept);
+        } catch (error) {
+          // a grant that nobody holds is ended
+          await endKeptSignIn(kept);
+          throw new Error(
+            `The sign-in could not be written to ${input.file} (${error instanceof Error ? error.message : String(error)}), so it is revoked. Run the command again.`,
+          );
+        }
+        return {
+          message: `Kept in ${input.file} (mode 600). Deploy with ${SIGN_IN_FILE}=${input.file}. End it with iterate cloudflare sign-out --file ${input.file}.`,
+        };
+      }),
+    signOut: os
+      .input(
+        z.object({
+          file: z
+            .string()
+            .optional()
+            .describe(
+              "The file of the sign-in, deleted after the revocation (default: the sign-in's JSON on standard input)",
+            ),
+        }),
+      )
+      .meta({
+        description:
+          "Revoke a kept sign-in at Cloudflare (iterate cloudflare sign-in), and delete its file. A secret store's copy is yours to delete",
+      })
+      .handler(async ({ input }) => {
+        if (!input.file && process.stdin.isTTY)
+          throw new Error("Name the sign-in: --file <path>, or its JSON on standard input.");
+        // a deploy that renews the sign-in while it is revoked would keep a live one in the file
+        if (input.file) lockKept(input.file);
+        const text = input.file
+          ? readFileSync(input.file, "utf8")
+          : await streamText(process.stdin);
+        const kept = parsed(KeptSignIn, text);
+        if (!kept)
+          throw new Error(
+            `${input.file || "Standard input"} holds no sign-in of iterate cloudflare sign-in.`,
+          );
+        // read before the revocation, while the access works: these tokens outlive it
+        const made = await tokensMadeThrough(kept).catch(() => undefined);
+        const refused = await endKeptSignIn(kept);
+        if (refused.length > 0)
+          throw new Error(
+            `Cloudflare did not take the revocation (${refused.join("; ")}). Nothing is deleted. Run the command again.`,
+          );
+        if (input.file) rmSync(input.file, { force: true });
+        const tokens = made
+          ? made.length > 0
+            ? `The API tokens that deploys made stay until you delete them: ${made.map((found) => `${found.tokens.join(", ")} in ${found.account} (${found.page})`).join("; ")}. Deleting them turns off the mind's telemetry until its next deploy.`
+            : "Deploys made no API token in the accounts that it reached."
+          : "Its access had ended, so the API tokens that deploys made were not listed: look for iterate-<stage>-telemetry-catalog and -analytics on each account's API tokens page. They stay until you delete them.";
+        return {
+          message: `Revoked at Cloudflare${input.file ? `, and ${input.file} is deleted` : ""}. ${tokens}`,
+        };
+      }),
+  },
+  identity: {
+    show: os
+      .input(z.object({ mind: mindArgument }))
+      .meta({
+        description:
+          "The mind's id, the hostnames of its last identity record, how many records are on this computer and how many of them the mind publishes, and where its identity key is",
+      })
+      .handler(async ({ input }) => shownIdentity(await identityAddressOf(input.mind), identityIo)),
+    post: os
+      .input(z.object({ mind: mindArgument }))
+      .meta({
+        description:
+          "Post the identity records on this computer that the mind does not publish yet, and the last one again, which makes the mind's stack deliver what it still owes its own log. Then, with the identity key on this computer, sign and post the record that lists the stack's key, when no record lists it yet: until then the mind signs nothing as itself. `iterate deploy` does this itself; this is for a post that failed",
+      })
+      .handler(async ({ input }) => {
+        const address = await identityAddressOf(input.mind);
+        const done = await postIdentity({ controlPlaneHostname: address }, identityIo);
+        if (!done)
+          return {
+            message: `This computer holds no identity records of the mind at ${address}: the computer that first deployed it does.`,
+          };
+        const { mindId: mind, taken, here, published } = done;
+        if (published === undefined)
+          return {
+            mind,
+            message:
+              "The mind publishes a record that is not on this computer, so nothing here continues its log. Nothing was posted.",
+          };
+        return {
+          mind,
+          message: [
+            taken
+              ? `The mind took ${taken} of the ${here} records on this computer.`
+              : `The mind had the ${here} records on this computer, and took the last one again.`,
+            published === here
+              ? "Its published log shows them all."
+              : `Its published log shows ${published} of them.`,
+          ].join(" "),
+        };
+      }),
+  },
+  git: {
+    setup: os
+      .input(
+        z.object({
+          host: z
+            .string()
+            .meta({ positional: true })
+            .describe("The host that serves the mind's repos, e.g. git.example.com"),
+          mind: z
+            .string()
+            .optional()
+            .describe("The mind's address (default: the host without its first label)"),
+        }),
+      )
+      .meta({
+        description:
+          "Let plain git clone, pull and push at a mind's git host with this computer's sign-in: sign in if needed, and set git's credential helper for that one host",
+      })
+      .handler(async ({ input }) => {
+        const host = gitHostOf(input.host);
+        // in a sandbox of the mind there is nobody to sign in: the helper asks the mind itself
+        const told = process.env.ITERATE_MIND?.trim().toLowerCase() || "";
+        if (!input.mind && ownSandboxOf(process.env, told)) {
+          using connection = await connectMind({ address: told });
+          const mindUrl = await connection.itx.url();
+          if (!isHostOfMind(host, mindUrl))
+            throw new Error(
+              `${host} is no host of this sandbox's mind (${mindUrl}): a sandbox's git is set up for its own mind's host alone.`,
+            );
+          writeGitConfig({ host, helper: gitHelperCommandOf(told), namesRepo: true });
+          return {
+            message: `Git is set up for https://${host} in this sandbox, with no sign-in: it asks ${told} for each repo's token.`,
+          };
+        }
+        const mind = await discoveredMind(addressOf(input.mind || mindOfGitHost(host)));
+        const signedIn =
+          readSession(mindApiUrlOf(mind.address)) || process.env.ITERATE_MIND_TOKEN?.trim()
+            ? undefined
+            : (await login({ address: mind.address })).message;
+        writeGitConfig({ host, helper: gitHelperCommandOf(mind.address) });
+        // one token now, so a host that is not this mind's, or a sign-in that cannot be used for
+        // it, is said here and not at the first clone
+        const said: string[] = [];
+        const credential = await gitCredential({
+          operation: "get",
+          asked: `protocol=https\nhost=${host}\n\n`,
+          address: mind.address,
+          interactive: true,
+          io: { ...gitCredentialIo(mind.address), say: (line) => said.push(line) },
+        });
+        if (!credential.startsWith("username="))
+          throw new Error(
+            `Git's config is written, but no token came for ${host}:\n${said.join("\n")}`,
+          );
+        return {
+          message: `${signedIn ? `${signedIn}. ` : ""}Git is set up for https://${host}. Run your git command again.`,
+        };
+      }),
+  },
+  login: os
+    .input(LoginInput)
+    .meta({ description: "Sign in to a mind and make it the profile's mind" })
+    .handler(async ({ input }) => login({ ...input, address: addressOf(input.address) })),
+  logout: os
+    .input(z.object({ mind: mindOption }))
+    .meta({
+      description:
+        "End this machine's sign-ins to the mind (for its API, and to hand in a mind that runs here) at its issuer, and forget them",
+    })
+    .handler(async ({ input }) => {
+      const address = await resolveMind(input.mind);
+      const ended: string[] = [];
+      for (const resource of [mindApiUrlOf(address), mindProvideConnectResourceOf(address)]) {
+        const session = readSession(resource);
+        if (!session) continue;
+        await revokeSession(session).catch((error: unknown) => {
+          console.error(
+            `Could not end the sign-in at the issuer (${error instanceof Error ? error.message : String(error)}); it is forgotten here.`,
+          );
+        });
+        removeSession(resource);
+        ended.push(resource);
+      }
+      return { message: ended.length ? `Signed out of ${address}` : `Not signed in to ${address}` };
+    }),
+  whoami: os
+    .input(z.object({ mind: mindOption }))
+    .meta({ description: "Who the mind says you are, and where" })
+    .handler(async ({ input }) => {
+      using connection = await connect(await resolveMind(input.mind));
+      return { mind: connection.address, ...(await connection.itx.whoami()) };
+    }),
+  repl: os
+    .input(
+      z.object({
+        mind: mindOption,
+        context: z.string().default("/").describe("Context path within the mind"),
+      }),
+    )
+    .meta({ description: "Open a local Node REPL with itx and RpcTarget in scope" })
+    .handler(async ({ input }) => {
+      using connection = await connect(await resolveMind(input.mind));
+      using context = await connection.itx.cd(input.context);
+      console.error(
+        `Connected to ${connection.address}, context ${input.context}. Use .exit to quit.`,
+      );
+      // capnweb identifies built-ins by prototype. Evaluate in this process's
+      // realm so objects and argument arrays use the transport's constructors.
+      const server = repl.start({ prompt: "itx> ", useGlobal: true });
+      const initialize = () => {
+        server.context.itx = context;
+        server.context.RpcTarget = RpcTarget;
+      };
+      initialize();
+      server.on("reset", initialize);
+      try {
+        const outcome = await Promise.race([
+          new Promise<"exit">((resolve) => server.once("exit", () => resolve("exit"))),
+          connection.closed,
+        ]);
+        if (outcome !== "exit") {
+          throw new Error(
+            `REPL disconnected (${outcome.code}: ${outcome.reason || "connection closed"}). Start a new REPL to reconnect.`,
+          );
+        }
+      } finally {
+        server.close();
+      }
+    }),
+  itx: {
+    run: os
+      .input(
+        z
+          .object({
+            mind: mindOption,
+            context: z.string().default("/").describe("Context path within the mind"),
+            eval: z
+              .string()
+              .optional()
+              .describe("Script body with itx in scope; use return for the result"),
+            file: z
+              .string()
+              .optional()
+              .describe("Read the script from a UTF-8 file; - reads stdin"),
+          })
+          .refine(
+            (input) => Boolean(input.eval) !== Boolean(input.file),
+            "Specify exactly one of --eval or --file",
+          ),
+      )
+      .meta({ description: "Run an itx script once in the mind" })
+      .handler(async ({ input }) => {
+        let script = input.eval;
+        if (input.file === "-") {
+          const chunks: Buffer[] = [];
+          for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
+          script = Buffer.concat(chunks).toString("utf8");
+        } else if (input.file) script = await readFile(input.file, "utf8");
+        using connection = await connect(await resolveMind(input.mind));
+        using context = await connection.itx.cd(input.context);
+        return await context.run(`async (itx) => {\n${script}\n}`);
+      }),
+  },
+  mcp: {
+    claude: mcpCommand("claude"),
+    codex: mcpCommand("codex"),
+    grok: mcpCommand("grok"),
+    agy: mcpCommand("agy"),
+  },
+  chatgpt: {
+    connect: os
+      .input(
+        z.object({
+          address: z
+            .string()
+            .optional()
+            .meta({ positional: true })
+            .describe("The mind's address, e.g. example.com (default: the profile's)"),
+          test: z
+            .boolean()
+            .default(true)
+            .meta({ negatable: true })
+            .describe("Send one Responses request on the plan after the sign-in"),
+        }),
+      )
+      .meta({
+        description:
+          "Connect a personal ChatGPT Plus or Pro plan to the mind: sign in with ChatGPT in this computer's browser, on 127.0.0.1:1455; the mind gets the tokens and keeps them",
+      })
+      .handler(async ({ input }) => {
+        const address = await resolveMind(input.address);
+        // a first-time user runs this one command: no sign-in here is `iterate login` first
+        if (!process.env.ITERATE_MIND_TOKEN?.trim() && !readSession(mindApiUrlOf(address)))
+          console.error((await login({ address })).message);
+        using connection = await connect(address);
+        return await connectChatgpt({
+          itx: connection.itx,
+          address: connection.address,
+          test: input.test,
+          print: (line) => console.error(line),
+          openBrowser: (url) => openForSignIn(url, (line) => console.error(line)),
+        });
+      }),
+  },
+  useMyComputer: os
+    .input(
+      z.object({
+        mind: mindOption,
+        name: z
+          .string()
+          .regex(/^[a-zA-Z][a-zA-Z0-9]*$/)
+          .optional()
+          .describe("Computer capability name, e.g. jonasComputer"),
+      }),
+    )
+    .meta({
+      description:
+        "Share this computer with a mind until Ctrl-C: run commands and read and write files (on a Mac, native dialogs and Swift too). The same as `iterate provide` of use-my-computer.ts",
+    })
+    .handler(async ({ input }) => {
+      const address = await resolveMind(input.mind);
+      // shareMyComputer owns the connection from here, and every one `reconnect` opens
+      await shareMyComputer({
+        connection: await connect(address),
+        reconnect: () => connect(address),
+        endsAt: () => signInEndsAt(address),
+        name: input.name,
+      });
+    }),
+  tunnel: os
+    .input(
+      z.object({
+        port: z
+          .number()
+          .int()
+          .min(1)
+          .max(65535)
+          .meta({ positional: true })
+          .describe("The local port to serve, e.g. Vite's 5173"),
+        name: z
+          .string()
+          .optional()
+          .describe(
+            "The tunnel's name: the tunnel is at <name>.<the mind's first zone> (default: a random one)",
+          ),
+        hostname: z
+          .string()
+          .optional()
+          .describe(
+            "Serve on this hostname of the mind instead of the name's, e.g. hello.tunnels.example.com",
+          ),
+        public: z
+          .boolean()
+          .optional()
+          .describe("Anyone may use it (default: signed-in visitors only)"),
+        mind: mindOption,
+      }),
+    )
+    .meta({
+      description: "Serve a local port on a mind host until Ctrl-C, WebSockets included",
+    })
+    .handler(async ({ input }) => {
+      const address = await resolveMind(input.mind);
+      // runTunnel owns the connection from here, and every one `reconnect` opens
+      await runTunnel({
+        connection: await connect(address),
+        reconnect: () => connect(address),
+        port: input.port,
+        tunnelName: input.name,
+        hostname: input.hostname,
+        public: input.public,
+      });
+    }),
+  provide: os
+    .input(
+      z.object({
+        file: z
+          .string()
+          .meta({ positional: true })
+          .describe(
+            "A .ts, .mjs or .js file whose default export, ({ itx }) => ({ someFunction() {} }), answers the functions to lend",
+          ),
+        name: z
+          .string()
+          .optional()
+          .describe(
+            "The capability's name, itx.<name> (default: the file's, whatsapp.ts → whatsapp)",
+          ),
+        key: z
+          .string()
+          .optional()
+          .describe(
+            "A file for this bridge's own key, made on the first run: a member allows it once at the link printed, and the bridge then connects with no sign-in, for as long as the key is allowed",
+          ),
+        paths: z
+          .string()
+          .optional()
+          .describe(
+            "With --key: where the key may also add events, comma-separated, under /integrations/ (e.g. /integrations/whatsapp/)",
+          ),
+        json: z
+          .boolean()
+          .optional()
+          .describe(
+            "Print one JSON object per line on stdout at each change of state (connecting, live, reconnecting, notAllowed, incompatible, stopped), for a program that keeps the lend; the human lines stay on stderr",
+          ),
+        mind: mindOption,
+      }),
+    )
+    .meta({
+      description:
+        "Lend a local file's functions to a mind as itx.<name> until Ctrl-C; the file's folder installs its own dependencies",
+    })
+    .handler(async ({ input }) => {
+      // --json: one state per line on stdout (provide-state.ts), the last one as it ends
+      const report = input.json
+        ? (state: ProvideState) => process.stdout.write(`${JSON.stringify(state)}\n`)
+        : undefined;
+      try {
+        // the file first: a missing dependency is the answer before any sign-in
+        const file = await importProvidedFile(input.file);
+        const name = input.name || nameOfFile(input.file);
+        const address = await resolveMind(input.mind);
+        report?.({ state: "connecting", mind: address, name: `itx.${name}` });
+        await provideWith({ address, file, name, key: input.key, paths: input.paths, report });
+        report?.({ state: "stopped", why: "stopped by Ctrl-C or a signal" });
+      } catch (error) {
+        report?.(finalStateOf(error));
+        throw error;
+      }
+    }),
+  config: {
+    get: os
+      .input(z.object({}))
+      .meta({ default: true, description: "Show the profile in use, its mind and its sign-in" })
+      .handler(async () => {
+        const name = resolveConfigName(process.cwd());
+        const config = readConfig(name);
+        if (config instanceof Error) return { configPath: CONFIG_PATH, error: config.message };
+        const session = config.mind ? readSession(mindApiUrlOf(config.mind)) : null;
+        return {
+          configPath: CONFIG_PATH,
+          profile: name,
+          mind: config.mind,
+          signedIn: session ? { issuer: session.issuer, expiresAt: session.expiresAt } : false,
+        };
+      }),
+    list: os
+      .input(z.object({}))
+      .meta({ description: "List the profiles" })
+      .handler(async () => {
+        const configFile = readConfigFile();
+        const current = resolveConfigName(process.cwd());
+        return {
+          profiles: Object.fromEntries(
+            Object.entries(configFile.configs || {}).map(([name, config]) => [
+              name,
+              { mind: config.mind, active: name === current ? true : undefined },
+            ]),
+          ),
+          default: configFile.default,
+        };
+      }),
+    set: os
+      .input(
+        z.object({
+          name: z.string().describe("Profile name"),
+          mind: z.string().optional().describe("The mind's address, e.g. example.com"),
+          setDefault: z.boolean().optional().describe("Make it the default profile"),
+          setWorkspace: z.boolean().optional().describe("Map the current folder to this profile"),
+        }),
+      )
+      .meta({ description: "Create or change a profile" })
+      .handler(async ({ input }) => {
+        const configFile = readConfigFile();
+        configFile.configs ||= {};
+        configFile.configs[input.name] ||= {};
+        if (input.mind) configFile.configs[input.name]!.mind = addressOf(input.mind);
+        if (input.setDefault) configFile.default = input.name;
+        if (input.setWorkspace) {
+          configFile.workspaces ||= {};
+          configFile.workspaces[process.cwd()] = input.name;
+        }
+        writeConfigFile(configFile);
+        return { configPath: CONFIG_PATH, profile: configFile.configs[input.name] };
+      }),
+    use: os
+      .input(
+        z.object({
+          name: z.string().meta({ positional: true }).describe("Profile to make the default"),
+        }),
+      )
+      .meta({ description: "Set the default profile" })
+      .handler(async ({ input }) => {
+        const configFile = readConfigFile();
+        if (input.name !== DEFAULT_CONFIG_NAME && !configFile.configs?.[input.name])
+          throw new Error(`Profile "${input.name}" not found.`);
+        configFile.default = input.name;
+        writeConfigFile(configFile);
+        return { default: input.name };
+      }),
+  },
+};
+
+const PackageVersion = z.object({ version: z.string().min(1) });
+
+/** Reads this CLI package's `version` from the nearest `package.json` above `fromUrl`
+ *  (works identically from `src/cli/cli.ts` and the built `dist/cli.mjs`). */
+export function packageVersionOf(fromUrl: string = import.meta.url): string {
+  for (let dir = dirname(fileURLToPath(fromUrl)); ; dir = dirname(dir)) {
+    const manifest = join(dir, "package.json");
+    if (existsSync(manifest)) {
+      const parsed = PackageVersion.safeParse(JSON.parse(readFileSync(manifest, "utf8")));
+      if (parsed.success) return parsed.data.version;
+    }
+    const parent = dirname(dir);
+    if (parent === dir) return "0.0.0";
+  }
+}
+
+export const runCli = async () => {
+  // the machine's own files, no sign-in and no flags of ours (fs.ts); a sandbox runs the same file alone
+  if (process.argv[2] === "fs") {
+    process.exitCode = await runFs(process.argv.slice(3), process);
+    return;
+  }
+  // git's own helper (git.ts): git reads its stdout, so no flag of ours and no logger
+  if (process.argv[2] === "git-credential") {
+    process.exitCode = await runGitCredential(process.argv.slice(3));
+    return;
+  }
+  configFlagOverride = consumeCliStringFlag("--config");
+  process.argv.splice(2, Infinity, ...loginArgvOf(process.argv.slice(2)));
+  if (process.argv.length === 2) process.argv.push("--help");
+  if (process.argv.length === 3 && process.argv[2] === "-v") process.argv[2] = "--version";
+  const cli = createCli({
+    router: launcherProcedures,
+    name: "iterate",
+    version: packageVersionOf(),
+    description:
+      "The iterate CLI: sign in to a mind by its address, run itx scripts in it, and lend it what runs on this machine.",
+  });
+  // trpc-cli's built-in prompts ask for a missing input, but only a person at a terminal
+  await cli.run({
+    prompts: !isAgent && process.stdin.isTTY && process.stdout.isTTY,
+    logger: yamlTableConsoleLogger,
+  });
+};
+
+/** POSIX-shell-quoted: plain words bare, anything else single-quoted with `'` spelled `'\''`. */
+export const shellCommand = (argv: string[]) =>
+  argv
+    .map((arg) => (/^[\w./:@%+=,-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", `'\\''`)}'`))
+    .join(" ");
A core/lib/src/cli/cloudflare-access.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/cloudflare-access.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/coding-agent.ts
@@ -0,0 +1,20 @@
+/**
+ * Whether a coding agent, not a person, is running this process. The one list of agent markers for
+ * the iterate CLI (no browser opens, no prompts) and .husky/prepare-commit-msg (no
+ * `git commit --amend`). The hook loads this file with Node's own type stripping, so it stays
+ * import-free erasable TypeScript.
+ *
+ * - Claude Code sets CLAUDE_CODE_CHILD_SESSION=1 in the processes its tool calls and hooks spawn.
+ *   Not CLAUDECODE: Claude Code's IDE extensions also set that in the integrated terminal a person
+ *   types into. https://code.claude.com/docs/en/env-vars
+ * - OpenCode sets OPENCODE=1 and OPENCODE_SESSION.
+ * - AGENT=1 is the generic marker for other agents.
+ */
+export function isCodingAgent(env: Record<string, string | undefined>) {
+  return (
+    env.CLAUDE_CODE_CHILD_SESSION === "1" ||
+    env.OPENCODE === "1" ||
+    Boolean(env.OPENCODE_SESSION) ||
+    env.AGENT === "1"
+  );
+}
A core/lib/src/cli/config.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/deploy.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/deploy.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/device-login/flow.test.ts
@@ -0,0 +1,72 @@
+import { expect, test } from "vitest";
+import { loginFlowFor, unexpectedUser, type LoginFlow } from "./flow.ts";
+
+test.for<{
+  name: string;
+  device?: boolean;
+  env: Record<string, string>;
+  platform: string;
+  flow: LoginFlow;
+}>([
+  { name: "a Mac desktop", env: {}, platform: "darwin", flow: "browser" },
+  {
+    name: "a Linux desktop",
+    env: { WAYLAND_DISPLAY: "wayland-1" },
+    platform: "linux",
+    flow: "browser",
+  },
+  { name: "Linux with no display server", env: {}, platform: "linux", flow: "device" },
+  {
+    name: "a shell over SSH, even with a forwarded display",
+    env: { SSH_CONNECTION: "203.0.113.7 50000 192.0.2.1 22", DISPLAY: "localhost:10.0" },
+    platform: "linux",
+    flow: "device",
+  },
+  { name: "a coding agent on a Mac", env: { AGENT: "1" }, platform: "darwin", flow: "device" },
+  {
+    name: "ITERATE_LOGIN_FLOW=browser over SSH",
+    env: { ITERATE_LOGIN_FLOW: "browser", SSH_CONNECTION: "203.0.113.7 50000 192.0.2.1 22" },
+    platform: "linux",
+    flow: "browser",
+  },
+  {
+    name: "--device over ITERATE_LOGIN_FLOW",
+    device: true,
+    env: { ITERATE_LOGIN_FLOW: "browser" },
+    platform: "darwin",
+    flow: "device",
+  },
+  {
+    name: "--device false on a headless Linux",
+    device: false,
+    env: {},
+    platform: "linux",
+    flow: "browser",
+  },
+])("$name signs in with the $flow flow", ({ device, env, platform, flow }) => {
+  expect(loginFlowFor({ device, env, platform })).toBe(flow);
+});
+
+test.for<{ name: string; signedInAs?: string; expected?: string; refusal: string | null }>([
+  { name: "no expectation", signedInAs: "a@example.com", refusal: null },
+  {
+    name: "the expected person, typed in another case",
+    signedInAs: "a@example.com",
+    expected: " A@Example.com ",
+    refusal: null,
+  },
+  {
+    name: "someone else",
+    signedInAs: "b@example.com",
+    expected: "a@example.com",
+    refusal: "This sign-in is b@example.com, not a@example.com. It was ended and not saved.",
+  },
+  {
+    name: "an account with no email",
+    expected: "a@example.com",
+    refusal:
+      "This sign-in is an account with no email, not a@example.com. It was ended and not saved.",
+  },
+])("the expected user: $name", ({ signedInAs, expected, refusal }) => {
+  expect(unexpectedUser(signedInAs, expected)).toBe(refusal);
+});
A core/lib/src/cli/device-login/flow.ts
@@ -0,0 +1,31 @@
+import { isCodingAgent } from "../coding-agent.ts";
+
+/** `browser`: the loopback login (oauth.ts `oauthLogin`); `device`: index.ts `deviceLogin`. */
+export type LoginFlow = "browser" | "device";
+
+/** The flow for this process (README "Login without a browser"). A coding agent gets the device
+ *  flow because the person who opens its printed URL may be on another machine, where a redirect
+ *  to this machine's localhost fails. A TTY says nothing: an agent has none, even on a laptop. */
+export function loginFlowFor(input: {
+  device?: boolean;
+  env: Record<string, string | undefined>;
+  platform: string;
+}): LoginFlow {
+  if (input.device !== undefined) return input.device ? "device" : "browser";
+  const { env } = input;
+  if (env.ITERATE_LOGIN_FLOW === "browser" || env.ITERATE_LOGIN_FLOW === "device")
+    return env.ITERATE_LOGIN_FLOW;
+  if (env.SSH_CONNECTION) return "device";
+  if (input.platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return "device";
+  if (isCodingAgent(env)) return "device";
+  return "browser";
+}
+
+/** Why a new session must not be kept, or null: it signed in someone else than `expected`
+ *  (`--expect-user`). Emails compare as the platform stores them: trimmed and lower-cased. */
+export function unexpectedUser(signedInAs: string | undefined, expected: string | undefined) {
+  if (!expected) return null;
+  const normalize = (email: string) => email.trim().toLowerCase();
+  if (signedInAs && normalize(signedInAs) === normalize(expected)) return null;
+  return `This sign-in is ${signedInAs || "an account with no email"}, not ${expected}. It was ended and not saved.`;
+}
A core/lib/src/cli/device-login/index.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/device-login/poll.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/device-login/poll.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/device-login/qr.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/device-login/qr.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/fs.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/fs.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/git.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/git.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/identity.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/identity.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/mcp-clients.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/mcp-clients.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/oauth.test.ts
@@ -0,0 +1,36 @@
+import { expect, test } from "vitest";
+import { listenForRedirect } from "./oauth.ts";
+
+test("the loopback's /start leads to a long page; the sign-in's own redirect goes on to onboarding", async () => {
+  await using onward = await listenForRedirect();
+  const long =
+    "https://iterate.ada-labs.com/sign-in/access?next=https%3A%2F%2Fiterate.ada-labs.com%2Foauth%2Fauthorize";
+  const start = await fetch(onward.startAt(long), { redirect: "manual" });
+  onward.sendOnward("https://onboarding.ada-labs.com/", "s1");
+  const answer = await fetch(`${onward.redirectUri}?code=abc&state=s1`, { redirect: "manual" });
+  expect({
+    start: [start.status, start.headers.get("location")],
+    status: answer.status,
+    location: answer.headers.get("location"),
+    code: (await onward.redirect).get("code"),
+  }).toEqual({
+    start: [303, long],
+    status: 303,
+    location: "https://onboarding.ada-labs.com/",
+    code: "abc",
+  });
+});
+
+test("a redirect with another state, or a refusal, gets the page and does not go on", async () => {
+  for (const query of ["code=abc&state=other", "error=access_denied&state=s1"]) {
+    await using loopback = await listenForRedirect();
+    loopback.sendOnward("https://onboarding.ada-labs.com/", "s1");
+    const answer = await fetch(`${loopback.redirectUri}?${query}`, { redirect: "manual" });
+    expect({ query, status: answer.status, location: answer.headers.get("location") }).toEqual({
+      query,
+      status: query.startsWith("error") ? 400 : 200,
+      location: null,
+    });
+    await loopback.redirect;
+  }
+});
A core/lib/src/cli/oauth.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/open-page.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/open-page.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/provide-state.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/provide.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/provide.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/recover.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/recover.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/run-command.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/share-my-computer.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/tunnel.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/tunnel.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/use-my-computer.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/zone-protocols.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cli/zone-protocols.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/connected-mind.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/event-log.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/event-log.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/heartbeat.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/live-state.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/live-state.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/new-version.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/new-version.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/oauth.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/oauth.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/react.tsx

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/socket.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/client/socket.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/cloudflare-read-scopes.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/compatibility-date.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/dash-routes.fixture.json

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/email.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/expression.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/expression.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/facts.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/facts.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/integrations.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/integrations.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/lib.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/lib.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-api.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-api.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-config.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-config.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-identity-log.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-identity-log.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-identity.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-identity.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/mind-ingress.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/node-renewal.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/node.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/node.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/oauth-scopes.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/oauth-scopes.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/package-builds.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/package-builds.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/platform-retry.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/platform-retry.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/principal.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/principal.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/released-answer.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/auth.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/auth.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/call-with-cause.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/code-failed.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/cut.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/direct-append.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/direct-append.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/files.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/index.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/index.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/itx-scope.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/itx-scope.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/loaded-worker.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/loaded-worker.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sdk/mcp.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/secret-placeholder.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/secret-placeholder.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/signed.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/signed.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sshsig.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/sshsig.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/standalone-page.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/standalone-page.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/stream/contract.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/stream/processor-rules.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/stream/processor.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/stream/processor.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/stream/run.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/stream/test-support.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/test-support/cloudflare-workers-shim.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/test-support/identity-log.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/test-support/ssh-signer.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/theme/plain-page-css.gen.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/theme/plain-page.css

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/theme/theme.css

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/theme/tokens.css

Not shown: the change is larger than this page shows. A clone has it.

A core/lib/src/workers.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/acts-gate.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/acts-gate.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/acts-page.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/acts-page.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/approval.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/approval.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/approvals-index.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/approvals-page.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/approvals-page.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/body-placement.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/body-placement.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/callback-page.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/callback-page.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/cloud-client.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/cloud-client.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/config.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/config.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/env.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/grant-ceiling.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/grant-refresh.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/grant-refresh.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/http.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/markdown.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/markdown.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/objects.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/rpc.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-at-rest.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-collect.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-collect.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-list.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-list.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-oauth-callback.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-oauth-callback.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-oauth-resource.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-oauth-start.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-oauth-start.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret-oauth.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/body-placement.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/by-proxy.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/contract.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/durable-object.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/durable-object.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/exchange-jail.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/key-ops.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/refusals.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/refusals.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secret/signing-key.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secrets.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/secrets.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/stack-secrets.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/stack-secrets.ts

Not shown: the change is larger than this page shows. A clone has it.

A core/secrets-worker/src/worker.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/README.md

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/package.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/ai-target.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/auth.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/cloud-ai.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/connect.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/ledger.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/openai-voice.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/usage.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/src/worker.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/tsconfig.json
@@ -0,0 +1,7 @@
+{
+  "extends": "../../tsconfig.base.json",
+  "compilerOptions": {
+    "types": ["@cloudflare/workers-types", "node"]
+  },
+  "include": ["src", "vitest.config.ts"]
+}
A internal-packages/cloud-ai/vitest.config.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-ai/wrangler.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/README.md

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/dev/fake-x/worker.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/dev/fake-x/wrangler.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/package.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/scripts/bot-link.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/scripts/dev-petshop.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/scripts/production-clients.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/scripts/synthetic-delivery.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/bot.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/keys.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/post-subscriptions.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/secrets-compat.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/signed.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/test-workers.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/worker.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/src/worker.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/tsconfig.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/vitest.config.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/cloud-clients/wrangler.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/.dev.vars.example

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/package.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/scripts/deploy.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/authorization-server.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/authorization-server.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/calendar-push.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/capnweb.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/cloudflare.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/durable-object.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/gateway.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/github-app.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/github.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/gmail-push.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/google-calendar.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/google-records.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/google.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/graphql-login.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/mcp-app.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/mcp.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/mcp.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/memory-state.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/oauth-provider.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/oidc.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/openapi.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/pet-events.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/pet-events.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/pet-stream.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/pets.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/seal.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/seal.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/shop-day.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/shop-day.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/slack.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/state.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/state.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/tesco-login.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/test-controls.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/test-controls.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/walk-in.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/webhook-inbox.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/webhook-inbox.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/worker.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/src/x.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/tsconfig.json
@@ -0,0 +1,4 @@
+{
+  "extends": "../../tsconfig.app.json",
+  "include": ["**/*.ts"]
+}
A internal-packages/dummy-petshop/vite.config.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/dummy-petshop/vitest.config.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/.gitignore
@@ -0,0 +1,1 @@
+test/out
A internal-packages/installer/README.md

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/Dockerfile

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/check-imports.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/check-result.sh

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/erase.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/pack-stack.sh

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/prove-local.sh

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/run.sh

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/container/takeover.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/index.html

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/package.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/pretend/pages.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/pretend/scenarios.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/pretend/worker.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/pretend/world.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/pretend/wrangler.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/public/iterate-logo.svg

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/scripts/deploy-prd.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/CloudNav.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/ConnectedPage.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/Deployments.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/ErasePage.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/Wizard.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/analytics.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/api.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/connected.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/deploy-steps.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/erase.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/main.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/parts.tsx

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/phone.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/styles.css

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/update-consent.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/src/your-deployments.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/access.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/account-name.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/deploy-prd.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/deploy-steps.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/deployments.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/domain-names.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/fake-cloudflare.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/flow.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/give-up.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/imports.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/installations.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/mcp-relay-proof.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/mcp-relay.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/pages.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/platform-host.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/proof-worker/prove-enrol.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/proof-worker/prove.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/proof-worker/redeploy.sh

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/proof-worker/worker.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/proof-worker/wrangler.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/prove-mind.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/records-free.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/routes.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/run-log.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/same-origin.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/scopes.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/service.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/stack-config.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/takeover.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/ticket-asker.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/update-consent.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/test/update-guard.mjs

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/tsconfig.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/tsconfig.worker.json

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/vite.config.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/access.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/account-name.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/cloudflare-access.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/deploy-run.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/deployments.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/domain-names.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/first-owner.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/globals.d.ts

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/index.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/installation-pages.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/installation-pretend.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/installation.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/main.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/mcp-relay.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/pretend-deployer.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/pretend-main.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/pretend-run.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/run-log.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/scopes.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/service.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/stack-commits.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/worker/stack-config.js

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/wrangler.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/wrangler.mcp-relay.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A internal-packages/installer/wrangler.pretend.jsonc

Not shown: the change is larger than this page shows. A clone has it.

A package.json

Not shown: the change is larger than this page shows. A clone has it.

A patches/@cloudflare__workers-oauth-provider@1.2.4.patch

Not shown: the change is larger than this page shows. A clone has it.

A patches/zod@4.6.5.patch

Not shown: the change is larger than this page shows. A clone has it.

A pnpm-lock.yaml

Not shown: the change is larger than this page shows. A clone has it.

A pnpm-workspace.yaml

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/README.md

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/RULES.md

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/ask-agent.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/base-rules.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/cloudflare-routes.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/fake-cloudflare.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/fake-cloudflare.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/install.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/mind-app/backend.ts.txt

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/mind-app/mind.ts.txt

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/rules.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/serve.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/start.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/cloud-rehearsal/stop.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/zone-enrollment/README.md

Not shown: the change is larger than this page shows. A clone has it.

A scripts/zone-enrollment/fake-cloudflare.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/zone-enrollment/fixture.run.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/zone-enrollment/only-the-fake.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/zone-enrollment/zone-enrollment.test.ts

Not shown: the change is larger than this page shows. A clone has it.

A scripts/zone-enrollment/zone-resources.ts

Not shown: the change is larger than this page shows. A clone has it.

A tsconfig.app.json

Not shown: the change is larger than this page shows. A clone has it.

A tsconfig.base.json

Not shown: the change is larger than this page shows. A clone has it.