Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c4915f5ad | ||
|
|
76ec2c0019 | ||
|
|
9a15fb2a86 | ||
|
|
0116ccd0d2 | ||
|
|
992e871c56 | ||
|
|
9cfc150f2c | ||
|
|
857816166e | ||
|
|
9c3eaa9819 | ||
|
|
cbb59ad3bc | ||
|
|
ef2d71bfc3 | ||
|
|
85f91a9da1 | ||
|
|
c1c7a10f9b | ||
|
|
a550a6aa34 | ||
|
|
5fa4d2800f | ||
|
|
7cd6d0af01 | ||
|
|
1fb01b3d55 |
No files matched your search
@@ -10,3 +10,4 @@ dist/
|
||||
worker-configuration.d.ts
|
||||
emdash-env.d.ts# diigo exports: personal data
|
||||
export/
|
||||
result
|
||||
+12
-8
@@ -89,6 +89,12 @@ narrative.
|
||||
[the issues sketch](potluck/issues-sketch.md))? If the policy
|
||||
changes, stripping stored rows is a durable-state migration.
|
||||
|
||||
- [ ] **1h. Align the UX with the RPC interface: every action findable, under the authority it needs.** Map and misalignments: [the UX map](capsite-notes.md#diigo-cache-ux-map-2026-10-07). First use on bldbox (2026-10-14) found search but no way there.
|
||||
- [ ] 1h-i. Home links each public page in the username index.
|
||||
- [ ] 1h-ii. The webkey page links its public companion's page.
|
||||
- [ ] 1h-iii. Search private bookmarks from the webkey page: the 1d filters over the private cache's `items`, by RPC held by the cache key.
|
||||
- [ ] 1h-iv. Publish and dump move from HTTP form routes to the webkey page's RPC.
|
||||
|
||||
- [ ] **2. potluck reads the public cache**: public data, so no capability, no cookie, no secret on potluck's side. The [diigo-week](diigo-week/README.md) plugin reads `GET /public/dckc-madmode?in=<week>&by=created` as microformats (an `h-feed` of `h-entry` bookmarks). Working in dev 2026-10-09; 2-iii postponed.
|
||||
- [x] 2-i. Transport: the `DIIGO_CACHE` service binding in potluck's `wrangler.jsonc`, in dev too: the plugin's `ctx.http.fetch` refuses localhost (EmDash's SSRF guard), and a binding names one worker, not a host.
|
||||
- [x] 2-ii. The page's microformats are the contract: diigo-cache's tests parse it with microformats-parser; diigo-week's tests read fixtures in the same markup.
|
||||
@@ -99,14 +105,10 @@ narrative.
|
||||
|
||||
- [ ] **4b. Consider scruffier tags.** EmDash tags are taxonomy terms (rows that must exist before use); diigo-week auto-creates them, so drafting feels scruffy, but the model is neat. Alternative: the inline `/tag/<tag>` links in issue bodies *are* the tags (matching the microformats `p-category` reading), and potluck's `/tag/<tag>` page finds issues by scanning bodies. Cost: no EmDash tag field or index; a scan over a few dozen issues a year is cheap. Open: does the admin's tag field let you type a new tag inline?
|
||||
|
||||
- [ ] **5. Deployed end-to-end** (order matters):
|
||||
- [ ] 5-i. webapp: `cd webapp && npx wrangler deploy`
|
||||
- [ ] 5-ii. diigo-cache: rate-limit `/api` (and `/public/*`) first
|
||||
(diigo-cache CONTRIBUTING, "Deployment concern"); deploy; create
|
||||
against prod (ids → password manager; no worker secret);
|
||||
run the fill job.
|
||||
- [ ] 5-iii. madmode: deploy with the service binding; the
|
||||
weekly page renders against prod.
|
||||
- [ ] **5. Deployed end-to-end**: on bldbox, tailnet only, not Cloudflare: diigo binds the cookie to the IP it was issued to ([operator docs](diigo-cache/doc/README.md)).
|
||||
- [x] 5-i. webapp and diigo-cache in one workerd under systemd, via [the flake](diigo-cache/flake.nix); behind `tailscale serve` at `https://bldbox.tail09e44.ts.net/`. 2026-10-14.
|
||||
- [x] 5-ii. Create against prod: cookie from a browser on bldbox, wired public, filled 168 pages. 2026-10-14. Rate limiting `/api` waits while only the tailnet reaches it ([open issue 4](diigo-cache/doc/open-issues.md)).
|
||||
- [ ] 5-iii. madmode/potluck reads the public page from prod: no service binding off Cloudflare ([open issue 5](diigo-cache/doc/open-issues.md)).
|
||||
- [ ] **6. Cookie expiry**: when diigo's session ends, head refreshes
|
||||
fail; the public page keeps serving what's stored (say so on the
|
||||
page, don't fail silently). Rotation is manual: re-mint via
|
||||
@@ -218,6 +220,8 @@ to every goal in this tree.
|
||||
pattern, abstracted from the E-on-Java sources (bearer secrets,
|
||||
YURL32, secret≠address); the reason ids ride only fragments and POST
|
||||
bodies
|
||||
- [docs/learn-by-watching.md](docs/learn-by-watching.md) — an agent
|
||||
watches me use a site, then writes policy-bounded code for its hidden API
|
||||
- [the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo) —
|
||||
provenance of the fluent client and dump generator (`projects/diigo-bak/`:
|
||||
WebApp.js, diigo-dump.mjs, diigo-interact.mjs; mm-diigo commit 7dbb367,
|
||||
|
||||
@@ -47,6 +47,7 @@ flowchart LR
|
||||
login["/cache/ login<br/>(password manager)"]
|
||||
admin["webkey page<br/>/cache/ + key in fragment"]
|
||||
public["/public/username<br/>(anyone)"]
|
||||
search["/public/username?q=…&in=…<br/>search, date windows"]
|
||||
|
||||
home -->|create| connect
|
||||
connect -->|"POST /_mint (cookie)"| wire
|
||||
@@ -59,8 +60,12 @@ flowchart LR
|
||||
home -->|"dump: POST / (cache id + page)"| home
|
||||
admin -->|"api.cache(key) …"| admin
|
||||
created -->|"link (public mode)"| public
|
||||
public -->|"GET form"| search
|
||||
search -->|"GET form"| search
|
||||
```
|
||||
|
||||
Updated 2026-10-14. There's no edge from home to public: once the created page is gone, you reach your public page only by typing its URL.
|
||||
|
||||
| action | where | transport | authority |
|
||||
|---|---|---|---|
|
||||
| mint the diigo session | `/_connect` | HTTP `POST /_mint` (relays webapp's form) | the cookie |
|
||||
@@ -73,6 +78,9 @@ flowchart LR
|
||||
| …of the public companion | webkey page | RPC `publicCache().…` | cache key |
|
||||
| invalidate the last N days | webkey page | RPC `invalidateRecent(days)` | cache key |
|
||||
| read public bookmarks | `/public/<u>` | HTTP GET (HTML or JSON) ⚠ | none |
|
||||
| search, date windows (1d) | `/public/<u>` | HTTP GET `q`, `days`, `in`, `after`, `before`, `by` | none |
|
||||
| find your public page | — ⚠ | — | none (the username index knows it) |
|
||||
| search private bookmarks | — ⚠ | — | cache key |
|
||||
| bulk dump for another worker | — | service binding `DiigoBridge.dumpNdjson` | worker config |
|
||||
|
||||
⚠ misalignments:
|
||||
@@ -81,6 +89,8 @@ flowchart LR
|
||||
- ~~the public page can write~~ — resolved: it reads only through the
|
||||
read-only `viewer()` facet; unfetched pages say so
|
||||
- the webkey page has no dump or publish; the home page has no fill
|
||||
- (2026-10-14, first use on bldbox) nothing links to `/public/<u>`: home doesn't list the username index, and the webkey page doesn't link its public companion's page
|
||||
- search exists only on the public page; the private cache, which holds every item, has the raw page dump and nothing else. Private search belongs on the webkey page, held by the cache key (an RPC over the same `items` query `viewer()` runs)
|
||||
|
||||
## Native-plugin wiring (the part that took a while)
|
||||
|
||||
|
||||
@@ -69,4 +69,4 @@ Check a filled cache against a diigo RSS export: `node scripts/compare-export.ts
|
||||
|
||||
## Deploy
|
||||
|
||||
Not deployed yet; the order matters (goal 5 in [the capsite checklist](../capsite-checklist.md)): webapp first (`cd ../webapp && npx wrangler deploy`), then diigo-cache, after rate-limiting `/api` (above).
|
||||
On bldbox, tailnet only, via [the flake](flake.nix): see [the operator docs](doc/README.md). Cloudflare is out while diigo binds the cookie to the IP it was issued to ([open issue 1](doc/open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
|
||||
@@ -23,4 +23,4 @@ Then, in the browser:
|
||||
- **Ids are capabilities:** the cache id is a bearer key you keep in your password manager. It rides URL fragments and POST bodies, never a path or query string, so it stays out of logs and history.
|
||||
- **Cheap to read:** pages come from Durable Object SQLite storage, and a fill job in the background fetches each diigo page once.
|
||||
|
||||
Design, tests, and deploying: [CONTRIBUTING](CONTRIBUTING.md).
|
||||
Design and tests: [CONTRIBUTING](CONTRIBUTING.md). Running it on bldbox: [the operator docs](doc/README.md).
|
||||
@@ -0,0 +1,19 @@
|
||||
# Operating diigo-cache on bldbox
|
||||
|
||||
diigo-cache and [webapp](../../webapp/README.md) run together in one workerd on bldbox, reachable only over the tailnet at `https://bldbox.tail09e44.ts.net/`. Cloudflare doesn't work: diigo binds the session cookie to the IP address it was issued to, and Cloudflare's egress IPs aren't that address (see [open issue 1](open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
|
||||
|
||||
```
|
||||
browser on the tailnet
|
||||
→ tailscale serve (HTTPS, bldbox.tail09e44.ts.net:443)
|
||||
→ diigo-cache.socket (127.0.0.1:8790)
|
||||
→ diigo-cache.service: workerd, DynamicUser
|
||||
diigo-cache worker → state in /var/lib/diigo-cache/cache
|
||||
webapp worker → state in /var/lib/diigo-cache/webapp (holds the cookie)
|
||||
→ diigo.com
|
||||
```
|
||||
|
||||
- [Install, upgrade, roll back](install.md)
|
||||
- [Day to day: create a cache, logs, backups](operate.md)
|
||||
- [Open issues](open-issues.md), in IBIS style
|
||||
|
||||
The build is [the flake](../flake.nix): wrangler bundles each worker as `wrangler deploy` would, [gen-config.sh](../nix/gen-config.sh) fills [the workerd config](../nix/config.capnp.in), and the [socket](../nix/diigo-cache.socket) and [service](../nix/diigo-cache.service) units ship in the package. workerd comes from nixpkgs' `wrangler`, which bundles a patched one; nixpkgs has no standalone `workerd`.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Install, upgrade, roll back
|
||||
|
||||
Everything below runs on bldbox. Neither unit has been run under the system manager yet; the flake's smoke check runs the same build under workerd directly.
|
||||
|
||||
## Once: tailnet HTTPS
|
||||
|
||||
In the [Tailscale admin console DNS page](https://login.tailscale.com/admin/dns), enable MagicDNS (on) and **HTTPS Certificates** (off as of 2026-10-14: `tailscale status --json | jq .CertDomains` is `null`). HTTPS matters: the "save to password manager" button uses `PasswordCredential`, which browsers offer only in a secure context.
|
||||
|
||||
## Build and check
|
||||
|
||||
```sh
|
||||
cd ~/oros-bots/capsite/diigo-cache
|
||||
nix flake check # builds, then serves the home page and mints a webapp instance
|
||||
out=$(nix build --no-link --print-out-paths .#)
|
||||
nix/probe-unit.sh "$out" # serves it under the unit's syscall filter: "probe: ok"
|
||||
```
|
||||
|
||||
The probe catches what the smoke check can't: the nix sandbox has no systemd, so it doesn't apply the unit's `SystemCallFilter`. The flake only sees files git tracks: `git add` new files before building.
|
||||
|
||||
## Install
|
||||
|
||||
The service runs whatever `/nix/var/nix/profiles/diigo-cache` points at, so the profile is also the GC root and the rollback history.
|
||||
|
||||
nix-env is spelled out in full because sudo's `secure_path` leaves out nix's profile.
|
||||
|
||||
```sh
|
||||
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
|
||||
sudo systemctl link /nix/var/nix/profiles/diigo-cache/lib/systemd/system/diigo-cache.{socket,service}
|
||||
sudo systemctl enable --now diigo-cache.socket diigo-cache.service
|
||||
sudo tailscale serve --bg --https=443 http://127.0.0.1:8790
|
||||
```
|
||||
|
||||
`tailscale serve --bg` persists across reboots in tailscaled's state; `tailscale serve status` shows it.
|
||||
|
||||
## Verify
|
||||
|
||||
```sh
|
||||
curl -sf https://bldbox.tail09e44.ts.net/ | grep -c _connect # 1+; first request starts workerd
|
||||
systemctl status diigo-cache.service
|
||||
```
|
||||
|
||||
On a 502, make sure `tailscale serve` finds something on 8790: `curl -sI http://127.0.0.1:8790/`. (The cache also answers 502 when it can't load a page from diigo; its body then says `could not load page`.) If workerd crashes on start, systemd stops retrying, then fails the socket too (`Result: service-start-limit-hit` in `systemctl status diigo-cache.socket`). After fixing the cause:
|
||||
|
||||
```sh
|
||||
sudo systemctl reset-failed diigo-cache.socket diigo-cache.service
|
||||
sudo systemctl start diigo-cache.socket
|
||||
```
|
||||
|
||||
From another tailnet device, open `https://bldbox.tail09e44.ts.net/`. From off the tailnet, the name doesn't resolve and `100.89.146.23` doesn't route.
|
||||
|
||||
## Upgrade
|
||||
|
||||
```sh
|
||||
out=$(nix build --no-link --print-out-paths .#)
|
||||
nix/probe-unit.sh "$out"
|
||||
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
|
||||
sudo systemctl daemon-reload # in case the units changed
|
||||
sudo systemctl restart diigo-cache.service
|
||||
```
|
||||
|
||||
Durable Object state outlives the code: an upgrade whose schema change existing state can't read is a breaking change (see [capsite AGENTS.md](../../AGENTS.md#durable-state-be-loud-and-conservative-about-breaking-changes)). Back up first ([operate](operate.md#backups)).
|
||||
|
||||
## Roll back
|
||||
|
||||
```sh
|
||||
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --list-generations
|
||||
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --rollback
|
||||
sudo systemctl restart diigo-cache.service
|
||||
```
|
||||
|
||||
## Update nixpkgs
|
||||
|
||||
`nix flake update` moves wrangler, and with it workerd. The flake names workerd's version (`version` in [flake.nix](../flake.nix)); if nixpkgs' wrangler bundles a different one, the build fails with `no workerd <version>`. Set it to the bundled version, which must be no older than the workers' `compatibility_date`.
|
||||
|
||||
## Remove
|
||||
|
||||
```sh
|
||||
sudo tailscale serve --https=443 off
|
||||
sudo systemctl disable --now diigo-cache.socket diigo-cache.service
|
||||
sudo rm /nix/var/nix/profiles/diigo-cache* # state in /var/lib/private/diigo-cache stays
|
||||
```
|
||||
@@ -0,0 +1,173 @@
|
||||
# Open issues
|
||||
|
||||
In [IBIS](https://github.com/dckc/vattr97/wiki/IBIS) notation: `?` issue, `?!` resolved, `?~` open with a fallback; `:` position, `:+` accepted, `:-` rejected, `:~+` fallback; `+` pro, `-` con; `!` to-do; `.` comment. Append; don't renumber.
|
||||
|
||||
### ?! 1. How does diigo see the cookie come from the IP it was issued to?
|
||||
|
||||
```
|
||||
?! 1. How does diigo see the cookie come from the IP it was issued to?
|
||||
. observed: minted from the browser, the cookie failed from Cloudflare
|
||||
. unverified that IP is the only binding; the mint sends user-agent
|
||||
"Mozilla/5.0", not the browser's, and that works in dev
|
||||
: 1a. log in to diigo from a browser that shares bldbox's public IP
|
||||
(same LAN, same NAT)
|
||||
+ no setup if that's where the browser already is
|
||||
- breaks when the browser roams (phone, laptop away from home)
|
||||
! compare: curl https://ifconfig.me on bldbox and in the browser
|
||||
: 1b. advertise bldbox as a tailnet exit node; route the browser through
|
||||
it while logging in to diigo and copying the cookie
|
||||
+ bldbox's IP by construction, from anywhere on the tailnet
|
||||
- bldbox isn't an exit node (ExitNodeOption false, 2026-10-14);
|
||||
needs `tailscale set --advertise-exit-node` and admin approval
|
||||
:+ 1c. run the browser on bldbox
|
||||
+ worked 2026-10-14: a cookie copied from Brave's devtools on bldbox
|
||||
minted, wired public, and filled 168 pages
|
||||
:- 1d. deploy to Cloudflare
|
||||
- its egress IPs aren't the browser's (the failure that prompted this)
|
||||
```
|
||||
|
||||
### ?~ 2. How is diigo-cache reachable only from the tailnet?
|
||||
|
||||
```
|
||||
?~ 2. How is diigo-cache reachable only from the tailnet?
|
||||
:~+ 2a. workerd on 127.0.0.1:8790; tailscale serve proxies
|
||||
https://bldbox.tail09e44.ts.net/ to it
|
||||
+ HTTPS with a real cert: PasswordCredential needs a secure context
|
||||
+ tailscaled owns the tailnet address; no start-order dependency
|
||||
- needs HTTPS certificates on in the tailnet (off as of 2026-10-14)
|
||||
! enable in the admin console (install.md)
|
||||
- every local user and process on bldbox reaches 127.0.0.1:8790 (see 3)
|
||||
+ the cache id is still needed for anything private
|
||||
: 2b. listen on 100.89.146.23 directly (ListenStream, FreeBind=yes)
|
||||
- plain HTTP: the password-manager button fails
|
||||
: 2c. tailscale serve to a unix socket only it can open
|
||||
+ no loopback port
|
||||
- unverified that tailscale 1.90.9 serve takes a unix socket target
|
||||
? 2d. Which tailnet devices may reach it?
|
||||
. today: every device on the tailnet (m5x, penguin, pixel-7, tiny-jwc)
|
||||
: 2d-i. restrict to some devices with a tailnet ACL grant on bldbox:443
|
||||
```
|
||||
|
||||
### ?~ 3. What account does the service run as?
|
||||
|
||||
```
|
||||
?~ 3. What account does the service run as?
|
||||
:~+ 3a. a system unit with DynamicUser=yes
|
||||
+ the cookie's state is 0700 to a uid nothing else runs as; agents
|
||||
and bots running as connolly can't read it
|
||||
+ full sandboxing (systemd-analyze security: 2.2 OK)
|
||||
- install and upgrade need sudo
|
||||
: 3b. a user unit under connolly, with lingering
|
||||
+ no sudo for upgrade; a ~/.local profile
|
||||
- the cookie sits in connolly's files, readable by every process
|
||||
connolly runs, Discord and opencode bots included
|
||||
- Ubuntu's AppArmor userns restriction weakens user-manager sandboxing
|
||||
- tailscale serve needs root (or `tailscale set --operator`) anyway
|
||||
```
|
||||
|
||||
### ? 4. Does /api need a rate limit on the tailnet?
|
||||
|
||||
```
|
||||
? 4. Does /api need a rate limit on the tailnet?
|
||||
. CONTRIBUTING asks for one "before exposing a deployment"
|
||||
:~+ 4a. not while only tailnet devices reach it (see 2)
|
||||
: 4b. a rate limit in front of workerd before any funnel (see 5)
|
||||
```
|
||||
|
||||
### ? 5. How does the weekly roundup read the public page?
|
||||
|
||||
```
|
||||
? 5. How does the weekly roundup read the public page?
|
||||
. the madmode blog build needs /public/<username>; where does it run?
|
||||
: 5a. build on a tailnet device
|
||||
: 5b. join CI to the tailnet (Tailscale's GitHub Action)
|
||||
: 5c. tailscale funnel just /public/ to the internet
|
||||
+ public pages are public by design
|
||||
- exposes a guessable URL; needs 4b
|
||||
```
|
||||
|
||||
### ? 6. How is state backed up?
|
||||
|
||||
```
|
||||
? 6. How is state backed up?
|
||||
:~+ 6a. by hand, service stopped (operate.md)
|
||||
: 6b. a systemd timer
|
||||
- backups hold the cookie: where do they go, encrypted how?
|
||||
: 6c. none: the cache is a cache
|
||||
- the ids people saved point at objects that would be gone
|
||||
```
|
||||
|
||||
### ? 7. How does a cache get a fresh cookie?
|
||||
|
||||
```
|
||||
? 7. How does a cache get a fresh cookie?
|
||||
. a wired cache refuses a different webapp id
|
||||
:~+ 7a. mint a fresh webapp instance and wire a new cache
|
||||
- a new cache id to save
|
||||
+ wiring public re-registers the username, so the public URL stays
|
||||
: 7b. let webapp replace the cookie in an existing instance
|
||||
+ cache ids stay put
|
||||
```
|
||||
|
||||
### ? 8. Should `wrangler dev` state move to bldbox?
|
||||
|
||||
```
|
||||
? 8. Should `wrangler dev` state move to bldbox?
|
||||
. Durable Object unique keys follow miniflare's `<script>-<class>`,
|
||||
so the per-object files may carry over; untested
|
||||
:~+ 8a. start fresh on bldbox
|
||||
+ dev cookies were minted for wherever dev ran (see 1)
|
||||
: 8b. copy .wrangler/state/v3/do/<script>-<class>/ into the state dirs
|
||||
```
|
||||
|
||||
### ? 9. What should we be able to observe, and how?
|
||||
|
||||
```
|
||||
? 9. What should we be able to observe, and how?
|
||||
. today: each worker console.logs objects ({event, ...}); workerd's
|
||||
structuredLogging puts them in the journal (operate.md)
|
||||
. gap: webapp logs only mint; a diigo request shows up only as the
|
||||
cache's account of it ({event: "cache", outcome: "miss" | "refetch"}),
|
||||
so no status, latency, or failure before the cache sees it
|
||||
. the refresh (every 3h) is seen only by reading the journal
|
||||
! survey practice before choosing: logs vs metrics vs traces, what to
|
||||
alert on; Workers observability docs as a start
|
||||
: 9a. log each diigo request in webapp: path, status, ms; no query
|
||||
values or headers, so the cookie never appears
|
||||
? 9b. how does anyone notice a refresh failing (expired cookie)?
|
||||
```
|
||||
|
||||
### ? 10. Do we need to store diigo page numbers?
|
||||
|
||||
```
|
||||
? 10. Do we need to store diigo page numbers?
|
||||
. pages come from load_user_items with sort=updated, newest first; each
|
||||
new or edited bookmark shifts the rest down one slot, a deletion up one
|
||||
. only page 1 is refetched (every 3h, refetchThrough 1), so pages 2 and
|
||||
on are snapshots from the first fill (2026-10-14)
|
||||
. items are keyed by item_id; page_members records each page's positions
|
||||
. consequences, seen 2026-10-29:
|
||||
. k new bookmarks leave k items on no page: a gap in paged views
|
||||
. an edited bookmark is listed on page 1 and at its stale position
|
||||
. summing logged page items (16,767 private) counts snapshots, not items
|
||||
. a deletion is never noticed; its row stays
|
||||
. week views (?days=, ?in=) query items by date, so they're unaffected
|
||||
: 10a. keep pages as stored snapshots (today)
|
||||
+ read-through: viewing a page not yet filled fetches it
|
||||
- the drift above
|
||||
: 10b. store only items; a page number is just the fill's cursor
|
||||
. each page-table read has a replacement:
|
||||
. refresh depth (deepestPageSince): items updated since the cutoff,
|
||||
/ 100, rounded up, + 1 page of slack for shifts
|
||||
. invalidateRecent: not needed
|
||||
. knownTotal: keep diigo's latest total as one kv value
|
||||
. completeness (pagesThrough): a "full pass done" flag on the fill job
|
||||
. paged public view: items order by updated desc, limit/offset
|
||||
. page dump (HIT/MISS): fetch live; it's a debugging tool
|
||||
+ paged views get no gaps or duplicates
|
||||
+ last_seen per item: after a full pass, items not seen were deleted
|
||||
or made private on diigo
|
||||
+ fetched_at per item says more than pages.etched_at
|
||||
- views past the filled part come back short until the fill gets there
|
||||
- a schema migration
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
# Day to day
|
||||
|
||||
## Create a cache
|
||||
|
||||
As in [the README](../README.md#getting-started), at `https://bldbox.tail09e44.ts.net/` instead of localhost: mint, wire, save the ids, fill. Copy the cookie from a browser running on bldbox: diigo accepts it only from the IP it was issued to (see [issue 1](open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
|
||||
|
||||
The public page is then `https://bldbox.tail09e44.ts.net/public/<diigo username>?days=7`, on the tailnet only.
|
||||
|
||||
## Logs
|
||||
|
||||
```sh
|
||||
journalctl -u diigo-cache.service -f -o cat |
|
||||
jq -Rr 'fromjson? | "\(.timestamp / 1000 | todate) \(.level) \(.message | gsub("\\s*\\n\\s*"; " "))"'
|
||||
```
|
||||
|
||||
`fromjson?` skips lines that aren't JSON: systemd's own ("Started …") and entries from before `structuredLogging`.
|
||||
|
||||
workerd runs with `structuredLogging`: each entry is one line of JSON, `{timestamp, level, message}`. `message` is the logged object as `console.log` prints it, not JSON: on Cloudflare, Workers Logs indexes the fields of a logged object, so the workers log objects rather than strings.
|
||||
|
||||
workerd logs the workers' `console.*` output: `{event: "cache", kind, page, outcome}` per page read, `{event: "fill", state, …}` per fill step (a refresh logs `refetchThrough`), `{event: "mint"}`. Ids show only as fingerprints; the cookie never appears.
|
||||
|
||||
## State
|
||||
|
||||
With `DynamicUser=yes`, systemd keeps the state in `/var/lib/private/diigo-cache/` (`/var/lib/diigo-cache` is a symlink to it), mode 0700, owned by a uid that exists only while the service runs:
|
||||
|
||||
| Dir | Holds | Secret? |
|
||||
| :--- | :--- | :--- |
|
||||
| `cache/diigo-cache-DiigoCache/` | private caches: every bookmark | yes |
|
||||
| `cache/diigo-cache-PublicCache/` | public caches and the username index | no |
|
||||
| `webapp/webapp-WebAppDo/` | webapp instances: the diigo cookie | yes, a credential |
|
||||
|
||||
Each Durable Object is one `<id hash>.sqlite`. Read one with the service stopped, or copy it first: `sudo sqlite3 -readonly <file> .tables`.
|
||||
|
||||
## Backups
|
||||
|
||||
The private caches are refillable from diigo; the cookie can be re-minted. What's lost with the state is the binding from the ids people saved to these objects. Backups hold the cookie, so treat them as secret.
|
||||
|
||||
```sh
|
||||
sudo systemctl stop diigo-cache.socket diigo-cache.service # the socket would restart it
|
||||
sudo tar -C /var/lib/private -czf diigo-cache-$(date +%F).tgz diigo-cache
|
||||
sudo systemctl start diigo-cache.socket
|
||||
```
|
||||
|
||||
No backup is scheduled (see [open issue 6](open-issues.md#-6-how-is-state-backed-up)).
|
||||
|
||||
## The cookie expires
|
||||
|
||||
When fills log `{event: "fill", state: "failed"}` with a diigo auth error, mint a fresh webapp instance and wire a new cache. A wired cache refuses a different webapp id (`setup` in [cache.ts](../src/cache.ts)) (see [open issue 7](open-issues.md#-7-how-does-a-cache-get-a-fresh-cookie)).
|
||||
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1791734076,
|
||||
"narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
description = "diigo-cache and webapp on workerd, outside Cloudflare";
|
||||
|
||||
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
|
||||
outputs =
|
||||
{ self, nixpkgs }:
|
||||
let
|
||||
system = "x86_64-linux";
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
inherit (pkgs) lib;
|
||||
|
||||
# nixpkgs has no workerd of its own; wrangler carries a patched one
|
||||
workerd =
|
||||
pkgs.runCommand "workerd-${version}" { } ''
|
||||
bin=${pkgs.wrangler}/lib/node_modules/.pnpm/@cloudflare+workerd-linux-64@${version}/node_modules/@cloudflare/workerd-linux-64/bin/workerd
|
||||
test -x $bin || { echo "no workerd ${version} in ${pkgs.wrangler}" >&2; exit 1; }
|
||||
mkdir -p $out/bin
|
||||
ln -s $bin $out/bin/workerd
|
||||
'';
|
||||
# the workerd that nixpkgs' wrangler bundles; must be at least the
|
||||
# workers' compatibility_date
|
||||
version = "1.20261006.1";
|
||||
|
||||
# the flake's source is all of capsite; take what the two workers need
|
||||
src = lib.fileset.toSource {
|
||||
root = ./..;
|
||||
fileset = lib.fileset.unions [
|
||||
./package.json
|
||||
./pnpm-lock.yaml
|
||||
./wrangler.jsonc
|
||||
./tsconfig.json
|
||||
./src
|
||||
../webapp/wrangler.jsonc
|
||||
../webapp/tsconfig.json
|
||||
../webapp/src
|
||||
];
|
||||
};
|
||||
|
||||
diigo-cache = pkgs.stdenv.mkDerivation (finalAttrs: {
|
||||
pname = "diigo-cache";
|
||||
version = "0.0.0";
|
||||
inherit src;
|
||||
sourceRoot = "${finalAttrs.src.name}/diigo-cache";
|
||||
|
||||
nativeBuildInputs = [
|
||||
pkgs.nodejs
|
||||
pkgs.pnpm_10
|
||||
pkgs.pnpmConfigHook
|
||||
pkgs.wrangler
|
||||
];
|
||||
pnpmDeps = pkgs.fetchPnpmDeps {
|
||||
inherit (finalAttrs) pname version src sourceRoot;
|
||||
pnpm = pkgs.pnpm_10;
|
||||
fetcherVersion = 3;
|
||||
hash = "sha256-sn/juOL2mhyy3i57GCUKA2X8SPyR9FwY4KoxdkgZa0M=";
|
||||
};
|
||||
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
export HOME=$TMPDIR WRANGLER_SEND_METRICS=false
|
||||
# wrangler writes .wrangler/tmp beside each config
|
||||
chmod -R u+w ../webapp
|
||||
wrangler deploy --dry-run --outdir $PWD/dist/cache -c wrangler.jsonc
|
||||
wrangler deploy --dry-run --outdir $PWD/dist/webapp -c ../webapp/wrangler.jsonc
|
||||
bash ${./nix/gen-config.sh} dist ${./nix/config.capnp.in} \
|
||||
"$(sed -n 's/.*"compatibility_date": *"\([^"]*\)".*/\1/p' wrangler.jsonc)" \
|
||||
"$(sed -n 's/.*"compatibility_date": *"\([^"]*\)".*/\1/p' ../webapp/wrangler.jsonc)" \
|
||||
> dist/config.capnp
|
||||
runHook postBuild
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
share=$out/share/diigo-cache
|
||||
mkdir -p $share $out/bin $out/lib/systemd/system
|
||||
cp -r dist/cache dist/webapp dist/config.capnp $share/
|
||||
rm -f $share/*/README.md $share/*/*.map
|
||||
cat > $out/bin/diigo-cache-serve <<EOF
|
||||
#!${pkgs.runtimeShell}
|
||||
exec ${workerd}/bin/workerd serve $share/config.capnp "\$@"
|
||||
EOF
|
||||
chmod +x $out/bin/diigo-cache-serve
|
||||
cp ${./nix/diigo-cache.socket} $out/lib/systemd/system/diigo-cache.socket
|
||||
cp ${./nix/diigo-cache.service} $out/lib/systemd/system/diigo-cache.service
|
||||
runHook postInstall
|
||||
'';
|
||||
});
|
||||
in
|
||||
{
|
||||
packages.${system} = {
|
||||
default = diigo-cache;
|
||||
inherit diigo-cache workerd;
|
||||
};
|
||||
|
||||
# the built config serves the home page, and mints a webapp instance
|
||||
# through the WEBAPP binding into webapp's Durable Object storage;
|
||||
# each log entry is one line of JSON
|
||||
checks.${system}.smoke = pkgs.runCommand "diigo-cache-smoke" { nativeBuildInputs = [ pkgs.curl pkgs.jq ]; } ''
|
||||
mkdir -p cache webapp
|
||||
${diigo-cache}/bin/diigo-cache-serve -s http=127.0.0.1:18790 \
|
||||
-d cache-state=$PWD/cache -d webapp-state=$PWD/webapp > log 2>&1 &
|
||||
pid=$!
|
||||
for i in $(seq 50); do curl -sf http://127.0.0.1:18790/ -o home.html && break; sleep 0.2; done
|
||||
grep -q '/_connect' home.html
|
||||
curl -sf -X POST http://127.0.0.1:18790/_mint \
|
||||
--data-urlencode url=https://diigo.invalid/ --data-urlencode cookie=x \
|
||||
-D headers -o /dev/null
|
||||
grep -qi '^x-webapp-id: [A-Za-z0-9-]' headers
|
||||
ls webapp/*/*.sqlite
|
||||
kill $pid; wait $pid || true
|
||||
cat log
|
||||
grep -q "event: 'mint'" log
|
||||
jq -e . log > /dev/null
|
||||
touch $out
|
||||
'';
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
# diigo-cache and the webapp it reads diigo through, in one workerd.
|
||||
#
|
||||
# The listening socket has no address here: systemd hands it in
|
||||
# (-S http=3), so holding the socket is the authority to reach the cache.
|
||||
# State directories likewise come from the command line:
|
||||
# -d cache-state=<dir> -d webapp-state=<dir>.
|
||||
#
|
||||
# Durable Object unique keys follow miniflare's `<script>-<class>`, so a
|
||||
# `wrangler dev` state directory names its objects the same way.
|
||||
using Workerd = import "/workerd/workerd.capnp";
|
||||
|
||||
const config :Workerd.Config = (
|
||||
services = [
|
||||
(name = "diigo-cache", worker = .cache),
|
||||
(name = "webapp", worker = .webapp),
|
||||
(name = "nowhere", network = (allow = [])),
|
||||
(name = "cache-state", disk = (path = "cache-state", writable = true)),
|
||||
(name = "webapp-state", disk = (path = "webapp-state", writable = true)),
|
||||
],
|
||||
sockets = [
|
||||
(name = "http", http = (), service = "diigo-cache"),
|
||||
],
|
||||
# one JSON object per line, console.* included: journald keeps an
|
||||
# object in one entry rather than one entry per line of it
|
||||
structuredLogging = true,
|
||||
);
|
||||
|
||||
const cache :Workerd.Worker = (
|
||||
compatibilityDate = "@CACHE_DATE@",
|
||||
modules = [
|
||||
@CACHE_MODULES@
|
||||
],
|
||||
durableObjectNamespaces = [
|
||||
(className = "DiigoCache", uniqueKey = "diigo-cache-DiigoCache", enableSql = true),
|
||||
(className = "PublicCache", uniqueKey = "diigo-cache-PublicCache", enableSql = true),
|
||||
],
|
||||
durableObjectStorage = (localDisk = "cache-state"),
|
||||
bindings = [
|
||||
(name = "CACHE_DO", durableObjectNamespace = "DiigoCache"),
|
||||
(name = "PUBLIC_DO", durableObjectNamespace = "PublicCache"),
|
||||
(name = "WEBAPP", service = (name = "webapp", entrypoint = "WebAppFactory")),
|
||||
],
|
||||
# diigo is reached only through WEBAPP
|
||||
globalOutbound = "nowhere",
|
||||
);
|
||||
|
||||
const webapp :Workerd.Worker = (
|
||||
compatibilityDate = "@WEBAPP_DATE@",
|
||||
modules = [
|
||||
@WEBAPP_MODULES@
|
||||
],
|
||||
durableObjectNamespaces = [
|
||||
(className = "WebAppDo", uniqueKey = "webapp-WebAppDo", enableSql = true),
|
||||
],
|
||||
durableObjectStorage = (localDisk = "webapp-state"),
|
||||
bindings = [
|
||||
(name = "WEBAPP_DO", durableObjectNamespace = "WebAppDo"),
|
||||
],
|
||||
# globalOutbound: workerd's default "internet", public addresses only
|
||||
);
|
||||
@@ -0,0 +1,31 @@
|
||||
[Unit]
|
||||
Description=diigo-cache and webapp (workerd)
|
||||
Requires=diigo-cache.socket
|
||||
|
||||
[Service]
|
||||
# the profile path survives upgrades; see doc/install.md
|
||||
ExecStart=/nix/var/nix/profiles/diigo-cache/bin/diigo-cache-serve -S http=3 -d cache-state=/var/lib/diigo-cache/cache -d webapp-state=/var/lib/diigo-cache/webapp
|
||||
DynamicUser=yes
|
||||
StateDirectory=diigo-cache diigo-cache/cache diigo-cache/webapp
|
||||
StateDirectoryMode=0700
|
||||
# webapp fetches diigo.com; nothing else needs the network
|
||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
PrivateDevices=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectControlGroups=yes
|
||||
RestrictNamespaces=yes
|
||||
LockPersonality=yes
|
||||
CapabilityBoundingSet=
|
||||
SystemCallFilter=@system-service
|
||||
# V8 uses memory protection keys; without these, SIGSYS at startup
|
||||
SystemCallFilter=pkey_alloc pkey_mprotect pkey_free
|
||||
# not MemoryDenyWriteExecute: V8's JIT needs W+X
|
||||
|
||||
[Install]
|
||||
# started at boot, not only on the first request: workerd runs the
|
||||
# caches' refresh alarms only while it is up
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=diigo-cache: loopback port behind tailscale serve
|
||||
|
||||
[Socket]
|
||||
# tailscale serve proxies https://bldbox.<tailnet>.ts.net/ here
|
||||
ListenStream=127.0.0.1:8790
|
||||
|
||||
[Install]
|
||||
WantedBy=sockets.target
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fill config.capnp.in from `wrangler deploy --dry-run` outdirs.
|
||||
# usage: gen-config.sh <dist> <template> <cache-date> <webapp-date> > config.capnp
|
||||
# <dist>/cache and <dist>/webapp each hold index.js plus the text modules
|
||||
# wrangler.jsonc's rules name (*.sql, capnweb's browser build); embed
|
||||
# paths are relative to the config, which sits beside them.
|
||||
set -euo pipefail
|
||||
dist=$1 template=$2 cache_date=$3 webapp_date=$4
|
||||
|
||||
modules() {
|
||||
local dir=$1
|
||||
if [[ ! -f $dist/$dir/index.js ]]; then
|
||||
echo "gen-config: $dist/$dir/index.js: missing" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo " (name = \"index.js\", esModule = embed \"$dir/index.js\"),"
|
||||
for f in "$dist/$dir"/*; do
|
||||
local name=${f##*/}
|
||||
case $name in
|
||||
index.js | README.md | *.map) ;;
|
||||
*.sql | *-index.js) echo " (name = \"$name\", text = embed \"$dir/$name\")," ;;
|
||||
*)
|
||||
echo "gen-config: $dir/$name: no module type rule" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
cache_modules=$(modules cache)
|
||||
webapp_modules=$(modules webapp)
|
||||
while IFS= read -r line; do
|
||||
case $line in
|
||||
@CACHE_MODULES@) echo "$cache_modules" ;;
|
||||
@WEBAPP_MODULES@) echo "$webapp_modules" ;;
|
||||
*)
|
||||
line=${line//@CACHE_DATE@/$cache_date}
|
||||
echo "${line//@WEBAPP_DATE@/$webapp_date}"
|
||||
;;
|
||||
esac
|
||||
done <"$template"
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
# Serve a built package under the service unit's syscall filter, as a
|
||||
# transient user unit, on a scratch port and state; check the home page.
|
||||
# The flake's smoke check can't: the nix sandbox has no systemd.
|
||||
# usage: probe-unit.sh <package out path>
|
||||
set -euo pipefail
|
||||
out=$1
|
||||
state=$(mktemp -d)
|
||||
trap 'systemctl --user stop diigo-cache-probe 2>/dev/null; rm -rf "$state"' EXIT
|
||||
mkdir "$state/cache" "$state/webapp"
|
||||
|
||||
props=()
|
||||
while IFS= read -r line; do props+=(-p "$line"); done \
|
||||
< <(grep '^SystemCallFilter=' "$out/lib/systemd/system/diigo-cache.service")
|
||||
|
||||
systemd-run --user -q --collect --unit=diigo-cache-probe "${props[@]}" \
|
||||
"$out/bin/diigo-cache-serve" -s http=127.0.0.1:18791 \
|
||||
-d cache-state="$state/cache" -d webapp-state="$state/webapp"
|
||||
for _ in $(seq 30); do
|
||||
if curl -sf -m 2 http://127.0.0.1:18791/ | grep -q _connect; then
|
||||
echo "probe: ok"
|
||||
exit 0
|
||||
fi
|
||||
sleep 0.3
|
||||
done
|
||||
echo "probe: no home page; see journalctl --user -u diigo-cache-probe and journalctl -k | grep syscall=" >&2
|
||||
exit 1
|
||||
@@ -44,6 +44,14 @@ const LEGACY_FILL_PAGE_SIZE = 24;
|
||||
* pages at MS_PER_CALL; this keeps steps from running back to back */
|
||||
const FILL_STEP_DELAY_MS = 1000;
|
||||
|
||||
/** how long after a fill ends (done or failed) a refresh starts: a fill
|
||||
* that refetches the recent pages, then ends and schedules the next */
|
||||
const REFRESH_INTERVAL_MS = 3 * 60 * 60 * 1000;
|
||||
|
||||
/** a refresh refetches the pages holding anything updated this recently
|
||||
* (and every page before them; page 1 at least, for new bookmarks) */
|
||||
const REFRESH_DAYS = 2;
|
||||
|
||||
/**
|
||||
* a fill job's progress (goal 1e; tests/fill.test.ts). Stored in the DO
|
||||
* (new state, additive), so it survives eviction; advanced by alarms.
|
||||
@@ -66,6 +74,9 @@ export type FillStatus = {
|
||||
updatedAt: string;
|
||||
/** why it failed: safe to show and log (no ids, no header values) */
|
||||
error?: string;
|
||||
/** pages numbered this or lower are fetched even when cached (a
|
||||
* refresh); absent on plain fills */
|
||||
refetchThrough?: number;
|
||||
};
|
||||
|
||||
/** the page size a fill job counts in (old jobs didn't record it) */
|
||||
@@ -139,6 +150,11 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
await null; // let the subclass constructor finish: `kind` is its field
|
||||
const from = this.#writer.migrate();
|
||||
if (from < SCHEMA_VERSION) console.log({ event: "schema", kind: this.kind, from, to: SCHEMA_VERSION });
|
||||
// a fill that ended before refreshes existed has no alarm yet
|
||||
const fill = await ctx.storage.get<FillStatus>("fill");
|
||||
if (fill && fill.state !== "running" && fill.state !== "stopped" && (await ctx.storage.getAlarm()) === null) {
|
||||
await ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -176,12 +192,20 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
* cache, `pagesPerStep` per alarm (default 20, 1–50). Starting while a
|
||||
* job runs returns that job unchanged; a finished, stopped, or failed
|
||||
* job is replaced by a fresh one (cached pages are skipped anyway).
|
||||
* Once the job ends, a refresh follows every REFRESH_INTERVAL_MS until
|
||||
* stopped.
|
||||
*/
|
||||
async startFill(opts: { pagesPerStep?: number } = {}): Promise<FillStatus> {
|
||||
const current = await this.fillStatus();
|
||||
if (current?.state === "running" && fillCountsAsNow(current)) return current;
|
||||
const step = Math.trunc(opts.pagesPerStep ?? 20);
|
||||
if (!(step >= 1 && step <= 50)) throw new Error("pagesPerStep: expected 1–50");
|
||||
return this.#startJob(step);
|
||||
}
|
||||
|
||||
/** a fresh fill job, first step in FILL_STEP_DELAY_MS; `refetchThrough`
|
||||
* makes it a refresh */
|
||||
async #startJob(step: number, refetchThrough?: number): Promise<FillStatus> {
|
||||
const now = this.#iso();
|
||||
const status: FillStatus = {
|
||||
state: "running",
|
||||
@@ -192,13 +216,22 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
fetched: 0,
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
...(refetchThrough === undefined ? {} : { refetchThrough }),
|
||||
};
|
||||
await this.ctx.storage.put({ fill: status, fillStep: step });
|
||||
await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
|
||||
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step });
|
||||
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step, refetchThrough });
|
||||
return status;
|
||||
}
|
||||
|
||||
/** start a refresh: a fill that refetches the pages holding anything
|
||||
* updated in the last REFRESH_DAYS days. Fetching overwrites a page in
|
||||
* place, so a refresh that fails leaves the cache as it was. */
|
||||
async #refresh(step: number): Promise<void> {
|
||||
const cutoff = Math.floor(this.#clock.now() / 1000) - REFRESH_DAYS * 24 * 60 * 60;
|
||||
await this.#startJob(step, Math.max(1, this.#reader.deepestPageSince(cutoff) ?? 1));
|
||||
}
|
||||
|
||||
/** the fill job's progress, or undefined if none was ever started;
|
||||
* the page count comes from any cached page until the job learns it */
|
||||
async fillStatus(): Promise<FillStatus | undefined> {
|
||||
@@ -206,11 +239,12 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
return fill && fill.pages === null ? { ...fill, pages: this.#knownPages() } : fill;
|
||||
}
|
||||
|
||||
/** stop the fill job after its current step; cached pages stay */
|
||||
/** stop the fill job after its current step, and its refreshes;
|
||||
* cached pages stay */
|
||||
async stopFill(): Promise<FillStatus> {
|
||||
const current = await this.fillStatus();
|
||||
if (!current) throw new Error("no fill job to stop");
|
||||
if (current.state !== "running") return current;
|
||||
if (current.state === "stopped") return current;
|
||||
const stopped: FillStatus = { ...current, state: "stopped", updatedAt: this.#iso() };
|
||||
await this.ctx.storage.put("fill", stopped);
|
||||
await this.ctx.storage.deleteAlarm();
|
||||
@@ -239,10 +273,15 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
}
|
||||
|
||||
/** one fill step: up to `fillStep` pages, progress saved after each,
|
||||
* then the next step is scheduled (or the job ends) */
|
||||
* then the next step is scheduled (or the job ends, and the next
|
||||
* refresh is). On a job that has ended, the refresh starts. */
|
||||
async alarm(): Promise<void> {
|
||||
const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20;
|
||||
let status = await this.fillStatus();
|
||||
if (status?.state === "done" || status?.state === "failed") {
|
||||
await this.#refresh(step);
|
||||
return;
|
||||
}
|
||||
// a job saved under another page size or numbering counts its pages
|
||||
// differently: resuming it would skip or repeat items, so it fails
|
||||
if (status?.state === "running" && !fillCountsAsNow(status)) {
|
||||
@@ -253,6 +292,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
status = { ...status, state: "failed", error, updatedAt: this.#iso() };
|
||||
console.error({ event: "fill", kind: this.kind, state: "failed", error });
|
||||
await this.ctx.storage.put("fill", status);
|
||||
await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < step && status?.state === "running"; i += 1) {
|
||||
@@ -261,7 +301,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
const page = await this.page(status.nextPage, PAGE_SIZE);
|
||||
const page = await this.#load(status.nextPage, PAGE_SIZE, status.nextPage <= (status.refetchThrough ?? 0));
|
||||
const fetched = status.fetched + (page.cached ? 0 : 1);
|
||||
// a page whose own total says the data ended before it (diigo
|
||||
// answers total 0 past the end) ends the walk; the count is the
|
||||
@@ -293,6 +333,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
await this.ctx.storage.put("fill", status);
|
||||
console.log({ event: "fill", kind: this.kind, state: status.state, nextPage: status.nextPage, pages: status.pages, fetched: status.fetched });
|
||||
if (status.state === "running") await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
|
||||
else await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
|
||||
}
|
||||
|
||||
/** diigo's page count, if any cached page recorded `total` (pages past
|
||||
@@ -309,10 +350,16 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
* rides in the result (`cached`).
|
||||
*/
|
||||
async page(pageNum: number, count: number): Promise<CachePage> {
|
||||
return this.#load(pageNum, count, false);
|
||||
}
|
||||
|
||||
/** {@link page}, or with `fresh`, fetch even if cached (overwriting
|
||||
* the stored page) */
|
||||
async #load(pageNum: number, count: number, fresh: boolean): Promise<CachePage> {
|
||||
const init = await this.wiring();
|
||||
if (!init) throw new Error("not wired: this cache id was never set up");
|
||||
|
||||
const hit = await this.#pageFromStorage(pageNum, count);
|
||||
const hit = fresh ? null : await this.#pageFromStorage(pageNum, count);
|
||||
if (hit) {
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length });
|
||||
return hit;
|
||||
@@ -329,7 +376,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
this.#step += 1;
|
||||
this.#pause = this.#clock.sleep(MS_PER_CALL);
|
||||
// a request ahead of us at the gate may have etched this page
|
||||
const late = await this.#pageFromStorage(pageNum, count);
|
||||
const late = fresh ? null : await this.#pageFromStorage(pageNum, count);
|
||||
if (late) {
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length });
|
||||
return late;
|
||||
@@ -357,7 +404,7 @@ abstract class PagedCache extends DurableObject<CacheEnv> {
|
||||
}
|
||||
const kept = this.keep(toRows(data.items, console));
|
||||
// fetched vs kept: the public cache's drop of private rows shows here
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "miss", fetched: data.items.length, kept: kept.length });
|
||||
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: fresh ? "refetch" : "miss", fetched: data.items.length, kept: kept.length });
|
||||
return this.#etch(pageNum, count, data.total, kept);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,10 +26,14 @@ const wired = async (webappId = "fake-webapp-id") => {
|
||||
return stub;
|
||||
};
|
||||
|
||||
/** run alarms until none is scheduled (bounded, so a runaway job fails) */
|
||||
const drain = async (stub: DurableObjectStub, max = 20) => {
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
/** run alarms until the job ends (bounded, so a runaway job fails); the
|
||||
* refresh alarm an ended job leaves is not run */
|
||||
const drain = async (stub: DurableObjectStub & { fillStatus(): Promise<{ state: string } | undefined> }, max = 20) => {
|
||||
let ran = 0;
|
||||
while (ran < max && (await runDurableObjectAlarm(stub))) ran += 1;
|
||||
const running = async () => (await stub.fillStatus())?.state === "running";
|
||||
while (ran < max && (await running()) && (await runDurableObjectAlarm(stub))) ran += 1;
|
||||
expect(ran).toBeLessThan(max);
|
||||
return ran;
|
||||
};
|
||||
@@ -120,6 +124,9 @@ describe("fill job (goal 1e)", () => {
|
||||
});
|
||||
await drain(stub);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "done", updatedAt: at });
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
expect(await state.storage.getAlarm()).toBe(FIXED_NOW + 3 * HOUR);
|
||||
});
|
||||
});
|
||||
|
||||
it("a capped page size fails the fill with the reason, instead of skipping items", async () => {
|
||||
@@ -170,6 +177,66 @@ describe("fill job (goal 1e)", () => {
|
||||
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, pageSize: PAGE_SIZE });
|
||||
});
|
||||
|
||||
it("refreshes 3 hours after a fill: refetches the pages updated in the last 2 days, skips the rest, then waits again", async () => {
|
||||
// deep account: item n updated n-1 days + 1 hour ago, so items 1–2
|
||||
// (both on page 1) are within 2 days
|
||||
const stub = await wired("fake-deep-webapp");
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
const alarm = (await state.storage.getAlarm()) ?? 0;
|
||||
expect(alarm - Date.now()).toBeGreaterThan(2.9 * HOUR);
|
||||
expect(alarm - Date.now()).toBeLessThanOrEqual(3 * HOUR);
|
||||
});
|
||||
expect(await runDurableObjectAlarm(stub)).toBe(true);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 1, refetchThrough: 1 });
|
||||
await drain(stub);
|
||||
// fetched counts diigo calls; pages 2–3 were hits
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "done", pages: 3, fetched: 1 });
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
expect(await state.storage.getAlarm()).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("a refresh refetches page 1 even when nothing cached is recent: new bookmarks land there", async () => {
|
||||
const stub = await wired();
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
await runDurableObjectAlarm(stub);
|
||||
expect(await stub.fillStatus()).toMatchObject({ refetchThrough: 1 });
|
||||
await drain(stub);
|
||||
expect(await stub.fillStatus()).toMatchObject({ state: "done", fetched: 1 });
|
||||
});
|
||||
|
||||
it("a failed fill is retried by the next refresh; a stopped one is not", async () => {
|
||||
const failing = await wired("no-such-webapp");
|
||||
await failing.startFill();
|
||||
await drain(failing);
|
||||
expect((await failing.fillStatus())?.state).toBe("failed");
|
||||
expect(await runDurableObjectAlarm(failing)).toBe(true);
|
||||
expect((await failing.fillStatus())?.state).toBe("running");
|
||||
|
||||
const stopped = await wired();
|
||||
await stopped.startFill();
|
||||
await drain(stopped);
|
||||
expect((await stopped.stopFill()).state).toBe("stopped");
|
||||
expect(await runDurableObjectAlarm(stopped)).toBe(false);
|
||||
});
|
||||
|
||||
it("a fill that ended before refreshes existed gets one when the cache next wakes", async () => {
|
||||
const stub = await wired();
|
||||
await stub.startFill();
|
||||
await drain(stub);
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
await state.storage.deleteAlarm();
|
||||
});
|
||||
await evictDurableObject(stub);
|
||||
await stub.fillStatus();
|
||||
await runInDurableObject(stub, async (_obj, state) => {
|
||||
expect(await state.storage.getAlarm()).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("a public cache's fill stores no private rows", async () => {
|
||||
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
|
||||
await stub.setup({ webappId: "fake-webapp-id" });
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 113 KiB |
@@ -0,0 +1,295 @@
|
||||
---
|
||||
title: Good Fences Make Good Agents
|
||||
type: slide
|
||||
slideOptions:
|
||||
transition: slide
|
||||
center: false
|
||||
---
|
||||
<style>
|
||||
.reveal h1 { font-size: 1.8em; }
|
||||
.reveal h2 { font-size: 1.2em; }
|
||||
.reveal table { font-size: 0.6em; }
|
||||
.reveal ul { font-size: 0.7em; }
|
||||
.reveal pre { font-size: 0.45em; }
|
||||
</style>
|
||||
|
||||
# Good Fences Make Good Agents
|
||||
|
||||
*with apologies to Robert Frost*
|
||||
|
||||
Dan Connolly · Oct 2026
|
||||
|
||||
---
|
||||
|
||||
## I bookmark on diigo all week…
|
||||
|
||||
<img src="tada-diigo-library.png" style="max-height: 45vh">
|
||||
|
||||
|
||||
…and since Dec 2016 I've wanted them on my blog: [madmode-blog#23](https://github.com/dckc/madmode-blog/issues/23)
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Monday's issue drafts itself
|
||||
|
||||

|
||||
|
||||
One click on potluck's EmDash dashboard; I cut, comment, and publish.
|
||||
|
||||
[the Loom](https://www.loom.com/share/191c7ad59660477a92d799906e93c4e9)
|
||||
|
||||
---
|
||||
|
||||
## POLA IO: diigo-cache gets limited fetch
|
||||
|
||||
- `makeWebApp().joinpath('diigo.com/api').withHeaders({cookie})`
|
||||
<img src="weekly-roundup-wiring.png" style="max-height: 80vh">
|
||||
|
||||
---
|
||||
|
||||
## fluent builder API narrows
|
||||
|
||||
- `makeWebApp().joinpath('diigo.com/api').withHeaders({cookie})`
|
||||
|
||||
- ✨ diigo-week gets only read-only `viewer`: h-feed of public items
|
||||
- ✨ the cache id is kept in my password manager
|
||||
- ⏳ frozen `{ cookie }`
|
||||
- fresh cookie needs a new access and a **new cache**
|
||||
|
||||
---
|
||||
|
||||
## ✨ Rotating with mutable cookie MapStore
|
||||
|
||||
<img src="cookie-rotation-wiring.png" style="max-height: 80vh">
|
||||
|
||||
---
|
||||
|
||||
## ✨ Rotating with cookie MapStore
|
||||
|
||||
- the cookie lives in Alice's store; `access` reads a read-only facet at every send
|
||||
- Mallory, holding the instance id, can use the cookie but can't rotate it
|
||||
|
||||
---
|
||||
|
||||
## It's one piece of a toybox
|
||||
|
||||
| story | source | sink | trigger |
|
||||
|---|---|---|---|
|
||||
| S1 weekly roundup | diigo, public only | madmode draft | weekly, human edits |
|
||||
| S2 album to album | **one** Google Photos album | **one** Amazon folder | each insert, nobody watching |
|
||||
| S3 drag to archive.org | Google Photos | archive.org | drag-and-drop |
|
||||
|
||||
Recurring needs: **narrowed capabilities** and **confined generated code**.
|
||||
|
||||
---
|
||||
|
||||
## The toy version: lend a mower
|
||||
|
||||
```js
|
||||
client.chat.completions.create({
|
||||
messages: [{
|
||||
role: 'user',
|
||||
content: 'you can use this mower for the weekend',
|
||||
things: { mower },
|
||||
about: { mower: { ts: 'type Mower { start(), push(), turn(), stop() }' }}
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
- the neighbor writes code; a **tenant** runs it in a dynamic worker, endowed with only `mower`
|
||||
- I lend a **governed** mower: never more than 100 yards (10 cells) from where it started
|
||||
|
||||
---
|
||||
|
||||
## The fence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant T as tenant
|
||||
participant G as governed mower
|
||||
participant M as mower DO
|
||||
T->>G: push()
|
||||
G->>M: push()
|
||||
T->>G: push()
|
||||
G->>M: push()
|
||||
T->>G: push()
|
||||
G-->>T: throws 'fence: 2 cells from start'
|
||||
```
|
||||
|
||||
⏳ _no governor code; just design: ([lend-the-mower](../good-fences/docs/lend-the-mower.md))
|
||||
|
||||
---
|
||||
|
||||
## ✨ The model writes code to mow
|
||||
|
||||
gpt-oss-120b on Workers AI, given `about.mower` and the story; the test reads the code it writes:
|
||||
|
||||
```js
|
||||
async (env) => {
|
||||
const { mower } = env;
|
||||
mower.start(); // cuts the starting cell
|
||||
for (let c = 0; c < cols; c++) {
|
||||
for (let i = 0; i < rows - 1; i++) {
|
||||
mower.push(); // cut next cell
|
||||
}
|
||||
...
|
||||
}
|
||||
await mower.stop(); // wait for the whole batch to finish
|
||||
```
|
||||
|
||||
✨ no `await` per call: promise pipelining, after one `lamp` example in the prompt
|
||||
|
||||
---
|
||||
|
||||
## 🪄 A little tipsy
|
||||
|
||||
```js
|
||||
if (c < cols - 1) {
|
||||
calls.push(env.mower.turn()); // turn right
|
||||
calls.push(env.mower.push()); // step into next column
|
||||
calls.push(env.mower.turn()); // turn right again (now facing opposite way)
|
||||
}
|
||||
```
|
||||
|
||||
- going north: right, step east, right → facing south ✅
|
||||
- going south: right, step **west**, right → facing north 🐛
|
||||
- run, it would mow two columns, back and forth: "mowed 2401 cells"
|
||||
|
||||
---
|
||||
|
||||
## 🙌 Then: Project Think
|
||||
|
||||
| ours | [Project Think](https://blog.cloudflare.com/project-think/) |
|
||||
|---|---|
|
||||
| the neighbor's harness | a `Think` agent: a DO with sessions, model, prompt, tools |
|
||||
| `code-mode.ts`, `about` | `@cloudflare/codemode`: the model writes code against types |
|
||||
| tenants in dynamic workers | `DynamicWorkerExecutor`, `globalOutbound: null` |
|
||||
|
||||
"no ambient authority; capabilities granted explicitly via bindings"
|
||||
|
||||
---
|
||||
|
||||
## ✅ Green
|
||||
|
||||
```
|
||||
⬜⬜⬜⬜⬜⬜⬜⬜
|
||||
⬜🟩🟩🟩🟩🟩🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩⬜⬜⬜⬜🟩⬜
|
||||
⬜🟩🟩🟩🟩🟩🟩⬜
|
||||
⬜⬜⬜⬜⬜⬜⬜⬜
|
||||
```
|
||||
|
||||
model → generated code → sandbox → mower: 36 calls, 30 cells
|
||||
|
||||
---
|
||||
|
||||
## 🧰 …with ceremony
|
||||
|
||||
The mower, as a codemode connector:
|
||||
|
||||
```ts
|
||||
protected tools(): ConnectorTools {
|
||||
const mower = this.#mower;
|
||||
return {
|
||||
start: { description: "put the mower down, facing north, and cut the cell under it", execute: () => mower.start() },
|
||||
push: { description: "move forward one cell, cutting the cell it enters", execute: () => mower.push() },
|
||||
turn: { description: "turn right 90 degrees, in place", execute: () => mower.turn() },
|
||||
stop: { description: "park the mower", execute: () => mower.stop() },
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
What the model ran, 7 `execute` calls:
|
||||
|
||||
```js
|
||||
await codemode.search('mower')
|
||||
await state.readdir({ path: '/' })
|
||||
await codemode.search('lawn')
|
||||
await codemode.describe('mower.start')
|
||||
await codemode.describe('mower.push')
|
||||
await codemode.describe('mower.turn')
|
||||
await mower.start({}); for (...) await mower.push({}); ...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧱 Not methods on objects
|
||||
|
||||
[Code Mode](https://blog.cloudflare.com/code-mode-mcp/) turns **tools** into a TypeScript API.
|
||||
|
||||
- JSON in, JSON out: no reference goes in, no object comes back
|
||||
- so a neighbor can't hand what it holds to the next neighbor
|
||||
|
||||
One floor down, Workers RPC and Cap'n Web do pass references and pipeline calls.
|
||||
|
||||
---
|
||||
|
||||
## 🧱 Identity, in two halves
|
||||
|
||||
| | durable | passable |
|
||||
|---|---|---|
|
||||
| Durable Object id | ✅ | ❌ a string plus a binding the receiver must already hold |
|
||||
| Workers RPC / Cap'n Web stub | ❌ dies with its request or session | ✅ |
|
||||
| Endo / OCapN reference | ✅ | ✅ |
|
||||
|
||||
> durable, passable object identity. I've been using endo for so long that it just feels like air to me.
|
||||
|
||||
---
|
||||
|
||||
## 🧱 Where it bites
|
||||
|
||||
- S2, album to album: **nobody watching**, so no session to keep a stub alive
|
||||
- a scavenger hunt: a kid buys a Pete Rose card from the shopkeeper → it admits him to the clubhouse → Sam's telescope there reads a QR code a mile away → step 7 → he wins a bicycle
|
||||
- every hop is a reference, held for years
|
||||
- is the card genuine? the clubhouse has to ask its issuer
|
||||
|
||||
---
|
||||
|
||||
## The turn: Cloudflare as a netlayer
|
||||
|
||||
OCapN on top: sturdyrefs for durability, live refs within a session, third-party handoffs.
|
||||
|
||||
| their technique | ours, on references |
|
||||
|---|---|
|
||||
| code mode against generated types | code against `about` for the objects it holds |
|
||||
| `search` / `describe` over many tools | a petname directory the model can browse |
|
||||
| saved snippets | tenant code exported as an entrypoint, handed on |
|
||||
| `runFiber` / `stash` | vat persistence |
|
||||
| sub-agents as DO facets | tenants as child vats |
|
||||
|
||||
Still load-bearing: Worker Loader, Durable Objects and facets, Workers RPC, Cap'n Web, Workers AI.
|
||||
|
||||
---
|
||||
|
||||
## 🧮 Recap +
|
||||
|
||||
✅ the weekly roundup drafts in one click
|
||||
✨ webkeys in a password field; a read-only facet for the plugin
|
||||
✨ model-written code pipelines, in a confined dynamic worker
|
||||
🙌 Project Think: a green spike in an evening
|
||||
|
||||
---
|
||||
|
||||
## 🧮 Recap -
|
||||
|
||||
⏳ nothing deployed; the governor not built
|
||||
🪄 tipsy tenants: always turn right
|
||||
🧰 codemode ceremony: `{ description, execute }`, `search`, `describe`
|
||||
🧱 no durable, passable references: an OCapN layer to build
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- [Good Fences Make Good Agents: design story and IBIS](good-fences-make-good-agents.md)
|
||||
- [toybox user stories](../toybox-stories.md)
|
||||
- [Project Think](https://blog.cloudflare.com/project-think/) · [Code Mode](https://blog.cloudflare.com/code-mode-mcp/)
|
||||
- [OCapN](https://ocapn.org/) · [Cap'n Web](https://github.com/cloudflare/capnweb)
|
||||
@@ -0,0 +1,29 @@
|
||||
# learn by watching: an agent that finds a site's hidden API
|
||||
|
||||
social.coop and zotero publish nice APIs. diigo doesn't: for [diigo-cache](../diigo-cache/README.md) we opened browser devtools, watched the requests the web app made, and wrote a client for them by hand ([the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo)). What if a bot did that part?
|
||||
|
||||
## the workflow
|
||||
|
||||
1. **I log in, by hand.** Whatever site: diigo, my bank. The password never leaves me; the session lives in the browser.
|
||||
2. **I grab a debug capability** on that browser: a [PinchTab](https://github.com/pinchtab/pinchtab) token, or a Chrome DevTools Protocol / WebDriver BiDi endpoint.
|
||||
3. **I hand it to a smart coding agent** (e.g. Opus) and say what I'm about to do: "get last month's transactions."
|
||||
4. **It watches me** navigate and do the task, recording the proceedings: network requests and responses, plus my clicks.
|
||||
5. **It sanitizes the recording** into fixtures for unit tests: cookies, auth headers, account numbers, and names replaced with stand-ins.
|
||||
6. **It writes code** that later uses the debug capability deterministically, with no model in the loop, tested against those fixtures.
|
||||
|
||||
## small steps within a policy
|
||||
|
||||
The generated code only does small steps, such as `listTransactions({ from, to })` or `bookmarksPage(n)`. More sophisticated code (a scheduler, another agent) can drive them, but the steps themselves must clearly stay within a policy:
|
||||
|
||||
> I'm only downloading my bank transactions, not paying bills.
|
||||
|
||||
The policy is code, not a prompt: a facet in front of the debug capability that allows only the requests the recording justified (method + URL pattern, e.g. `GET /accounts/*/transactions`) and refuses everything else. The driver holds only the facet, never the raw capability, so a confused or compromised driver still can't reach `POST /payments`. This is the [governed mower](good-fences-make-good-agents.md) again: I attenuate before I hand it over.
|
||||
|
||||
Raw CDP is nearly unlimited authority (it can evaluate arbitrary JS in the page), which is why only the watching phase, with me present, uses it directly.
|
||||
|
||||
## open questions
|
||||
|
||||
- **Replay or drive?** If the recorded API is plain HTTP, extract the session and replay it with `fetch`, as diigo-cache does; the facet then wraps `fetch`, not a browser. Sites that need in-page JS (anti-bot tokens, signed requests) have to be driven through the browser.
|
||||
- **Who reviews the policy?** The agent proposes the allowlist from the recording; I approve it. Is a diff of URL patterns reviewable enough?
|
||||
- **Drift:** sites change their private APIs. The fixtures make breakage loud; re-watching should be cheap.
|
||||
- **Session lifetime:** the facet is only as durable as the login. Re-login stays manual.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 232 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 156 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 240 KiB |
@@ -0,0 +1,148 @@
|
||||
<!doctype html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<title>weekly roundup on main: who holds what</title>
|
||||
<!-- drawn after the style of MarkM's ERTP slides, as cookie-rotation-wiring.html on the webapp-cookie-rotation branch; weekly-roundup-wiring.png is a headless-Chromium screenshot of this page -->
|
||||
<style>
|
||||
html, body { margin: 0; background: #fff; }
|
||||
.sans { font-family: "Helvetica Neue", "DejaVu Sans", sans-serif; }
|
||||
.obj { font-family: "DejaVu Serif", serif; font-style: italic; }
|
||||
.mono { font-family: "DejaVu Sans Mono", monospace; }
|
||||
</style></head>
|
||||
<body>
|
||||
<svg id="c" xmlns="http://www.w3.org/2000/svg" width="1120" height="820" viewBox="0 0 1120 820"
|
||||
role="img" aria-labelledby="title desc">
|
||||
<title id="title">weekly roundup on main: who holds what</title>
|
||||
<desc id="desc">Three actors and two makers. Alice holds a cache id, saved in her
|
||||
password manager, which refers to a DiigoCache. Each DiigoCache refers to its
|
||||
wiring table: webappId and publicId. webappId refers to an access object made
|
||||
by makeWebApp; publicId refers to a PublicCache, which refers to the same
|
||||
access. Each access refers to its init table: url and headers, and the
|
||||
headers hold the diigo session cookie. A viewer facet reads the PublicCache
|
||||
and can't fetch or write; diigo-week, the potluck plugin, reaches only the
|
||||
viewer, as the public page's h-feed. Mallory, who learned the instance id,
|
||||
also refers to access, so she can use the cookie. The wiring is set once, so
|
||||
when Alice logs in again she has to mint a new access and a new cache.</desc>
|
||||
<defs>
|
||||
<radialGradient id="ball" cx="40%" cy="35%" r="70%">
|
||||
<stop offset="0%" stop-color="#7cc8f8"/>
|
||||
<stop offset="100%" stop-color="#3aa6ee"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="objfill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stop-color="#6cbcf4"/>
|
||||
<stop offset="100%" stop-color="#4aa8ec"/>
|
||||
</linearGradient>
|
||||
<marker id="head" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
|
||||
<path d="M0,0 L10,5 L0,10 z" fill="#1d4f7a"/>
|
||||
</marker>
|
||||
</defs>
|
||||
</svg>
|
||||
<script>
|
||||
const svg = document.getElementById("c");
|
||||
const NS = "http://www.w3.org/2000/svg";
|
||||
const el = (name, attrs, parent = svg) => {
|
||||
const e = document.createElementNS(NS, name);
|
||||
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
|
||||
parent.appendChild(e);
|
||||
return e;
|
||||
};
|
||||
const text = (x, y, s, cls, attrs = {}) => {
|
||||
const t = el("text", { x, y, class: cls, "text-anchor": "middle", fill: "#1d3550", ...attrs });
|
||||
t.textContent = s;
|
||||
return t;
|
||||
};
|
||||
|
||||
const INK = "#1d4f7a";
|
||||
const dot = (x, y) => el("circle", { cx: x, cy: y, r: 4.5, fill: INK });
|
||||
/** a reference: dot at the holder, arrowhead at the target */
|
||||
const ref = (x1, y1, x2, y2, bend = 0, extra = {}) => {
|
||||
dot(x1, y1);
|
||||
const mx = (x1 + x2) / 2 - (y2 - y1) * bend, my = (y1 + y2) / 2 + (x2 - x1) * bend;
|
||||
el("path", { d: `M${x1},${y1} Q${mx},${my} ${x2},${y2}`, fill: "none", stroke: INK, "stroke-width": 2, "marker-end": "url(#head)", ...extra });
|
||||
};
|
||||
|
||||
// maker box: a pale rounded region, with stacked instances inside
|
||||
function maker(x, y, w, h, label) {
|
||||
el("rect", { x, y, width: w, height: h, rx: 26, fill: "#d6ecfb", stroke: "#b5dbf5", "stroke-width": 1.5 });
|
||||
text(x + 18, y + 30, label, "obj", { "text-anchor": "start", "font-size": 20 });
|
||||
for (let i = 2; i >= 0; i -= 1) {
|
||||
el("rect", {
|
||||
x: x + 18 + i * 9, y: y + 48 + i * 9, width: w - 52, height: h - 82, rx: 22,
|
||||
fill: "#c8e5fa", stroke: "#8ec9f2", "stroke-width": 1.5, "fill-opacity": 0.9,
|
||||
});
|
||||
}
|
||||
}
|
||||
// an object: rounded square, optionally stacked (several made)
|
||||
function obj(x, y, w, h, label, stacked = false) {
|
||||
const n = stacked ? 3 : 1;
|
||||
for (let i = n - 1; i >= 0; i -= 1) {
|
||||
el("rect", { x: x + i * 7, y: y - i * 7, width: w, height: h, rx: 12, fill: "url(#objfill)", stroke: "#2f8fd6", "stroke-width": 1.5 });
|
||||
}
|
||||
text(x + w / 2, y + h / 2 + 7, label, "obj", { "font-size": 19 });
|
||||
}
|
||||
function actor(cx, cy, label) {
|
||||
el("circle", { cx, cy, r: 52, fill: "url(#ball)", stroke: "#2f8fd6", "stroke-width": 1.5 });
|
||||
text(cx, cy + 6, label, "sans", { "font-size": label.length > 8 ? 15 : 17 });
|
||||
}
|
||||
// a table like the ERTP ledger
|
||||
function table(x, y, title, rows, colW) {
|
||||
const rowH = 28, w = colW[0] + colW[1];
|
||||
el("rect", { x, y, width: w, height: 36 + rowH * rows.length, fill: "#5fb5f2", stroke: "#2f8fd6", "stroke-width": 1.5 });
|
||||
text(x + w / 2, y + 25, title, "obj", { "font-size": 18 });
|
||||
rows.forEach(([k, v], i) => {
|
||||
const ry = y + 36 + i * rowH;
|
||||
el("line", { x1: x, y1: ry, x2: x + w, y2: ry, stroke: "#2f8fd6", "stroke-width": 1.2 });
|
||||
text(x + 10, ry + 19, k, "mono", { "text-anchor": "start", "font-size": 14 });
|
||||
if (v) text(x + colW[0] + 10, ry + 19, v, "mono", { "text-anchor": "start", "font-size": 14 });
|
||||
});
|
||||
el("line", { x1: x + colW[0], y1: y + 36, x2: x + colW[0], y2: y + 36 + rowH * rows.length, stroke: "#1d4f7a", "stroke-width": 1.5 });
|
||||
return { rowY: (i) => y + 36 + i * rowH + rowH / 2, x, w, colX: x + colW[0] };
|
||||
}
|
||||
|
||||
// speech bubble (Alice, after logging in to diigo again)
|
||||
el("path", {
|
||||
d: "M30,22 h470 a16,16 0 0 1 16,16 v34 a16,16 0 0 1 -16,16 h-330 l-38,48 l6,-48 h-102 a16,16 0 0 1 -16,-16 v-34 a16,16 0 0 1 16,-16 z",
|
||||
fill: "#d9d9d9", stroke: "#555", "stroke-width": 2,
|
||||
});
|
||||
text(46, 62, "fresh cookie? mint a new access, a new cache", "mono", { "text-anchor": "start", "font-size": 16, fill: "#222" });
|
||||
|
||||
// actors
|
||||
actor(150, 200, "Alice");
|
||||
actor(560, 200, "diigo-week");
|
||||
actor(930, 200, "Mallory");
|
||||
|
||||
// makers
|
||||
maker(30, 320, 500, 470, "diigo-cache");
|
||||
maker(590, 320, 500, 470, "makeWebApp");
|
||||
|
||||
// diigo-cache insides
|
||||
obj(70, 410, 150, 80, "DiigoCache", true);
|
||||
const wiring = table(270, 410, "wiring", [["webappId", "…"], ["publicId", "…"]], [110, 90]);
|
||||
obj(70, 610, 150, 80, "PublicCache", true);
|
||||
obj(300, 640, 120, 60, "viewer", true);
|
||||
|
||||
// makeWebApp insides
|
||||
obj(640, 560, 140, 90, "access", true);
|
||||
const init = table(840, 420, "init", [["url", "diigo…"], ["headers", "{cookie}"]], [100, 105]);
|
||||
|
||||
// references
|
||||
ref(140, 228, 130, 403, 0.03); // Alice → DiigoCache (cache id)
|
||||
ref(560, 228, 380, 627, -0.04); // diigo-week → viewer
|
||||
ref(930 - 14, 200 + 20, 740, 553, -0.08); // Mallory → access
|
||||
ref(160, 450, wiring.x - 2, wiring.rowY(0), 0.05); // DiigoCache → wiring
|
||||
ref(wiring.colX + 40, wiring.rowY(0), 646, 580, -0.12); // webappId → access
|
||||
ref(wiring.colX + 40, wiring.rowY(1), 165, 598, -0.08); // publicId → PublicCache
|
||||
ref(200, 688, 632, 640, 0.25); // PublicCache → access
|
||||
ref(306, 675, 232, 668, 0.1); // viewer → PublicCache (read)
|
||||
ref(780, 600, init.x - 2, init.rowY(1), -0.1); // access → init
|
||||
|
||||
// captions
|
||||
const cap = (x, y, s, attrs = {}) => text(x, y, s, "sans", { "font-size": 14, fill: "#33536f", ...attrs });
|
||||
cap(270, 286, "cache id, in the password manager", {});
|
||||
cap(560, 120, "potluck plugin: /public/<user>, an h-feed;", {});
|
||||
cap(560, 138, "reaches only the viewer", {});
|
||||
cap(930, 118, "holds the instance id:", {});
|
||||
cap(930, 136, "uses the cookie", {});
|
||||
cap(280, 806, "setup(wiring) is one-shot: different values are refused", {});
|
||||
cap(840, 806, "the cookie rides in init.headers, fixed at mint", {});
|
||||
</script>
|
||||
</body></html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 125 KiB |
@@ -0,0 +1,185 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Lend the Mower</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f7f7f2; --fg: #1d2318; --muted: #6b7262; --line: #d9dccf;
|
||||
--grass: #e4e8d6; --cut: #3f9b3f; --mower: #c0392b; --card: #fff;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #15180f; --fg: #e8ecdc; --muted: #9aa38c; --line: #2e3426;
|
||||
--grass: #262c1d; --cut: #4cb84c; --mower: #ff6b5b; --card: #1d2116;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.45 system-ui, sans-serif; }
|
||||
header { padding: 12px 16px; border-bottom: 1px solid var(--line); display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; }
|
||||
header h1 { font-size: 18px; margin: 0; }
|
||||
header .muted { color: var(--muted); font-size: 13px; }
|
||||
main { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; padding: 16px; max-width: 1200px; margin: 0 auto; }
|
||||
@media (max-width: 800px) { main { grid-template-columns: 1fr; } }
|
||||
#chat { display: flex; flex-direction: column; min-height: 60vh; }
|
||||
#log { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-bottom: 8px; }
|
||||
.msg { padding: 8px 12px; border-radius: 8px; background: var(--card); border: 1px solid var(--line); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.msg.user { align-self: flex-end; background: var(--cut); color: #fff; border: none; max-width: 85%; }
|
||||
.msg.error { border-color: var(--mower); color: var(--mower); }
|
||||
details { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
|
||||
details summary { cursor: pointer; color: var(--muted); font-size: 13px; }
|
||||
pre { margin: 6px 0 0; overflow-x: auto; font-size: 12.5px; }
|
||||
form { display: flex; gap: 8px; }
|
||||
input[type=text] { flex: 1; padding: 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: inherit; }
|
||||
button { padding: 10px 16px; border-radius: 8px; border: none; background: var(--cut); color: #fff; font: inherit; cursor: pointer; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
#yard-box { display: flex; flex-direction: column; gap: 8px; }
|
||||
#yard { width: 100%; aspect-ratio: 1; image-rendering: pixelated; border-radius: 8px; border: 1px solid var(--line); background: var(--grass); }
|
||||
#stats { color: var(--muted); font-size: 13px; }
|
||||
a { color: var(--cut); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>Lend the Mower</h1>
|
||||
<span class="muted">yard <b id="yard-name"></b> · <a id="new-yard" href="#">new yard</a> · <span id="status">connecting…</span></span>
|
||||
</header>
|
||||
<main>
|
||||
<section id="chat">
|
||||
<div id="log"></div>
|
||||
<form id="send">
|
||||
<input id="text" type="text" autocomplete="off" value="you can use this mower for the weekend">
|
||||
<button id="go" disabled>Send</button>
|
||||
</form>
|
||||
</section>
|
||||
<section id="yard-box">
|
||||
<canvas id="yard" width="400" height="400"></canvas>
|
||||
<div id="stats"></div>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module">
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const name = location.hash.slice(1) || crypto.randomUUID().slice(0, 8);
|
||||
if (!location.hash) history.replaceState(null, "", `#${name}`);
|
||||
$("yard-name").textContent = name;
|
||||
$("new-yard").href = `#${crypto.randomUUID().slice(0, 8)}`;
|
||||
addEventListener("hashchange", () => location.reload());
|
||||
|
||||
const css = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
|
||||
const arrows = ["▲", "▶", "▼", "◀"];
|
||||
|
||||
/** draws the yard: cut cells green, the mower an arrow for its heading */
|
||||
const drawYard = ({ width, height, x, y, heading, cut }) => {
|
||||
const canvas = $("yard");
|
||||
const cell = Math.floor(canvas.width / Math.max(width, height));
|
||||
const g = canvas.getContext("2d");
|
||||
g.fillStyle = css("--grass");
|
||||
g.fillRect(0, 0, canvas.width, canvas.height);
|
||||
g.fillStyle = css("--cut");
|
||||
for (const c of cut) {
|
||||
const [cx, cy] = c.split(",").map(Number);
|
||||
g.fillRect(cx * cell, cy * cell, cell, cell);
|
||||
}
|
||||
g.fillStyle = css("--mower");
|
||||
g.font = `${cell}px system-ui`;
|
||||
g.textAlign = "center";
|
||||
g.textBaseline = "middle";
|
||||
g.fillText(arrows[heading] ?? "●", x * cell + cell / 2, y * cell + cell / 2 + 1);
|
||||
$("stats").textContent = `${cut.length} of ${width * height} cells cut · mower at (${x}, ${y}) facing ${["north", "east", "south", "west"][heading]}`;
|
||||
};
|
||||
|
||||
const log = $("log");
|
||||
const scroll = () => (log.scrollTop = log.scrollHeight);
|
||||
const say = (text, cls = "") => {
|
||||
const div = document.createElement("div");
|
||||
div.className = `msg ${cls}`;
|
||||
div.textContent = text;
|
||||
log.append(div);
|
||||
scroll();
|
||||
return div;
|
||||
};
|
||||
const summarize = (output) => {
|
||||
if (!output || typeof output !== "object") return JSON.stringify(output);
|
||||
const calls = output.calls?.length;
|
||||
return [output.status, calls !== undefined ? `${calls} mower calls` : "", output.error ?? ""].filter(Boolean).join(" · ");
|
||||
};
|
||||
/** one code run: the code the model wrote, and what came of it */
|
||||
const codeBlock = (code) => {
|
||||
const d = document.createElement("details");
|
||||
const s = document.createElement("summary");
|
||||
s.textContent = "code: running…";
|
||||
const pre = document.createElement("pre");
|
||||
pre.textContent = code;
|
||||
d.append(s, pre);
|
||||
log.append(d);
|
||||
scroll();
|
||||
return { done: (text) => (s.textContent = `code: ${text}`) };
|
||||
};
|
||||
|
||||
/** renders a stored message, e.g. history sent on connect */
|
||||
const renderMessage = ({ role, parts = [] }) => {
|
||||
for (const p of parts) {
|
||||
if (p.type === "text" && p.text) say(p.text, role === "user" ? "user" : "");
|
||||
else if (p.type?.startsWith("tool-") && p.input?.code !== undefined) {
|
||||
const b = codeBlock(p.input.code);
|
||||
b.done(p.state === "output-error" ? `error: ${p.errorText}` : summarize(p.output));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/agents/neighbor/${encodeURIComponent(name)}`);
|
||||
let reply = null;
|
||||
const blocks = new Map();
|
||||
const setBusy = (busy) => ($("go").disabled = busy || ws.readyState !== WebSocket.OPEN);
|
||||
|
||||
ws.addEventListener("open", () => { $("status").textContent = "connected"; setBusy(false); });
|
||||
ws.addEventListener("close", () => { $("status").textContent = "disconnected; reload to reconnect"; setBusy(true); });
|
||||
ws.addEventListener("message", ({ data }) => {
|
||||
let msg;
|
||||
try { msg = JSON.parse(data); } catch (e) { console.warn("unparsed message", data, e); return; }
|
||||
if (msg.type === "cf_agent_state" && msg.state) drawYard(msg.state);
|
||||
else if (msg.type === "cf_agent_chat_messages" && Array.isArray(msg.messages)) {
|
||||
log.replaceChildren();
|
||||
msg.messages.forEach(renderMessage);
|
||||
} else if (msg.type === "cf_agent_use_chat_response") {
|
||||
if (msg.error) say(String(msg.body), "error");
|
||||
for (const line of String(msg.body ?? "").split("\n").filter(Boolean)) {
|
||||
let c;
|
||||
try { c = JSON.parse(line.replace(/^data: /, "")); } catch { continue; }
|
||||
if (c.type === "text-delta") {
|
||||
reply ??= say("");
|
||||
reply.textContent += c.delta;
|
||||
scroll();
|
||||
} else if (c.type === "tool-input-available") {
|
||||
reply = null;
|
||||
blocks.set(c.toolCallId, codeBlock(c.input?.code ?? JSON.stringify(c.input)));
|
||||
} else if (c.type === "tool-output-available") blocks.get(c.toolCallId)?.done(summarize(c.output));
|
||||
else if (c.type === "tool-output-error") blocks.get(c.toolCallId)?.done(`error: ${c.errorText}`);
|
||||
else if (c.type === "error") say(c.errorText ?? JSON.stringify(c), "error");
|
||||
}
|
||||
if (msg.done) { reply = null; setBusy(false); }
|
||||
}
|
||||
});
|
||||
|
||||
$("send").addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const text = $("text").value.trim();
|
||||
if (!text) return;
|
||||
say(text, "user");
|
||||
$("text").value = "";
|
||||
setBusy(true);
|
||||
reply = null;
|
||||
const id = crypto.randomUUID();
|
||||
ws.send(JSON.stringify({
|
||||
type: "cf_agent_use_chat_request",
|
||||
id,
|
||||
init: { method: "POST", body: JSON.stringify({
|
||||
trigger: "submit-message",
|
||||
messages: [{ id: `u-${id}`, role: "user", parts: [{ type: "text", text }] }],
|
||||
}) },
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -21,13 +21,27 @@ const headings = [
|
||||
[-1, 0], // west
|
||||
] as const;
|
||||
|
||||
/** a mower on a `width` × `height` yard, starting at `at`; pushing past an
|
||||
* edge wraps to the other side (6d) */
|
||||
export const makeMower = ({ width, height, at }: { width: number; height: number; at: { x: number; y: number } }) => {
|
||||
let { x, y } = at;
|
||||
let heading = 0;
|
||||
const cut = new Set<string>();
|
||||
const cutHere = () => cut.add(`${x},${y}`);
|
||||
/** where a mower is and what it has cut, as `"x,y"` cells; `heading` indexes north, east, south, west */
|
||||
export type Yard = Readonly<{
|
||||
width: number;
|
||||
height: number;
|
||||
x: number;
|
||||
y: number;
|
||||
heading: number;
|
||||
cut: readonly string[];
|
||||
}>;
|
||||
|
||||
/** a mower on a yard, picking up where `yard` left off; pushing past an
|
||||
* edge wraps to the other side (6d). `onMove` hears each move. */
|
||||
export const makeMower = (yard: Yard, onMove: (yard: Yard) => void = () => {}) => {
|
||||
const { width, height } = yard;
|
||||
let { x, y, heading } = yard;
|
||||
const cut = new Set(yard.cut);
|
||||
const view = (): Yard => ({ width, height, x, y, heading, cut: [...cut] });
|
||||
const cutHere = () => {
|
||||
cut.add(`${x},${y}`);
|
||||
onMove(view());
|
||||
};
|
||||
return {
|
||||
start() {
|
||||
heading = 0;
|
||||
@@ -41,6 +55,7 @@ export const makeMower = ({ width, height, at }: { width: number; height: number
|
||||
},
|
||||
turn() {
|
||||
heading = (heading + 1) % headings.length;
|
||||
onMove(view());
|
||||
},
|
||||
stop() {},
|
||||
cutCells: () => [...cut],
|
||||
|
||||
@@ -1,16 +1,44 @@
|
||||
/** @file The neighbor's harness as a Project Think agent, lent a mower. */
|
||||
import { Think } from "@cloudflare/think";
|
||||
import type { Connection } from "agents";
|
||||
import { createExecuteTool } from "@cloudflare/think/tools/execute";
|
||||
import { createWorkersAI } from "workers-ai-provider";
|
||||
|
||||
import { MAX_TOKENS, MODEL } from "./model.ts";
|
||||
import { MowerConnector } from "./mower-connector.ts";
|
||||
import { makeMower } from "./mower.ts";
|
||||
import { makeMower, type Mower, type Yard } from "./mower.ts";
|
||||
|
||||
type Env = { AI: Ai; LOADER: WorkerLoader };
|
||||
|
||||
export class Neighbor extends Think<Env> {
|
||||
#mower = makeMower({ width: 40, height: 40, at: { x: 20, y: 20 } });
|
||||
/** how often, at most, a mowing yard goes out to the page */
|
||||
const PUBLISH_MS = 200;
|
||||
|
||||
export class Neighbor extends Think<Env, Yard> {
|
||||
initialState: Yard = { width: 40, height: 40, x: 20, y: 20, heading: 0, cut: [] };
|
||||
|
||||
#mower: Mower | undefined;
|
||||
#pending: Yard | undefined;
|
||||
|
||||
/** the mower, back where the saved yard left it; its moves are saved and
|
||||
* broadcast at most every PUBLISH_MS */
|
||||
get #lent(): Mower {
|
||||
this.#mower ??= makeMower(this.state, (yard) => {
|
||||
const idle = this.#pending === undefined;
|
||||
this.#pending = yard;
|
||||
if (!idle) return;
|
||||
setTimeout(() => {
|
||||
const latest = this.#pending;
|
||||
this.#pending = undefined;
|
||||
if (latest) this.setState(latest);
|
||||
}, PUBLISH_MS);
|
||||
});
|
||||
return this.#mower;
|
||||
}
|
||||
|
||||
/** the yard is the mower's to change; pages only watch */
|
||||
validateStateChange(_next: Yard, source: Connection | "server") {
|
||||
if (source !== "server") throw Error("the yard changes only by mowing");
|
||||
}
|
||||
|
||||
getModel() {
|
||||
return createWorkersAI({ binding: this.env.AI })(MODEL);
|
||||
@@ -32,13 +60,13 @@ lend you something, put it to use, then tell me what you did.`;
|
||||
getTools() {
|
||||
return {
|
||||
execute: createExecuteTool(this, {
|
||||
connectors: [new MowerConnector(this.ctx, this.env, this.#mower)],
|
||||
connectors: [new MowerConnector(this.ctx, this.env, this.#lent)],
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** the cells the mower has cut, as `"x,y"` */
|
||||
cutCells() {
|
||||
return this.#mower.cutCells();
|
||||
return this.#lent.cutCells();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"name": "good-fences3",
|
||||
"main": "./src/worker.ts",
|
||||
"compatibility_date": "2026-10-01",
|
||||
"compatibility_flags": ["nodejs_compat"],
|
||||
// the chat page; other paths fall through to the Worker
|
||||
"assets": { "directory": "./public" },
|
||||
"ai": { "binding": "AI" },
|
||||
// Dynamic Workers: deploying this binding takes the Workers Paid plan
|
||||
"worker_loaders": [{ "binding": "LOADER" }],
|
||||
"durable_objects": {
|
||||
"bindings": [{ "name": "Neighbor", "class_name": "Neighbor" }]
|
||||
},
|
||||
"exports": {
|
||||
"Neighbor": { "type": "durable-object", "storage": "sqlite" },
|
||||
// codemode's runtime, a facet of the agent's DO
|
||||
"CodemodeRuntime": { "type": "durable-object", "storage": "sqlite" }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user