Compare commits

...
20 Commits
Author SHA1 Message Date
kosmos 78fdec4f49 fix(daemon): lease a forge turn for an hour, not ten minutes
android / release (pull_request) Skipped
ci / checks (pull_request) Successful in 1m3s
ci / test (pull_request) Successful in 39s
ci / chart (pull_request) Successful in 5s
ci / docker (pull_request) Successful in 1m30s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
ci / web (pull_request) Successful in 13s
android / debug (push) Successful in 2m13s
android / release (push) Successful in 2m4s
ci / checks (push) Successful in 1m4s
ci / test (push) Successful in 44s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m30s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m33s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
android / debug (pull_request) Successful in 3m48s
ci / publish-edge-chart (push) Successful in 3s
The forge dispatcher was assembled on `DispatcherConfig::default()`,
whose ten-minute lease TTL is the spec's example value, sized for a
single agent step. A forge turn is not a step: it clones the repo, reads
it, and may build and test a fix. Nothing renews the lease once the turn
is under way — `poll_inbox` renews but is called once, at the start, and
the commit hook between tool calls checkpoints, which fails on a lapsed
lease rather than extending it — so the TTL is a hard ceiling on a whole
turn.

Crossing it is silent: the turn dies on its next tool call, the driver's
own checkpoint and release then report `Expired`, and the key ends with
no outcome recorded, indistinguishable from a pass that found nothing.

Give the forge lane its own timing — the library defaults with an
hour-long TTL, the same choice the interactive and jobs lanes already
make — and use it in both shapes (`--once` included).
2026-11-22 01:13:40 +00:00
kosmos c65f7fe962 fix(forge): read a GitHub notification id as a string or a number
ci / web (pull_request) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
android / debug (push) Successful in 2m34s
android / release (push) Successful in 2m4s
ci / checks (push) Successful in 1m4s
ci / web (push) Successful in 13s
ci / test (push) Successful in 1m5s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m28s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m33s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
android / release (pull_request) Skipped
ci / test (pull_request) Successful in 38s
ci / chart (pull_request) Successful in 5s
ci / checks (pull_request) Successful in 1m3s
ci / docker (pull_request) Successful in 1m28s
ci / publish-edge-chart (push) Successful in 3s
android / debug (pull_request) Successful in 2m25s
The notifications feed sends `id` as a JSON string (`"27210544329"`),
unlike every other row this adapter decodes, so `WireNotification`'s
`Option<i64>` refused one real row and failed the whole page. The account
watch has been stuck on 'error decoding response body' since the first
notification arrived (82 consecutive failures at the time of writing).

`lenient_id` accepts either shape; a non-numeric string is still a loud
parse error rather than a dropped row. The regression test is the row
captured live.
2026-11-22 00:01:01 +00:00
kosmos 9c13455f35 feat(claw): a mention of the daemon is an ask, not a phone buzz
android / release (pull_request) Skipped
ci / checks (pull_request) Successful in 1m10s
ci / test (pull_request) Successful in 37s
ci / chart (pull_request) Successful in 6s
ci / docker (pull_request) Successful in 1m34s
ci / web (pull_request) Successful in 14s
ci / publish-edge-chart (pull_request) Skipped
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
android / debug (push) Successful in 3m0s
android / release (push) Successful in 2m6s
ci / checks (push) Successful in 1m9s
ci / test (push) Successful in 42s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m28s
ci / web (push) Successful in 12s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m33s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 8s
android / debug (pull_request) Successful in 2m51s
ci / publish-edge-chart (push) Successful in 3s
The notifications feed triaged a GitHub `mention` as `Triage::Surface`:
the human hears about it, no agent runs. That verdict is right for a
consumer that only notifies — a mention of somebody else is not an
assignment — but this daemon is the party named. Somebody typed
`@handle` on a thread and is waiting for an answer, which is the same
ask an assignment is.

The bug that follows is silent: the surface arm never feeds the
dispatcher, so the thread is never dispatched and the mention is never
answered. Nothing looks broken; the phone buzzed.

`claw_triage` keeps the shared vocabulary as the base and upgrades
this one reason, the seam `triage` names for consumers ('classify is
the default, not a mandate'). Every other reason keeps its verdict, so
the co-edit that pinned those tests still holds.
2026-11-21 22:02:47 +00:00
vhaudiquet 6abb1436b5 feat(android): render chips from the span record, not the mark scan
android / debug (push) Successful in 2m45s
ci / checks (push) Successful in 1m0s
ci / docker (push) Successful in 1m23s
ci / web (push) Successful in 11s
android / release (push) Successful in 2m10s
ci / test (push) Successful in 38s
ci / chart (push) Successful in 5s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m25s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
ci / publish-edge-chart (push) Successful in 3s
The phone was the last surface reading chips as paired U+FFFC marks
in the text: a web user's staged paste rendered as its raw payload
inline, and the mark scan stayed the only parse. Now the row's chip
record does the work. `user_message`'s `pastes` spans parse beside the
text (the session annotation's own shape, absent on every row that
predates it), the controller carries them through the fold's dedupe
guard, and the render slices each chip out of the plain text at the
record's UTF-8 offsets — one walk maps every character boundary, so
a surrogate-heavy draft still lands exactly and a span that splits a
character skips whole rather than cutting one in half. A row without
a record still scans the mark form, exactly as before.

The composer still sends plain text only — this is the read side; the
phone never staged text chips even in the mark era.

Verified as CI does (assembleDebug, lintDebug) plus a JVM harness
running the verbatim slicing code against the daemon's own e2e record
numbers, surrogates and seams included.
2026-11-20 01:18:49 +01:00
vhaudiquet c5bf168eed feat: chips travel as span records, not mark embeds
android / debug (push) Successful in 2m19s
android / release (push) Successful in 3m0s
ci / checks (push) Successful in 1m11s
ci / test (push) Successful in 38s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m27s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m30s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 14s
ci / publish-edge-chart (push) Successful in 4s
The claw's wire carried chips only as U+FFFC-payload-U+FFFC marks
written into the text — the very encoding 0.4.0's fold migrated at
the provider seam. Now the record rhema-core defined is the wire's
own: a message's pasted payloads ride the POST body's `pastes` array
beside the plain draft, the fold composes the plain form and measures
each chip's PasteSpan, and the `user_message` echo carries text plus
`pastes` — the session annotation's own shape — while the turn's
question carries the span note into the checkpoint, shifted by the
exact bytes any framing prefix adds.

The web client mints and renders the new record: the composer sends
draft and payloads separately, the optimistic row composes the same
plain text and spans the fold will record (so the echo dedupes), and
the render slices the text at the record's byte offsets. Rows
recorded before spans arrived still parse the mark form — as does
every arrival that still mints it, including every surface the shim
or an older client feeds.

The phone is one of those: it parses chips by scanning marks, and
kotlinx ignores the new field, so it reads spans-less rows exactly
as before; adopting span records for its own rows is a follow-up.
2026-11-20 00:41:41 +01:00
vhaudiquet df260fd9a8 build: move the claw to rhema 0.4.0
android / debug (push) Successful in 3m34s
android / release (push) Successful in 2m2s
ci / checks (push) Successful in 1m53s
ci / test (push) Successful in 1m55s
ci / docker (push) Successful in 1m32s
ci / chart (push) Successful in 6s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m30s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 8s
ci / publish-edge-chart (push) Successful in 3s
The framework 0.4.0 split the toolkit: rhema-agent-tools becomes
rhema-bash plus rhema-prompt, and the facade crate is deleted from
the workspace this time, so the 0.3 facades never publish. The
driver changes name with its types: rhema-coding-agent and its
CodingAgent, CodingAgentConfig, and CodingAgentError become
rhema-host-agent with HostAgent, HostAgentConfig, and HostAgentError.
The claw imports the split crates directly, which drops its own
vision once-lock: rhema-bash's wire already caches the process-wide
answer.

The paste expansion moved off the provider seam. Chips travel as the
message's spans note now, and ExpandPastes is deleted: the dispatch
input migrates its embedded form into plain text plus the note at
run_turn, and a restashed session migrates the same way on restore,
one rewrite on the way in exactly as the driver's from_session does.
The transcript events keep the raw chip form, the record the web UI
owns, and a migration test pins the restore path.

max_turn_steps is NonZeroU32, the engine's own budget shape: a config
naming zero is refused at load instead of cutting every round dead.
The engine's Event and the sandbox error enum are non-exhaustive
now, so the hub sink and the protocol error map carry wildcard arms
that drop and fail in-band the way their neighbors do.

The claw's own version travels with the framework, as the 0.3.0 move
carried 0.2.3 to 0.3.0: the workspace and the chart base become
0.4.0, so the edge channel's pre-releases order above the 0.3.x line.

fmt, clippy with -D warnings over all features and targets, the
workspace tests, and the doc build pass.
2026-11-19 23:25:16 +01:00
vhaudiquet ed645d1faf fix(web/claw): keep the stream watchdog quiet on a tab switch
android / debug (push) Successful in 2m29s
android / release (push) Successful in 2m37s
ci / checks (push) Successful in 1m11s
ci / test (push) Successful in 43s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m32s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m39s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 14s
ci / publish-edge-chart (push) Successful in 4s
A hidden tab throttles timers and can stall the SSE reader. The 45s
silence watchdog kept counting that time, aborted the stream, and pushed
"the event stream went quiet" on every tab switch even though the
connection was fine.

The watchdog now pauses while the page is hidden and re-arms from zero
when it becomes visible. The attempt also remembers whether it crossed a
hidden period: if the browser held or dropped the connection there, the
reconnect stays silent. A keep-alive or frame clears that mark, so a
stream that really dies while visible still reports itself.

Tested in headless Chromium against the dev mock: 50s hidden, then
visible, no notice, and the stream went back to live.
2026-11-18 23:59:01 +01:00
vhaudiquet 51456f5b4c build: bump the chart base version past the 0.2.3 release
android / debug (push) Successful in 2m37s
android / release (push) Successful in 2m21s
ci / checks (push) Successful in 1m14s
ci / test (push) Successful in 54s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m26s
ci / web (push) Successful in 14s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m31s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 10s
ci / publish-edge-chart (push) Successful in 5s
CI publishes every main push as a timestamped pre-release of the chart's
base version. The base stayed at 0.1.0 through the 0.3.0 framework move,
but the package repository also holds a 0.2.3 chart from the old release
line. SemVer ranks 0.2.3 above every 0.1.0 pre-release, so a HelmRelease
with `>=0.1.0-0` resolves to 0.2.3 and never sees a newer edge chart.

The base is 0.3.0 now, matching the workspace version. Edge charts sort
above 0.2.3 again, and the release tag check already expects 0.3.0.
2026-11-18 21:54:19 +01:00
vhaudiquet ea4810a576 feat(claw): choose where bash runs, this host or a remote sandbox
android / debug (push) Successful in 2m42s
android / release (push) Successful in 5m2s
ci / checks (push) Successful in 1m22s
ci / test (push) Successful in 1m5s
ci / chart (push) Successful in 7s
ci / docker (push) Successful in 1m42s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m34s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 14s
ci / publish-edge-chart (push) Successful in 4s
The daemon's `bash` always ran on its own host. A deployment that wants
the shell isolated, or on a machine with the project's toolchain, had no
way to say so, and the web settings had no surface for it.

A sandbox choice now persists in the settings table, and the daemon can
be seeded from `sandbox` in claw.yaml. `local` keeps the existing shell;
`http` wraps `rhema-sandbox-http` in a `ShellSandbox` and gives every
handler a `ShellTools` built over it. Chat turns, forge turns, and coding
jobs all read the choice per dispatch, so a switch applies on the next
turn without a restart.

A remote sandbox starts empty. The first command for a workspace probes
`/workspace` and, when it is empty, sends the host workspace as a tarball
through the protocol's seed route. Later edits stay in the sandbox; the
claw does not copy them back.

The web settings gain a System > Sandbox page: the two kinds, the URL and
a write-only token, a forget-token action, and the effective workspace.
`GET /v1/sandbox` never returns the token; `PUT` validates and persists
the choice.

Tests: the sandbox state and config validation, the HTTP route round
trip, and a remote turn that seeds a fresh sandbox and runs its shell
there. fmt, clippy with -D warnings, the workspace tests, and the web
typecheck and build pass.
2026-11-18 21:00:50 +01:00
vhaudiquet 68671c76ce build: move the claw to rhema 0.3.0
android / debug (push) Successful in 2m51s
android / release (push) Successful in 2m37s
ci / checks (push) Successful in 1m32s
ci / test (push) Successful in 1m0s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m33s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m32s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 14s
ci / publish-edge-chart (push) Successful in 4s
The framework releases 0.3.0, so every rhema dependency moves with it: the workspace version, the daemon's crates, and the two integrations. The only new transitive package is webpki-roots, pulled by the provider crates' TLS stack.

The agent constructors changed shape. CodingAgentConfig::new takes the provider, model, workspace, and approval, and keeps both handles: CodingAgent::new and CodingAgent::from_session take the config alone, and turn no longer takes an approval argument. The claw's forge and job paths build one config each and pass AllowAll there, the policy every turn ran under before.

The vision and mcp tests build their config through the same constructor, so they hand it a MockProvider.

fmt, clippy with -D warnings, the workspace tests, and a locked check pass.
2026-11-18 20:25:22 +01:00
vhaudiquet c56f544993 feat(web/claw): render the reply, not the tool calls or the thinking
android / debug (push) Successful in 2m17s
android / release (push) Successful in 2m5s
ci / checks (push) Successful in 1m0s
ci / test (push) Successful in 37s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m21s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m23s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 13s
ci / publish-edge-chart (push) Successful in 3s
The web transcript was built to mirror the TUI: every tool call as a
shell line or a glyph row, the thinking trace between them, each at the
position the stream delivered it. That is the right shape for a
terminal session you sit and watch. On the web it reads as machinery in
front of the answer, and the answer is what the page is for.

`TurnEntries` now keeps only the two entries the reader must handle: a
consent card (the agent is waiting on an answer, so hiding it would
stall the turn) and an attachment card (the file it handed over).
Everything else in the turn renders as the reply, through
`AppMarkdown`.

The mirror in `useTranscript` still folds tool and thinking events; only
the render ignores them. Replay, the pending-echo dedupe and consent
placement keep working unchanged, and the bottom-pin watch loses the
thinking-length term it only needed while that block took height.

`TurnToolRow` had no other caller and goes with it.
2026-11-17 23:37:27 +01:00
vhaudiquet 268917646e docs: add the tools spec, carried from the rhema repository
android / debug (push) Successful in 2m12s
android / release (push) Successful in 2m3s
ci / checks (push) Successful in 59s
ci / test (push) Successful in 40s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m26s
ci / web (push) Successful in 15s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m23s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
ci / publish-edge-chart (push) Successful in 4s
The spec describes this tree now: ClawExtension, the tools/ project
(contract, common, notify), the daemon's axum router. It stayed
behind when the claw cut loose, and a design record belongs beside
its subject.
2026-11-17 23:16:41 +01:00
kosmos d74b1c40df feat(claw): answer a thread only when somebody addresses the daemon
android / release (pull_request) Skipped
ci / checks (pull_request) Successful in 1m12s
ci / docker (pull_request) Successful in 1m22s
ci / web (pull_request) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
ci / test (pull_request) Successful in 39s
ci / chart (pull_request) Successful in 5s
android / release (push) Successful in 2m2s
ci / checks (push) Successful in 59s
ci / test (push) Successful in 37s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m22s
android / debug (push) Successful in 3m51s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m29s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
android / debug (pull_request) Successful in 4m7s
ci / publish-edge-chart (push) Successful in 4s
A repo watch saw *every* issue, pull request, review and comment on the
repository, and the handler treated each dispatch as work to do: a
snapshot fetch, a coding-agent turn, and a comment posted back. On a
repository with any traffic at all that is the wrong end of the
question — watching a repo is not volunteering to answer it — and it is
also how a daemon ends up talking to itself, since its own replies are
news too.

The dispatch now starts with a mention gate. A thread runs when:

- it delivered a triaged notification — assigned, review requested,
  @-mentioned: the notifications feed already adjudicated that one; or
- one of its plain events names the handle the daemon speaks as
  (`@kosmos`), written by anybody *but* the daemon.

Everything else is drained and dropped: no snapshot, no model call, no
comment. The outcome is `Superseded` — RSD's vocabulary has no "nothing
was asked", and the closest is that the work the event names is not
this daemon's.

Recognizing its own name took a little plumbing. The credential a watch
resolves carries a login only when an account identity supplied the
token; a token pasted into a watch row, or a forge environment variable,
names nobody — and that is the deployment the gate must not go inert on.
So `Forge::viewer_login` is the backend's own answer to "who am I", from
its `/user` (Gitea and GitHub spell it `login`, GitLab `username`), with
a `None` default for backends that cannot say; the handler asks at most
once per credential and keeps the answer beside the cached client. A
forge that will not name the credential leaves the gate *open*, with a
warning in the log: a filter that silently mutes a watch is worse than
one that occasionally over-answers.

The actor check is load-bearing for the same reason the gate exists: a
reply quotes the mention it answers, so "addressed by name" alone would
have the daemon answer itself, forever.

Tests: unit tests for the gate (name in any case, own comment, no body,
notification, unnamed credential), one end-to-end test per behaviour —
a mention runs one turn and posts one reply; a thread's own chatter runs
nothing and posts nothing; the daemon's own reply does not reopen the
gate — plus `viewer_login` against all three backends.
2026-11-17 22:41:46 +01:00
vhaudiquet 504330b1b5 test(claw): the github mock answers since, as the forge does
android / debug (push) Successful in 2m24s
android / release (push) Successful in 3m5s
ci / checks (push) Successful in 1m6s
ci / test (push) Successful in 42s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m23s
ci / web (push) Successful in 14s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m28s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
android / release (pull_request) Canceled after 0s
ci / checks (pull_request) Canceled after 0s
ci / test (pull_request) Canceled after 0s
ci / chart (pull_request) Canceled after 0s
ci / docker (pull_request) Canceled after 0s
ci / web (pull_request) Canceled after 0s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Canceled after 0s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Canceled after 0s
ci / publish-edge-chart (pull_request) Canceled after 0s
ci / publish-edge-chart (push) Successful in 3s
android / debug (pull_request) Canceled after 0s
The fresh-watch pass now seeds its cursor at *now*, and the issues feed
is where GitHub applies `since` server-side. The mock always answered
the whole history, so the seeding pass fed an issue the real forge would
have filtered out and the new "a fresh watch seeds its cursor" assertion
saw one event.

The mock now returns the issue row only for the rewound cursor the test
sets, and nothing for any other `since`.
2026-11-17 22:38:41 +01:00
kosmos b6327a458f fix(claw): a repo watch resumes from its durable cursor, or starts now
android / release (pull_request) Skipped
ci / checks (pull_request) Successful in 1m0s
ci / test (pull_request) Failing after 36s
ci / chart (pull_request) Successful in 5s
ci / docker (pull_request) Successful in 1m23s
ci / web (pull_request) Successful in 14s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
android / debug (pull_request) Successful in 2m16s
The watcher kept one cursor per repo in a `Mutex<HashMap>`, so every
daemon restart began with no cursor — and `Watcher::poll` reads "no
cursor" as "feed everything the forge returns". A restart therefore
replayed the repository's whole history: every old thread a dispatch, and
every dispatch a comment posted on a thread nobody had just touched. The
dispatcher's dedup lane does not save this: it dedups against the pending
inbox, and a drained event re-ingests clean.

The cursor is a row now (`watch_cursors`, beside `watch_health`, same
scope/forge/subject key), written after every successful poll and read
before every poll, so a restart resumes where the last pass stopped.

A watch with no cursor yet — newly added, or added to a repository full of
history — starts at *now* rather than at the beginning: a watch reports
news, and history is not news. The seed is written before the poll, so a
forge that is down cannot walk the start line forward on every pass and
lose the news arriving in between. Removing a watch forgets its cursor
too, so a re-add seeds afresh instead of resuming into a backlog.

`Watcher::poll_since` is the seam the daemon needs to pass a cursor it
keeps itself; `Watcher::poll` keeps its in-memory behaviour unchanged.
`Timestamp::from_epoch_millis` spells an instant the way the forges spell
theirs, which is what a seed is.

Tests: the first pass feeds nothing and asks from the seeded instant; a
second pass resumes from it; the cursor moves only forward per watch and
dies with the watch. `e2e`/`continuity`/`http` seed an established watch,
since their subject is the dispatch, not the bootstrap.
2026-11-14 16:58:33 +00:00
kosmos 2f6c369e02 fix(forge): a gitea comment names its thread without issue_url
`comment_event` read the thread number from `issue_url` alone and failed
the whole poll when it could not. The instance behind git.vhaudiquet.fr
sends `issue_url: ""` on every row of the repo-wide `/issues/comments`
feed, so the first comment row failed the pass with

    malformed forge response: comment issue_url without a thread number:

and kept failing on every poll since the watch was created — 5296
consecutive failures, no event ever reported, no comment, no pull
request, nothing. The feed being broken was invisible: a watch that has
never polled once looks exactly like a quiet repository.

The number now comes from the first URL that carries one
(`issue_url`, then `pull_request_url`, then `html_url`), and a fragment is
dropped first: a comment's `html_url` points at the comment
(`…/pulls/1#issuecomment-164`), not at its thread. `is_pr` reads the same
three URLs, so a PR comment whose `issue_url` is blank still lands on the
pull request's sequence.

A row with no number anywhere is still a loud parse error — the
fallbacks must not degrade into a silently skipped event.
2026-11-14 16:58:25 +00:00
vhaudiquet 00037993af chore: carry dev.sh over — the claw+UI debug loop from the old tree
android / debug (push) Successful in 2m20s
android / release (push) Successful in 2m13s
ci / checks (push) Successful in 1m4s
ci / test (push) Successful in 37s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m22s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m29s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
ci / publish-edge-chart (push) Successful in 4s
Unchanged: the paths are root-relative, so the script works as-is in
the standalone workspace.
2026-11-12 19:38:08 +01:00
vhaudiquet 95e2fcfd57 ci: port the rust, chart, docker, web and edge-publish gates from the rhema repository
android / debug (push) Successful in 2m20s
ci / checks (push) Successful in 2m1s
ci / test (push) Successful in 57s
ci / chart (push) Successful in 6s
ci / web (push) Successful in 13s
ci / docker (push) Successful in 1m44s
android / release (push) Successful in 2m7s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m25s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 10s
ci / publish-edge-chart (push) Successful in 3s
The android workflow came over with the tree; the rest of the old
repo's CI was framework-shaped. What the claw needs is the rust
gate (fmt, clippy, release build with the binary artifact, offline
tests), the chart lint/render suite, the daemon image smoke test,
the web bundle, and the edge + release publishing pair (latest/sha
images on main, exact-version images and chart on a v* tag).

Dropped on the way: the crates.io publish-order and claw-boundary
checks (nothing here publishes to crates.io; the boundary is
enforced by the tree layout now), the cloudflare wasm gate, the
binary release legs, and the manifest/crates.io release jobs — all
framework concerns that stayed in the rhema repository.

Release tags are checked against the workspace version by a
verify-tag job that the image legs wait on.
2026-11-12 19:29:32 +01:00
vhaudiquet 12ba97c8f1 build: resolve the image manifests from crates.io
The Dockerfiles copied every framework crate's manifest because the
old root workspace path-patched crossterm and carried in-tree
resolution. The claw resolves from crates.io now, so the builder
copies only the claw's own manifests, and the vendored-crossterm
COPY (and its explanation) is gone.
2026-11-12 17:43:40 +01:00
vhaudiquet 552a76ba99 build: the claw stands alone
The claw product (the daemon, the feed integrations, the client
tools, and the web and android trees) extracted from the framework
repository, keeping its history. The framework crates the product
pulls are all on crates.io at 0.2.3, so the in-tree path
dependencies became versions and the workspace resolves without the
framework checkout.
2026-11-12 17:43:08 +01:00
59 changed files with 8030 additions and 497 deletions

No files matched your search

+271
View File
@@ -0,0 +1,271 @@
name: ci
on:
push:
pull_request:
env:
CARGO_TERM_COLOR: always
OWNER: vhaudiquet
jobs:
# Fast checks + release build of the Rust workspace.
checks:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@v4
# Installs the toolchain pinned in rust-toolchain.toml.
- uses: actions-rust-lang/setup-rust-toolchain@v1
# reqwest's default TLS links openssl; rusqlite's bundled SQLite
# needs a C compiler (present on the runner image, kept explicit
# next to the rest).
- name: Install native build dependencies
run: sudo apt-get update && sudo apt-get install -y pkg-config libssl-dev
- name: Format
run: cargo fmt --all -- --check
- name: Clippy (warnings are errors)
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
- name: Build (release)
run: cargo build --release --workspace
- name: Upload the claw binary
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
name: rhema-claw-linux-amd64
path: target/release/rhema-claw
if-no-files-found: error
retention-days: 14
test:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@v4
- uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Install native build dependencies
run: sudo apt-get update && sudo apt-get install -y pkg-config libssl-dev
# The offline-suite rule is load-bearing here: no test talks to the
# network, so the runner needs nothing beyond the toolchain.
- name: Test
run: cargo test --workspace --all-features
# The deploy chart: lint, render every supported shape, validate the
# result against the Kubernetes schemas — and prove the single-node
# invariant is enforced rather than hoped for.
chart:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@v4
- name: Install helm and kubeconform
run: |
curl -fsSL https://get.helm.sh/helm-v3.16.4-linux-amd64.tar.gz \
| tar -xz -C /tmp
sudo install /tmp/linux-amd64/helm /usr/local/bin/helm
curl -fsSL https://github.com/yannh/kubeconform/releases/download/v0.6.7/kubeconform-linux-amd64.tar.gz \
| tar -xz kubeconform
sudo install kubeconform /usr/local/bin/kubeconform
- name: Lint
run: helm lint deploy/helm/rhema-claw --strict --set token=ci-render-token
- name: Render and validate
run: |
check() {
helm template test "$@" --set token=ci-render-token | kubeconform -strict -summary
}
# The shapes: defaults (persistent), the disposable one
# (emptyDir), the recommended secret path, and a seeded watch.
# The token rides every render: the daemon binds all interfaces
# in-cluster and refuses a non-loopback surface without one.
check deploy/helm/rhema-claw
check deploy/helm/rhema-claw --set persistence.enabled=false
check deploy/helm/rhema-claw --set secret.existingSecret=rhema-claw-secrets
check deploy/helm/rhema-claw --set config.watches[0].forge=github --set config.watches[0].repo=acme/widgets
# The state layout is pinned to the mounted volume regardless of
# values, and the listener must not be loopback inside a pod.
render=$(helm template test deploy/helm/rhema-claw --set token=ci-render-token)
grep -q "db: /data/claw.db" <<<"$render"
grep -q "workspace_root: /data/workspaces" <<<"$render"
grep -q "listen: 0.0.0.0:7799" <<<"$render"
# The token is a render-time failure: an unguarded daemon with a
# wide bind refuses to start, and the chart says so earlier.
if helm template test deploy/helm/rhema-claw \
> /dev/null 2>&1; then
echo "an empty token must not render"; exit 1
fi
# The ingress shapes: host+class, host+TLS, and the two
# refusals — an enabled ingress without a host, and TLS without
# a certificate secret. Bearer tokens cross this ingress; neither
# may render silently.
check deploy/helm/rhema-claw --set ingress.enabled=true \
--set ingress.host=claw.example.com --set ingress.className=nginx
check deploy/helm/rhema-claw --set ingress.enabled=true \
--set ingress.host=claw.example.com --set ingress.tls.enabled=true \
--set ingress.tls.secretName=claw-tls
if helm template test deploy/helm/rhema-claw \
--set token=ci-render-token --set ingress.enabled=true > /dev/null 2>&1; then
echo "ingress without a host must not render"; exit 1
fi
if helm template test deploy/helm/rhema-claw \
--set token=ci-render-token --set ingress.enabled=true --set ingress.host=claw.example.com \
--set ingress.tls.enabled=true > /dev/null 2>&1; then
echo "tls without a secret must not render"; exit 1
fi
# The invariant is a render-time failure: the claw is single-node
# by design (one SQLite store, one dispatcher), and the chart is
# where that is enforced.
if helm template test deploy/helm/rhema-claw \
--set replicaCount=2 --set token=ci-render-token > /dev/null 2>&1; then
echo "replicaCount 2 must not render"; exit 1
fi
# The daemon's container image: build it, then prove the binary boots
# and serves /healthz inside it — config parsing, the state dirs, the
# keyless backend path, the dynamic linking. The image carries bash but
# no curl/wget, so the probe rides bash's /dev/tcp.
docker:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@v4
- name: Build image
run: docker build -f deploy/docker/claw.Dockerfile -t rhema-claw:ci .
- name: Smoke test
run: |
docker rm -f rhema-claw || true
trap 'docker rm -f rhema-claw || true' EXIT
# The llama-cpp backend boots keyless: no credentials are needed
# to prove the daemon serves. All state goes to /tmp so the
# smoke never depends on volume ownership.
docker run -d --name rhema-claw \
-e XDG_STATE_HOME=/tmp/state \
--entrypoint /bin/bash rhema-claw:ci -c '
mkdir -p /tmp/ws /tmp/state
printf "provider: llama-cpp\ndb: /tmp/claw.db\nworkspace_root: /tmp/ws\nlisten: 127.0.0.1:7799\n" > /tmp/claw.yaml
exec /usr/local/bin/rhema-claw --config /tmp/claw.yaml'
ok=0
for i in $(seq 1 30); do
# The request needs the full header terminator, and the read
# needs its own timeout: an accepted-but-unanswered probe
# would hang the exec, not fail it.
if docker exec rhema-claw bash -c \
'exec 3<>/dev/tcp/127.0.0.1/7799 && printf "GET /healthz HTTP/1.0\r\n\r\n" >&3 && timeout 5 grep -q ok <&3'; then
ok=1; break
fi
sleep 1
done
if [ "$ok" != 1 ]; then
docker logs rhema-claw
exit 1
fi
docker rm -f rhema-claw
# The web UI: install and produce the static bundle — the artifact an
# ingress serves next to /v1.
web:
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@v4
- name: Set up Node
run: |
curl -fsSL https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-x64.tar.xz \
| sudo tar -xJ -C /usr/local --strip-components=1
node --version
- name: Install dependencies
working-directory: web/claw
run: npm install
- name: Build
working-directory: web/claw
run: npm run build
# The edge channel: a main push that passed everything above ships
# the two deployable images as a rolling latest + sha pair. Release
# publishing (exact versions, the stable pin) lives in release.yaml.
# The claw image is rebuilt here for the registry even though the
# docker job above just built and smoked it: no artifact hand-off is
# worth the plumbing for a build this cheap.
publish-edge-images:
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main'
needs: [checks, test, chart, docker, web]
runs-on: ubuntu-latest
strategy:
matrix:
include:
- dockerfile: deploy/docker/claw.Dockerfile
image: rhema-claw
- dockerfile: deploy/docker/ui.Dockerfile
image: rhema-claw-ui
steps:
- name: Checkout repository
uses: https://gitea.com/actions/checkout@v4
- name: Log in to container registry
uses: docker/login-action@v3
with:
registry: https://git.vhaudiquet.fr
username: ${{ gitea.actor }}
password: ${{ secrets.PACKAGES_TOKEN }}
- name: Build and push image
uses: docker/build-push-action@v6
with:
context: .
file: ${{ matrix.dockerfile }}
push: true
# The edge pair: rolling latest, and the sha pin the chart's
# appVersion resolves to.
tags: |
git.vhaudiquet.fr/${{ env.OWNER }}/${{ matrix.image }}:latest
git.vhaudiquet.fr/${{ env.OWNER }}/${{ matrix.image }}:${{ gitea.sha }}
# The edge chart lands only once its images are in the registry: the
# chart's default image tag is appVersion, and appVersion here is
# this exact commit. The version rides the base version + a timestamp
# (ordered; SemVer pre-release rules allow no dots).
publish-edge-chart:
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main'
needs: publish-edge-images
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: https://gitea.com/actions/checkout@v4
- name: Install Helm
uses: azure/setup-helm@v5
- name: Update Chart version and appVersion
run: |
BASE_VERSION=$(grep '^version:' deploy/helm/rhema-claw/Chart.yaml | awk '{print $2}')
TIMESTAMP=$(date -u +"%Y%m%d-%H%M%S")
sed -i "s/^version:.*/version: \"${BASE_VERSION}-${TIMESTAMP}\"/" deploy/helm/rhema-claw/Chart.yaml
sed -i "s/^appVersion:.*/appVersion: \"${{ gitea.sha }}\"/" deploy/helm/rhema-claw/Chart.yaml
- name: Lint Helm chart
run: helm lint deploy/helm/rhema-claw
- name: Package Helm chart
run: helm package deploy/helm/rhema-claw
- name: Push Helm chart to Gitea registry
run: |
TOKEN=$(echo -n "${{ secrets.PACKAGES_TOKEN }}" | tr -d '\n')
curl --fail --user "${{ gitea.actor }}:${TOKEN}" \
-X POST \
--upload-file rhema-claw-*.tgz \
"https://git.vhaudiquet.fr/api/packages/${{ env.OWNER }}/helm/api/charts"
+110
View File
@@ -0,0 +1,110 @@
# The release channel: a v* tag ships the exact-version images (plus
# the sha pin the chart's appVersion resolves to) and the exact-version
# chart. Edge publishing on every main push lives in ci.yml. Release
# candidates (a v* tag with a prerelease suffix, v0.2.0-rc1) publish
# nothing. The daemon crate itself is `publish = false`, so no
# crates.io leg runs here: the crates the claw pulls live in the rhema
# repository's release channel.
name: release
on:
push:
tags:
- "v*"
permissions:
contents: read
packages: write
env:
REGISTRY: git.vhaudiquet.fr
OWNER: vhaudiquet
jobs:
verify-tag:
# cargo build ships whatever the manifest declares, regardless of
# the tag: a mismatch must fail loudly instead of shipping the
# wrong version under the release tag.
runs-on: ubuntu-latest
steps:
- name: Check the tag matches the workspace version
run: |
crate_version="$(grep -m1 '^version =' Cargo.toml | awk -F'"' '{print $2}')"
tag_version="${GITHUB_REF_NAME#v}"
if [ "$crate_version" != "$tag_version" ]; then
echo "tag $GITHUB_REF_NAME does not match workspace version $crate_version" >&2
exit 1
fi
build-and-push-release-images:
# The same two deployable images as the edge channel, tagged for the
# release: the exact version, the rolling stable pin, and the sha
# the chart's appVersion resolves to.
if: ${{ !contains(gitea.ref_name, '-') }}
needs: verify-tag
runs-on: ubuntu-latest
strategy:
matrix:
include:
- dockerfile: deploy/docker/claw.Dockerfile
image: rhema-claw
- dockerfile: deploy/docker/ui.Dockerfile
image: rhema-claw-ui
steps:
- name: Checkout repository
uses: https://gitea.com/actions/checkout@v4
- name: Log in to container registry
uses: docker/login-action@v3
with:
registry: https://git.vhaudiquet.fr
username: ${{ gitea.actor }}
password: ${{ secrets.PACKAGES_TOKEN }}
- name: Compute the release version (the tag strips the v)
id: ver
run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
- name: Build and push image
uses: docker/build-push-action@v6
with:
context: .
file: ${{ matrix.dockerfile }}
push: true
tags: |
git.vhaudiquet.fr/${{ env.OWNER }}/${{ matrix.image }}:${{ steps.ver.outputs.version }}
git.vhaudiquet.fr/${{ env.OWNER }}/${{ matrix.image }}:stable
git.vhaudiquet.fr/${{ env.OWNER }}/${{ matrix.image }}:${{ gitea.sha }}
release-chart:
# The exact tag version ships as-is so deployments can pin
# `--version 0.1.0`; appVersion pins the exact commit the image was
# built from (the chart's default image tag is appVersion, so the
# sha image above must exist before this runs).
if: ${{ !contains(gitea.ref_name, '-') }}
needs: build-and-push-release-images
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: https://gitea.com/actions/checkout@v4
- name: Install Helm
uses: azure/setup-helm@v5
- name: Update Chart version and appVersion
run: |
sed -i "s/^version:.*/version: \"${GITHUB_REF_NAME#v}\"/" deploy/helm/rhema-claw/Chart.yaml
sed -i "s/^appVersion:.*/appVersion: \"${{ gitea.sha }}\"/" deploy/helm/rhema-claw/Chart.yaml
- name: Lint Helm chart
run: helm lint deploy/helm/rhema-claw
- name: Package Helm chart
run: helm package deploy/helm/rhema-claw
- name: Push Helm chart to Gitea registry
run: |
TOKEN=$(echo -n "${{ secrets.PACKAGES_TOKEN }}" | tr -d '\n')
curl --fail --user "${{ gitea.actor }}:${TOKEN}" \
-X POST \
--upload-file rhema-claw-*.tgz \
"https://git.vhaudiquet.fr/api/packages/${{ env.OWNER }}/helm/api/charts"
+1
View File
@@ -0,0 +1 @@
/target/
Generated
+3688
View File
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
[workspace]
resolver = "2"
members = ["crates/*", "integrations/*"]
[workspace.package]
version = "0.4.0"
edition = "2024"
rust-version = "1.89"
license = "MIT"
repository = "https://git.vhaudiquet.fr/vhaudiquet/rhema-claw"
authors = ["Valentin Haudiquet"]
[workspace.lints.rust]
missing_docs = "deny"
[workspace.dependencies]
# Serialization: session and message types must round-trip for checkpointing
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Typed library errors
thiserror = "2"
# Async traits must stay object-safe (dyn ModelProvider, dyn ToolResolver)
async-trait = "0.1"
# Config file format (flat scalar fields; see the rhema-config crate)
serde_yaml = "0.9"
# Test runtime
tokio = { version = "1", features = ["macros", "rt"] }
# The claw's HTTP surface: native routes plus SSE, and the OpenAI shim
axum = { version = "0.8", features = ["json"] }
tokio-stream = { version = "0.1", features = ["sync"] }
[profile.release]
strip = "symbols"
codegen-units = 1
+32
View File
@@ -0,0 +1,32 @@
<div align="center">
<b>ῥῆμα, "the spoken word": words that do things.</b>
</div>
<h1 align="center">Rhema Claw</h1>
Rhema Claw is the resident tier of the Rhema agent framework: a
claw-shaped daemon that watches forges (GitHub, Gitea, GitLab) and
calendar feeds, dispatches work to its agents, and serves a chat
surface over HTTP — native routes plus an OpenAI-compatible shim,
with a web UI and an Android client talking to it.
The framework it embeds (the crates under `crates/` it pulls from
crates.io: `rhema-autonomous-agent`, `rhema-host-agent`,
`rhema-rsd`, and friends) lives in the
[rhema repository](https://git.vhaudiquet.fr/vhaudiquet/rhema).
## Layout
- [`crates/rhema-claw/`](./crates/rhema-claw) — the daemon: forge
watches, session dispatch, the chat surface, MCP wiring, and the
vision helper. See its
[README](./crates/rhema-claw/README.md).
- [`integrations/`](./integrations) — the feed adapters that
normalize forge and calendar activity into `rhema-rsd` dispatch.
- [`tools/`](./tools) — what runs on the *user's machine*: the
`rhema-claw-tools-contract` (the scoped agent-token allowlist the
auth middleware enforces), the shared thin-client code, and
`rhema-claw-tools-notify`.
- [`web/claw/`](./web/claw) — the Nuxt web UI.
- [`android/`](./android) — the Compose Android client.
- [`deploy/`](./deploy) — the Docker images and the Helm chart.
+5 -2
View File
@@ -77,8 +77,11 @@ manages the device fleet the claw keeps.
**subscribe first, then POST**, the reply arrives on the stream. Thinking
deltas render dim and collapsible, tool rows show name/summary with error
coloring (bash-like tools render as shell lines instead: dim `$` prefix,
the command line, and an exit-code badge), pasted payloads embedded in a
message as paired `U+FFFC` marks render as compact `▣N 5L` chips, and
the command line, and an exit-code badge), a message's paste chips render
as compact `▣N 5L` labels sliced from the span record its
`user_message` carries beside the plain text (rows recorded before
spans rode the stream still scan the legacy paired-`U+FFFC` form in
the text), and
`attachment` events render as cards: file name, size, caption, an inline
preview for small (≤ 2 MB) images, and a download-and-open row (bytes
from `GET /v1/attachments/{id}` land in the app cache and open through a
@@ -11,6 +11,7 @@ import rs.rhema.phone.net.ClawApi
import rs.rhema.phone.net.ClawEvent
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.OutboundImage
import rs.rhema.phone.net.PasteSpan
import rs.rhema.phone.net.SseFrame
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -61,6 +62,10 @@ class ChatController(
override val id: Long,
val text: String,
val images: List<SentImage> = emptyList(),
// The chip record this surface's rows never carry (its
// composer sends plain text) but a replayed row — a web user's
// chips in this conversation — does; the render slices on it.
val pastes: List<PasteSpan> = emptyList(),
) : Item
data class Thinking(override val id: Long, val text: String) : Item
data class ToolCall(
@@ -355,14 +360,15 @@ class ChatController(
is ClawEvent.UserMessage -> {
// The recorded question — replayed on reload, echoed live
// for a message this surface just sent. An identical last
// row — same text, same image count — is that echo's
// stand-in; skip it, previews and all.
// row — same text, same image count, same chip record —
// is that echo's stand-in; skip it, previews and all.
val last = list.lastOrNull()
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size)) {
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size && last.pastes == event.pastes)) {
list = list + UserMessage(
newId(),
event.text,
event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) },
event.pastes,
)
}
}
@@ -117,6 +117,13 @@ data class RhemaNotification(
@Serializable
data class UserImage(val id: String, @SerialName("media_type") val mediaType: String)
// One paste chip a user_message records: the byte span (UTF-8) of the
// payload in the message's plain text, plus the payload's line count
// — the session annotation's own shape (rhema-core `PasteSpan`), so a
// chip renders from the record instead of rebuilding the wire form.
@Serializable
data class PasteSpan(val start: Int = 0, val end: Int = 0, val lines: Int = 0)
// One event of GET /v1/sessions/{key}/history: the record's seq for it,
// beside the event itself. Seq order is the wire order.
@Serializable
@@ -138,11 +145,13 @@ data class HistoryPage(val events: List<HistoryEvent> = emptyList(), val more: B
sealed interface ClawEvent {
@Serializable
@SerialName("user_message")
// Rows recorded before images rode the stream carry no field at
// all; absent folds to none, never a guessed shape.
// Rows recorded before images — and then before chips — rode the
// stream carry no field at all; absent folds to none, never a
// guessed shape.
data class UserMessage(
val text: String = "",
val images: List<UserImage> = emptyList(),
val pastes: List<PasteSpan> = emptyList(),
) : ClawEvent
@Serializable
@@ -82,6 +82,7 @@ import rs.rhema.phone.chat.MAX_STAGED_IMAGES
import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PasteSpan
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
@@ -438,6 +439,7 @@ private sealed interface TurnGroup {
val id: Long,
val text: String,
val images: List<ChatController.SentImage>,
val pastes: List<PasteSpan> = emptyList(),
) : TurnGroup {
override val key: String = "u$id"
}
@@ -451,7 +453,7 @@ private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
val groups = mutableListOf<TurnGroup>()
for (item in items) {
when (item) {
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images)
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images, item.pastes)
else -> {
val last = groups.lastOrNull()
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item))
@@ -501,10 +503,13 @@ private fun TurnGroupRow(
}
}
}
// Embedded pastes render as chips, not payloads; the
// text around them stays verbatim.
// Chips render as chips, not payloads; the text
// around them stays verbatim. The row's chip record
// slices them out of the plain text; a row from
// before the record rode the stream carries none
// and still scans the mark form in the text.
var chip = 0
pasteParts(group.text).forEach { part ->
messageParts(group.text, group.pastes).forEach { part ->
when (part) {
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
is PastePart.Paste -> {
@@ -740,20 +745,67 @@ private fun PasteChip(label: String) {
)
}
// --- embedded pastes --------------------------------------------------
// The wire form a long paste travels in: MARK, payload, MARK — one
// logical unit inside otherwise plain text (rhema-core's paste module
// is the definition; these are its client-side shape). A mark with no
// partner is literal text.
// --- paste chips ------------------------------------------------------
// A long paste rides as a chip the render stands in for its payload.
// The record is the span list a user_message carries (the session
// annotation's own shape); the marks in the text are the record's
// legacy spelling, kept for rows that predate it — a mark with no
// partner is literal text (rhema-core's paste module is the
// definition; these are its client-side shape).
private const val PASTE_MARK = '\uFFFC'
/** One scanned piece of embedded-form text. */
/** One piece of a rendered message: literal text, or a chip standing
* for its payload. */
private sealed interface PastePart {
data class Text(val text: String) : PastePart
data class Paste(val payload: String) : PastePart
}
/** A message's parts. The chip record is the modern form — each span
* names the payload's byte range in the plain text — and rows recorded
* before it rode the stream carry none; those still scan the legacy
* mark form in the text itself. */
private fun messageParts(text: String, pastes: List<PasteSpan> = emptyList()): List<PastePart> =
if (pastes.isEmpty()) pasteParts(text) else spanParts(text, pastes)
/** Splits a record-carrying message into its parts, left to right. The
* spans' offsets are UTF-8 bytes, the plain form the fold measured —
* every character boundary is mapped in one walk, and a span that
* splits a character maps to none: the render skips it rather than cut
* one in half. Malformed input never throws. */
private fun spanParts(text: String, pastes: List<PasteSpan>): List<PastePart> {
var bytes = 0
var units = 0
val at = mutableMapOf(0 to 0)
var index = 0
while (index < text.length) {
val codePoint = text.codePointAt(index)
val width = Character.charCount(codePoint)
index += width
units = index
bytes += when {
codePoint < 0x80 -> 1
codePoint < 0x800 -> 2
codePoint < 0x10000 -> 3
else -> 4
}
at[bytes] = units
}
val parts = mutableListOf<PastePart>()
var cut = 0
for (span in pastes.sortedBy { it.start }) {
val start = at[span.start]
val end = at[span.end]
if (start == null || end == null || start < cut || end < start) continue
if (start > cut) parts += PastePart.Text(text.substring(cut, start))
parts += PastePart.Paste(text.substring(start, end))
cut = end
}
if (cut < text.length) parts += PastePart.Text(text.substring(cut))
return parts
}
/** Splits embedded-form text into its parts, left to right. A mark with
* no partner is literal text; malformed input never throws. */
private fun pasteParts(text: String): List<PastePart> {
+23 -14
View File
@@ -26,29 +26,36 @@ mock = ["rhema-core/mock"]
[dependencies]
# The shared toolkit: the resident agent assembles its agent from the
# shell, the approval seam, paste expansion, and revive-on-resume
rhema-agent-tools = { path = "../rhema-agent-tools" }
rhema-autonomous-agent = { path = "../rhema-autonomous-agent" }
rhema-coding-agent = { path = "../rhema-coding-agent" }
rhema-config = { path = "../rhema-config" }
rhema-core = { path = "../rhema-core" }
# shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.0"
rhema-prompt = "0.4.0"
rhema-host-agent = "0.4.0"
rhema-autonomous-agent = "0.4.0"
rhema-config = "0.4.0"
rhema-core = "0.4.0"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = { path = "../rhema-transcript" }
rhema-transcript = "0.4.0"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat
rhema-identity = { path = "../rhema-identity" }
rhema-rsd = { path = "../rhema-rsd" }
rhema-identity = "0.4.0"
rhema-rsd = "0.4.0"
# The sandbox seam: where `bash` runs, local process or a daemon speaking
# the wire protocol over HTTP
rhema-sandbox = "0.4.0"
rhema-sandbox-http = "0.4.0"
# The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain
rhema-memory = { path = "../rhema-memory" }
rhema-memory = "0.4.0"
# The shared ModelCard the backend registry's listings return
rhema-provider = { path = "../rhema-provider" }
rhema-provider-registry = { path = "../rhema-provider-registry", version = "0.2.3" }
rhema-provider = "0.4.0"
rhema-provider-registry = "0.4.0"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -59,6 +66,8 @@ thiserror = { workspace = true }
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
# concurrent handler runs share it. `net` is the HTTP listener.
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] }
# The sandbox executor implements the shell seam
async-trait = { workspace = true }
# The chat surface: native routes plus SSE, and the OpenAI shim
axum = { workspace = true }
# Broadcast receivers as SSE bodies
@@ -71,7 +80,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.22"
rhema-mcp = { version = "0.2.3", path = "../rhema-mcp" }
rhema-mcp = "0.4.0"
[dev-dependencies]
tempfile = "3"
@@ -83,7 +92,7 @@ reqwest = { version = "0.12", features = ["json", "stream"] }
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { path = "../rhema-core", features = ["mock"] }
rhema-core = { version = "0.4.0", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+34 -3
View File
@@ -69,6 +69,10 @@ listen: 127.0.0.1:7799
token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: http # local (default) or http
url: https://box.example:7600 # the sandboxd base URL
token: sandbox-secret # the daemon's shared secret, if it has one
poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty
@@ -96,6 +100,14 @@ unattended for a long time, so a cap this deep is a runaway guard, not
a work timer — a turn that hits it ends with a failed outcome and the
conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
`/workspace`. Later edits stay there; the claw does not copy them back.
The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer
token is what stands between it and the agent's tools. Set a token, or
@@ -123,7 +135,7 @@ The native surface:
```
GET /healthz GET /v1/sessions
POST /v1/sessions {"name"} — create an empty interactive session
POST /v1/sessions/{key}/messages {"text": "..."} -> 202
POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?} -> 202
GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
DELETE /v1/sessions/{key} drop a session and its turn history
@@ -137,6 +149,8 @@ DELETE /v1/consents/{id} deny a pending ask
GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
@@ -169,7 +183,10 @@ lets a UI badge setup state.
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
`turn_done`. Every streamed event is persisted as it streams, so both a
`turn_done`. A `user_message` names its paste chips as the byte spans
they stand for in its plain text (`paste::PasteSpan`, the session
record's own shape) — a client renders from that record; rows recorded
before spans arrived carry the legacy mark form in the text instead. Every streamed event is persisted as it streams, so both a
reload and a daemon restart rebuild the transcript, and a session that
runs for weeks keeps all of it.
@@ -244,7 +261,21 @@ tool wakes with the account id, never the secret, and a denial or a
15-minute silence comes back in-band so the turn can say so and move
on. A watch with no token of its own polls — and replies — as the
matching saved account: the same forge, and on a self-hosted forge the
same base URL. Acting with a stored account is `identity_exec`: it runs one shell
same base URL.
A repo watch is a feed, not an invitation. The daemon answers a thread
when somebody there addresses it — a comment whose body names the handle
its credential speaks as (`@kosmos`), written by anyone but itself — and
otherwise drains the news and runs nothing: no snapshot, no turn, no
comment on somebody else's conversation. (Its own replies quote the
mention they answer, so they never reopen the gate.) Notifications are
the other door and are adjudicated before they arrive — assigned, review
requested, @-mentioned — so those always run. The handle is the account
identity's when the token has one, and the forge's own `/user` answer
when it does not; a credential the forge will not name leaves the gate
open, with a warning in the log, rather than silently muting a watch.
Acting with a stored account is `identity_exec`: it runs one shell
command in the session workspace with the secret injected —
`ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/
`GITLAB_TOKEN`, and a git credential helper — so `git clone` and API
+1 -1
View File
@@ -26,9 +26,9 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rhema_agent_tools::render_template;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json};
/// The built-in system prompt, kept as data next to the code and read
+57 -6
View File
@@ -13,6 +13,7 @@
//! binary's startup, not here — the daemon library takes the built
//! provider, so tests can inject a mock.
use std::num::NonZeroU32;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -22,10 +23,13 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60;
/// How many tool rounds one chat turn may run, when
/// [`ClawConfig::max_turn_steps`] is unset — the coding driver's own
/// budget shape and its default: deep enough that a cap is a runaway
/// guard for an agent meant to work unattended, not a work timer.
pub const DEFAULT_MAX_TURN_STEPS: u32 = 2048;
/// [`ClawConfig::max_turn_steps`] is unset — the host agent driver's
/// own budget shape and its default: deep enough that a cap is a
/// runaway guard for an agent meant to work unattended, not a work
/// timer. `NonZeroU32`, the driver's own spelling: a turn cannot have
/// no step budget at all, and a config that names zero is refused at
/// load instead of cutting every round dead.
pub const DEFAULT_MAX_TURN_STEPS: NonZeroU32 = NonZeroU32::new(2048).unwrap();
/// Where the HTTP surface listens when [`ClawConfig::listen`] is unset:
/// loopback only — the surface is for the machine's resident user.
@@ -55,6 +59,9 @@ pub enum ConfigError {
"agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
)]
SameAgentToken,
/// The configured sandbox choice cannot run as written.
#[error("sandbox: {0}")]
Sandbox(String),
/// The ingest credential is the same value as the human token or
/// the agent token: boot refuses, because the ingest credential's
/// safety is that it is write-only and the event door only — a
@@ -127,7 +134,7 @@ pub struct ClawConfig {
/// How many tool rounds one chat turn may run before it is cut off
/// with a failed outcome, the conversation intact. A follow-up
/// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset.
pub max_turn_steps: u32,
pub max_turn_steps: NonZeroU32,
/// The handler's model backend: `google`, `llama-cpp`, `openrouter`,
/// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve
/// through the stored rhema config's default profile, env vars
@@ -171,6 +178,10 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still
/// ingest.
pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, or a
/// `rhema-sandboxd` over HTTP. The settings store owns the live
/// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>,
}
impl ClawConfig {
@@ -198,6 +209,7 @@ impl Default for ClawConfig {
tools_bin: None,
ingest_token: None,
transcript: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -326,6 +338,12 @@ impl ClawConfig {
{
return Err(ConfigError::IngestTokenCollision);
}
if let Some(sandbox) = &self.sandbox {
sandbox
.clone()
.normalized()
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
}
Ok(())
}
}
@@ -422,10 +440,14 @@ model: claude-sonnet-4-5
listen: 192.168.1.10:7800
token: sekrit
ingest_token: door-key
sandbox:
kind: http
url: https://box.example:7600
token: sandbox-secret
";
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
assert_eq!(config.poll_interval_secs, 30);
assert_eq!(config.max_turn_steps, 512);
assert_eq!(config.max_turn_steps, NonZeroU32::new(512).unwrap());
assert_eq!(config.provider.as_deref(), Some("anthropic"));
assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5"));
assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800"));
@@ -438,6 +460,35 @@ ingest_token: door-key
config.bootstrap_root.as_deref(),
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap"))
);
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
}
#[test]
fn an_http_sandbox_needs_a_url_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
token: None,
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"a remote sandbox without a URL is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
token: None,
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
+74 -7
View File
@@ -62,6 +62,9 @@ pub enum ClawError {
/// The runtime settings table could not be opened or read.
#[error(transparent)]
Settings(#[from] crate::settings::SettingsError),
/// The sandbox choice could not be loaded or is malformed.
#[error(transparent)]
Sandbox(#[from] crate::sandbox::SandboxError),
/// The notification table could not be opened or read.
#[error(transparent)]
Notifications(#[from] crate::notifications::NotificationStoreError),
@@ -123,6 +126,30 @@ fn interactive_dispatch() -> DispatcherConfig {
}
}
/// The forge dispatcher's timing: the library defaults, except the lease
/// TTL.
///
/// A forge turn is not a chat step. The handler clones a repository,
/// reads it, and may build and test a fix — tens of minutes of wall
/// clock — and nothing renews the lease once the turn is under way:
/// `SessionContext::poll_inbox` renews, and the handler calls it once, at
/// the start; the commit hook that runs between tool calls *checkpoints*,
/// which fails on a lapsed lease instead of extending one. So the TTL is
/// a hard ceiling on a whole turn: cross it and the turn dies on its next
/// tool call, after which the driver's own checkpoint and release both
/// report `Expired` and the key ends with no outcome recorded — a silent
/// kill, indistinguishable from a pass that found nothing.
///
/// `DispatcherConfig::default`'s ten minutes are the spec's example
/// values, sized for a single agent step. An hour matches the
/// interactive lane's choice for the same reason: the work is long.
pub fn forge_dispatch() -> DispatcherConfig {
DispatcherConfig {
lease_ttl_millis: 3_600_000,
..DispatcherConfig::default()
}
}
/// The resident daemon: the extension set's sources (the forge watches,
/// the task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface.
@@ -151,8 +178,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — the resident loop uses the
/// defaults, `--once` zeroes the debounce.
/// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// with `--once` zeroing the debounce.
pub fn build(
config: &ClawConfig,
backends: Arc<BackendRegistry>,
@@ -225,6 +252,10 @@ impl Daemon {
// The forge handler resolves its watches through the table at
// dispatch time, so a watch added mid-run is answerable without a
// restart.
// The runtime settings table, opened before the handlers so the
// sandbox choice and the provider write share one connection.
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The client tools' connection, handed to the agent's shell as
// environment: the URL the surface answers on, the scoped
// agent token (the middleware keeps it to the contract's data
@@ -252,6 +283,25 @@ impl Daemon {
format!("{}:{inherited}", tools_bin.display()),
);
}
// Where `bash` runs: the stored choice wins, the config seeds a
// fresh store. The state is shared by every handler and the
// surface, so a switch is live on the next turn.
let sandbox = Arc::new(crate::sandbox::SandboxState::load(
settings.clone(),
config.sandbox.clone(),
interactive_workspace.clone(),
&tool_env,
)?);
let sandbox_choice = sandbox.choice();
eprintln!(
"[claw] sandbox: {}{}",
sandbox_choice.kind.as_str(),
sandbox_choice
.url
.as_deref()
.map(|url| format!(" ({url})"))
.unwrap_or_default(),
);
let forge_handler = ClawHandler::new(
backends.clone(),
workspace_root,
@@ -259,7 +309,8 @@ impl Daemon {
accounts.clone(),
config.transcript_enabled(),
tool_env.clone(),
);
)
.with_sandbox(sandbox.clone());
// Three drivers over one store admit from the same table, so
// each owns its slice of the key space: a forge pass must never
// pick up a resident or job event (it would fail it, and
@@ -292,7 +343,6 @@ impl Daemon {
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The identity store shares the settings table and keeps its
// images beside the database.
let identity = Arc::new(crate::identity::IdentityStore::new(
@@ -361,7 +411,8 @@ impl Daemon {
extensions.clone(),
config.transcript_enabled(),
)
.with_steer(steer.clone());
.with_steer(steer.clone())
.with_sandbox(sandbox.clone());
let interactive_driver = Arc::new(
Driver::new(
interactive_dispatcher.clone(),
@@ -381,7 +432,8 @@ impl Daemon {
notifications.clone(),
config.max_turn_steps,
config.transcript_enabled(),
);
)
.with_sandbox(sandbox.clone());
let jobs_driver = Arc::new(
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
.with_holder("rhema-claw-jobs")
@@ -410,6 +462,7 @@ impl Daemon {
bridge,
attachments,
phone,
sandbox,
config.token.clone(),
config.agent_token.clone(),
config.ingest_token.clone(),
@@ -551,7 +604,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig {
debounce_window_millis: 0,
..DispatcherConfig::default()
..forge_dispatch()
};
let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?;
@@ -562,6 +615,20 @@ pub async fn run_once(
mod tests {
use super::*;
#[test]
fn the_forge_dispatcher_leases_for_a_turn_not_a_step() {
let dispatch = forge_dispatch();
assert_eq!(
dispatch.lease_ttl_millis, 3_600_000,
"an hour: a turn clones, reads, builds and tests"
);
assert_eq!(
dispatch.debounce_window_millis,
DispatcherConfig::default().debounce_window_millis,
"the rest stays the library's defaults"
);
}
#[test]
fn the_interactive_dispatcher_dispatches_now_and_leases_long() {
let dispatch = interactive_dispatch();
+194 -4
View File
@@ -24,9 +24,10 @@ use std::sync::{Arc, Mutex, PoisonError};
use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_forge_integration::forge_key_fn;
use rhema_forge_integration::triage::{self, Triage};
use rhema_forge_integration::triage::{self, Role, Triage};
use rhema_forge_integration::{
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, Watcher, register_forge,
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, NotificationReason, RepoRef,
Timestamp, Watcher, register_forge,
};
use rhema_identity::{IdentityStore, SecretKind};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
@@ -315,7 +316,14 @@ impl Source for ForgeSource {
}
};
let client = self.client_for(&record);
let polled = self.watcher.poll(client.as_ref(), &repo).await;
let since = self.cursor_for(&record)?;
let polled = self
.watcher
.poll_since(client.as_ref(), &repo, Some(&since))
.await;
if polled.is_ok() {
self.persist_cursor(&record, &repo)?;
}
// Health first, whatever the outcome: a watch that has been
// failing since it was created must be able to say so.
self.record_poll(
@@ -366,6 +374,44 @@ impl Source for ForgeSource {
}
impl ForgeSource {
/// The cursor one repo watch polls from: the durable one when it has
/// one, and otherwise a seed at *now*, written before the poll so a
/// forge that is down cannot walk the start line forward on every pass
/// and lose the news arriving in between.
///
/// A watch reports news, and a repository's history is not news.
/// Replaying it meant one dispatch per old thread — and, from the
/// handler, one comment posted on each. An unreadable cursor reads as
/// absent: a corrupted row must not fire a backlog either.
fn cursor_for(&self, record: &WatchRecord) -> Result<Timestamp, SourceError> {
let stored = self
.store
.cursor(SCOPE_REPO, &record.forge, &record.repo)
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
if let Some(since) = stored.as_deref().and_then(Timestamp::parse) {
return Ok(since);
}
let now = Timestamp::from_epoch_millis(SystemClock.now_millis() as i64)
.ok_or_else(|| SourceError::Backend("cannot spell this instant".to_owned()))?;
self.store
.set_cursor(SCOPE_REPO, &record.forge, &record.repo, now.raw())
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
Ok(now)
}
/// Advances a watch's durable cursor to wherever the poll got to. The
/// watcher's own map is per-process: a restart that lost it replayed
/// the repository's history, the backlog [`Self::cursor_for`] exists to
/// keep out.
fn persist_cursor(&self, record: &WatchRecord, repo: &RepoRef) -> Result<(), SourceError> {
let Some(cursor) = self.watcher.cursor(repo) else {
return Ok(());
};
self.store
.set_cursor(SCOPE_REPO, &record.forge, &record.repo, cursor.raw())
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))
}
/// Records one poll's outcome, and says something the first time a
/// streak begins: a watch refused on every tick looks exactly like a
/// quiet repository from the outside, and only the failing tick knows
@@ -468,7 +514,7 @@ impl ForgeSource {
let now = SystemClock.now_millis();
let mut fed = 0;
for notification in &page.notifications {
match triage::classify(notification) {
match claw_triage(notification) {
Triage::Ignore => {}
Triage::Surface => {
if let Err(err) = self.notifications.push(
@@ -530,6 +576,24 @@ impl ForgeSource {
}
}
/// [`triage::classify`], plus the one reclassification a resident agent
/// owes its own name: an @-mention of the daemon is an ask.
///
/// The shared vocabulary reads a mention as [`Triage::Surface`] — right
/// for a consumer that only notifies its human, since a mention is not an
/// assignment. This daemon is the party named: somebody typed `@handle` on
/// a thread and is waiting for an answer, which is the same ask an
/// assignment is. Left as a surface, a mention would be a phone buzz and
/// nothing else — this loop never dispatches for a surface, so the turn
/// that reads the thread would never run and the mention would go
/// unanswered.
fn claw_triage(notification: &Notification) -> Triage {
match &notification.reason {
NotificationReason::Mention => Triage::Agent(Role::Implementer),
_ => triage::classify(notification),
}
}
/// The device-notification text a [`Triage::Surface`] lands: the reason
/// and the thread title, so the human can judge without opening the
/// forge.
@@ -547,6 +611,83 @@ fn surface_body(notification: &Notification) -> String {
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
/// A watch installed on a repository full of history must not replay
/// it: the first pass seeds its cursor to *now* and feeds nothing, and
/// the poll that follows asks from that instant rather than from the
/// beginning. Every replayed event used to be a dispatch, and every
/// dispatch a comment posted on a thread nobody had just touched.
#[tokio::test]
async fn a_new_watch_starts_now_instead_of_replaying_history() {
let server = MockServer::start().await;
for endpoint in [
"/api/v1/repos/acme/barn/issues",
"/api/v1/repos/acme/barn/pulls",
"/api/v1/repos/acme/barn/issues/comments",
] {
Mock::given(method("GET"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
.mount(&server)
.await;
}
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
store
.add("gitea", "acme/barn", Some(&server.uri()), "tok")
.expect("add");
let (dispatcher, accounts, notifications) = test_parts(store.clone());
let source = ForgeSource::new(&dispatcher, "gitea", store.clone(), accounts, notifications);
assert_eq!(
source.detect().await.expect("the pass runs"),
0,
"a watch's first pass feeds no history"
);
let cursor = store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("cursor reads")
.expect("the first pass seeded a cursor");
assert!(
Timestamp::parse(&cursor).is_some(),
"the seed is spelled like a forge instant: {cursor}"
);
// The poll asked from the seed: one request per feed, each
// `since`-filtered where the feed takes one.
let requests = server.received_requests().await.expect("recording is on");
let issue_polls: Vec<_> = requests
.iter()
.filter(|request| request.url.path() == "/api/v1/repos/acme/barn/issues")
.collect();
assert_eq!(issue_polls.len(), 1, "one issues poll");
let since = issue_polls[0].url.query_pairs().find_map(|(key, value)| {
if key.as_ref() == "since" {
Some(value.into_owned())
} else {
None
}
});
assert_eq!(since.as_deref(), Some(cursor.as_str()));
// A second pass resumes from the same place, not from history.
assert_eq!(source.detect().await.expect("the second pass runs"), 0);
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("cursor reads"),
Some(cursor)
);
assert_eq!(
store
.health(SCOPE_REPO, "gitea", "acme/barn")
.expect("health reads")
.map(|health| health.consecutive_failures),
Some(0),
"the watch polled cleanly"
);
}
/// The parts a test source polls through, all in memory.
fn test_parts(
@@ -862,4 +1003,53 @@ mod tests {
});
assert_eq!(key.as_str(), "github:issue:acme/widgets#142");
}
/// The notification fixture the reclassification tests classify: one
/// plain issue thread, the reason the only thing that varies.
fn triaged_notification(reason: NotificationReason) -> Notification {
Notification {
id: format!("github:notification:1@{}", reason.as_str()),
reason,
repo: RepoRef::new("acme", "widgets"),
number: 7,
is_pr: false,
actor: Some("stranger".to_owned()),
title: Some("a title".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-11-21T00:00:00Z").expect("parses"),
raw: serde_json::json!({}),
}
}
/// A mention of the daemon is an ask: this daemon is the party named,
/// so the feed dispatches a turn that reads the thread — not a phone
/// buzz that leaves the mention unanswered.
#[test]
fn a_mention_of_the_daemon_dispatches_instead_of_surfacing() {
assert_eq!(
claw_triage(&triaged_notification(NotificationReason::Mention)),
Triage::Agent(Role::Implementer),
"somebody addressed the daemon and is waiting"
);
}
/// Every other reason keeps the shared vocabulary's verdict — the
/// reclassification is one row, not a second opinion.
#[test]
fn every_other_reason_keeps_the_shared_verdict() {
for reason in [
NotificationReason::ReviewRequested,
NotificationReason::Assigned,
NotificationReason::ReviewFeedback,
NotificationReason::Author,
NotificationReason::CiActivity,
NotificationReason::Other("subscribed".to_owned()),
] {
assert_eq!(
claw_triage(&triaged_notification(reason.clone())),
triage::classify(&triaged_notification(reason.clone())),
"{} keeps the base verdict",
reason.as_str()
);
}
}
}
+259 -17
View File
@@ -10,7 +10,7 @@
//!
//! Session continuity rides the dispatcher, not the filesystem: the
//! agent's session JSON is stashed into `ctx.session.core.driver_state`
//! before the run returns and restored with [`CodingAgent::from_session`]
//! before the run returns and restored with [`HostAgent::from_session`]
//! on the next dispatch of the same key, so a resumed thread keeps its
//! conversation. Commit-before-execute rides it too: the run installs the
//! context's commit hook, so the intent is in the store before the first
@@ -25,9 +25,8 @@ use std::sync::{Arc, Mutex, PoisonError};
use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore;
use rhema_agent_tools::AllowAll;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
use rhema_coding_agent::{CodingAgent, CodingAgentConfig};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
use rhema_forge_integration::ForgeKind;
use rhema_forge_integration::triage::Role;
@@ -35,10 +34,13 @@ use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode,
parse_key,
};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_identity::IdentityStore;
use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell;
use crate::backends::BackendRegistry;
use crate::sandbox::SandboxState;
/// The handler's tool permissions, resolved deterministically before the
/// agent's first step (spec §8) — never by the model, never mid-run. V1
@@ -70,7 +72,10 @@ pub struct ClawHandler {
/// agent shell: the daemon URL, the scoped agent token, the tools'
/// bin dir on PATH. Empty when the config issues no agent token.
tool_env: std::collections::BTreeMap<String, String>,
clients: Mutex<HashMap<String, Arc<dyn Forge>>>,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per dispatch.
sandbox: Option<Arc<SandboxState>>,
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
}
impl ClawHandler {
@@ -91,10 +96,18 @@ impl ClawHandler {
watches,
accounts,
tool_env,
sandbox: None,
clients: Mutex::new(HashMap::new()),
}
}
/// Shares the deployment's sandbox choice: a forge turn's commands
/// run where it says, seeded from the thread's host workspace.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// The forge client a dispatch key answers to:
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
/// table at dispatch time — the table is the source of truth, not a
@@ -120,6 +133,18 @@ impl ClawHandler {
key: &ResourceKey,
as_account: Option<&str>,
) -> Result<Arc<dyn Forge>, String> {
Ok(self.watch_client(key, as_account)?.forge.clone())
}
/// [`Self::watch_forge_as`] with the handle the credential speaks as
/// kept beside the client: the mention gate needs to recognize its own
/// name, and asking the forge is a request worth spending once per
/// credential, not once per dispatch.
fn watch_client(
&self,
key: &ResourceKey,
as_account: Option<&str>,
) -> Result<Arc<WatchClient>, String> {
let watch = watch_key(key)
.ok_or_else(|| format!("resource key {key} is not a forge thread key"))?;
let (forge, repo) = watch
@@ -192,7 +217,7 @@ impl ClawHandler {
kind: ForgeKind,
host: Option<&str>,
credential: &WatchCredential,
) -> Arc<dyn Forge> {
) -> Arc<WatchClient> {
// Everything that changes the client: the kind, its host, and the
// credential — the login included, since one value sent two ways
// is two credentials.
@@ -206,7 +231,10 @@ impl ClawHandler {
let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner);
clients
.entry(cache_key)
.or_insert_with(|| record_client(kind, host, credential))
.or_insert_with(|| {
let forge = record_client(kind, host, credential);
Arc::new(WatchClient::new(forge, credential.login.clone()))
})
.clone()
}
@@ -224,7 +252,22 @@ impl ClawHandler {
// that account — a thread the account's feed delivered may have no
// repo watch row at all.
let news = self.drain_news(ctx, &key).await?;
let forge = self.watch_forge_as(&ctx.key, delivery_account(&news))?;
let client = self.watch_client(&ctx.key, delivery_account(&news))?;
// The mention gate, before anything is fetched or run: the news is
// already drained, and this decides whether it asks anything of
// the daemon at all.
let handle = client.handle().await;
if handle.is_none() && news.iter().any(|item| matches!(item, InboxNews::Event(_))) {
eprintln!(
"[claw] warning: {key}: the forge would not name this credential; \
every event on the watch dispatches"
);
}
if !addressed(&news, handle.as_deref()) {
return Ok(Outcome::Superseded);
}
let forge = client.forge.clone();
let snapshot = forge
.snapshot(&repo, thread_kind, number)
@@ -252,7 +295,7 @@ impl ClawHandler {
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
let mut sink = TurnSink;
let output = agent
.turn(prompt, &mut sink, Arc::new(AllowAll))
.turn(prompt, &mut sink)
.await
.map_err(|err| format!("turn for {key} failed: {err}"))?;
@@ -299,35 +342,55 @@ impl ClawHandler {
ctx: &SessionContext,
workspace: &Path,
key: &str,
) -> Result<CodingAgent, String> {
) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current();
let config = self.agent_config(&model, workspace);
let config = self.agent_config(provider, &model, workspace);
let agent = match &ctx.session.core.driver_state {
// A never-dispatched key carries no stash: start clean.
serde_json::Value::Null => CodingAgent::new(provider, config),
serde_json::Value::Null => HostAgent::new(config),
stashed => {
let session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
CodingAgent::from_session(provider, config, session)
HostAgent::from_session(config, session)
}
};
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
}
/// The config one dispatch's agent runs on: the default coding
/// agent's, with the bounded request view when the config has it on.
/// agent's, with the bounded request view when the config has it on
/// and a remote shell when the sandbox choice says so.
/// A forge thread answers for as long as the thread lives; without
/// the view its history would ride whole on every step.
fn agent_config(&self, model: &str, workspace: &Path) -> CodingAgentConfig {
let mut config = CodingAgentConfig::new(model, workspace);
fn agent_config(
&self,
provider: Arc<dyn rhema_core::ModelProvider>,
model: &str,
workspace: &Path,
) -> HostAgentConfig {
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(workspace),
None => workspace.to_path_buf(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
// Write the resolved value, not an override: the coding agent's
// own default is on now, and the config's `false` must win.
config.transcript = self
.transcript
.then(rhema_transcript::TranscriptSettings::default);
config.shell_env = self.tool_env.clone();
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display,
sandbox.executor(workspace.to_path_buf()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
}
}
config
}
@@ -343,6 +406,45 @@ impl ClawHandler {
}
}
/// One cached forge client, with the handle it speaks as.
///
/// The credential a watch resolves carries a login only when an account
/// identity supplied the token; a token pasted into the watch row, or a
/// forge environment variable, names nobody. The mention gate still has to
/// recognize the daemon's own name — to see an @-mention in a body, and to
/// leave its own replies alone — so the forge is asked who it is, once per
/// credential, the first time a dispatch needs to know.
struct WatchClient {
forge: Arc<dyn Forge>,
/// The login the credential itself carries.
login: Option<String>,
/// The forge's own answer, asked at most once.
viewer: OnceCell<Option<String>>,
}
impl WatchClient {
fn new(forge: Arc<dyn Forge>, login: Option<String>) -> Self {
Self {
forge,
login,
viewer: OnceCell::new(),
}
}
/// The handle this client speaks as: the credential's when it has one,
/// else the forge's own answer. `None` when neither can name it — a
/// forge that is down, or a backend with no `/user`.
async fn handle(&self) -> Option<String> {
if let Some(login) = &self.login {
return Some(login.clone());
}
self.viewer
.get_or_init(|| async { self.forge.viewer_login().await.ok().flatten() })
.await
.clone()
}
}
#[async_trait]
impl Handler for ClawHandler {
async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
@@ -440,6 +542,60 @@ fn delivery_account(news: &[InboxNews]) -> Option<&str> {
})
}
/// Whether `news` asks anything of the daemon — the mention gate.
///
/// A triaged notification answered this question on the way in: the
/// notifications feed handed the row over because it was assigned, a
/// review was requested, or someone @-mentioned the account, and
/// [`triage`](rhema_forge_integration::triage) let it through. It always
/// runs.
///
/// A plain repo event has been through nothing: a repo watch sees every
/// issue, pull request, review and comment on the repository. Running a
/// turn for each of them would burn a model call per comment and post an
/// unasked-for reply on threads nobody addressed the daemon in — the
/// difference between watching a repository and answering it. So a plain
/// event runs only when it addresses the daemon: a body that names the
/// handle we speak as, written by somebody else.
///
/// With no handle to look for, nothing is gated: a filter that silently
/// turns a watch off is worse than one that occasionally over-answers, and
/// the dispatch says so in the log.
fn addressed(news: &[InboxNews], handle: Option<&str>) -> bool {
if news
.iter()
.any(|news| matches!(news, InboxNews::Notified { .. }))
{
return true;
}
let Some(handle) = handle else {
return true;
};
news.iter().any(|news| match news {
InboxNews::Notified { .. } => true,
InboxNews::Event(event) => mentions(event, handle),
})
}
/// Whether `event` addresses `handle`: its body names `@handle`, and the
/// event is not the daemon's own writing. Our replies quote the mentions
/// they answer, so an event written by the handle counts as addressed by
/// nobody — otherwise every answer would feed the next turn.
fn mentions(event: &ForgeEvent, handle: &str) -> bool {
let own = event
.actor
.as_deref()
.is_some_and(|actor| actor.eq_ignore_ascii_case(handle));
if own {
return false;
}
let Some(body) = event.body.as_deref() else {
return false;
};
let needle = format!("@{}", handle.to_lowercase());
body.to_lowercase().contains(needle.as_str())
}
/// The batch's dominant role, for the prompt's persona framing:
/// implementing subsumes reviewing — a batch that asks for both is a
/// dispatch where the work is the point. Plain events imply no persona:
@@ -712,6 +868,89 @@ mod tests {
);
}
/// A plain comment that names nobody is the thread's own traffic: the
/// gate stays shut, no turn runs, and nothing is posted.
#[test]
fn a_comment_that_names_nobody_does_not_address_the_daemon() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some("any progress on this?"),
))];
assert!(!addressed(&news, Some("kosmos")));
}
/// Addressed by name, in any case, anywhere in the body — the point of
/// the feature is that the human types a sentence, not a protocol.
#[test]
fn a_comment_that_names_the_handle_addresses_it() {
for body in [
"hey @kosmos can you take a look?",
"@Kosmos, this one is yours",
"I think @kosmos should decide",
] {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some(body),
))];
assert!(addressed(&news, Some("kosmos")), "body: {body}");
}
}
/// Our own replies quote the mention they answer, so they mention the
/// handle on every line — and must never feed the next turn.
#[test]
fn the_daemons_own_comments_never_address_it() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"kosmos",
Some("> @kosmos can you take a look?\n\nDone, see the branch."),
))];
assert!(!addressed(&news, Some("kosmos")));
// Case is the forge's, not the body's: the actor check folds it.
let news = [InboxNews::Event(event(
EventKind::Comment,
"Kosmos",
Some("@kosmos on it"),
))];
assert!(!addressed(&news, Some("kosmos")));
}
/// Thread-level events carry no body, so a mention gate can never pass
/// them: an opened or closed issue is context, not a request.
#[test]
fn an_event_with_no_body_is_not_a_request() {
let news = [InboxNews::Event(event(EventKind::Closed, "dave", None))];
assert!(!addressed(&news, Some("kosmos")));
}
/// A triaged notification was adjudicated on the way in — assigned, a
/// review requested, or a mention — so it runs regardless of bodies.
#[test]
fn a_triaged_notification_always_addresses_the_daemon() {
let notified = decode_news(&triaged_item(
Role::Implementer,
NotificationReason::Assigned,
))
.expect("the triaged payload decodes");
let news = [notified];
assert!(addressed(&news, Some("kosmos")));
assert!(addressed(&news, None), "a notification needs no handle");
}
/// With no handle to look for, the gate stays open: silently turning a
/// watch off is worse than over-answering, and the dispatch logs it.
#[test]
fn an_unnamed_credential_gates_nothing() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some("any progress?"),
))];
assert!(addressed(&news, None));
}
#[test]
fn thread_level_events_carry_no_body_and_the_prompt_says_so() {
let prompt = build_prompt(
@@ -861,6 +1100,7 @@ mod tests {
Content::Text("on it".into()),
Content::Text(" — closing.".into()),
],
annotations: Default::default(),
};
assert_eq!(final_text(&message).as_deref(), Some("on it — closing."));
let tool_only = Message {
@@ -871,6 +1111,7 @@ mod tests {
args: serde_json::json!({}),
provider_data: serde_json::Value::Null,
})],
annotations: Default::default(),
};
assert_eq!(final_text(&tool_only), None, "no text, no reply");
}
@@ -1014,6 +1255,7 @@ mod tests {
.expect("constructs"),
);
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0;
let on = ClawHandler::new(
registry.clone(),
"/tmp/w",
@@ -1031,12 +1273,12 @@ mod tests {
std::collections::BTreeMap::new(),
);
assert!(
on.agent_config("m", Path::new("/tmp/w"))
on.agent_config(provider.clone(), "m", Path::new("/tmp/w"))
.transcript
.is_some()
);
assert!(
off.agent_config("m", Path::new("/tmp/w"))
off.agent_config(provider, "m", Path::new("/tmp/w"))
.transcript
.is_none()
);
+81 -4
View File
@@ -123,6 +123,9 @@ pub struct ClawState {
/// The phone tables: the command queue the device polls and the
/// reported state the ingest door feeds.
phone: Arc<crate::phone::PhoneStore>,
/// Where the agent's `bash` runs: the live choice `/v1/sandbox`
/// edits, shared with every handler.
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>,
/// The scoped agent token the client tools hold: a second bearer
/// answering only the contract's data routes (see
@@ -146,7 +149,7 @@ impl ClawState {
/// `agent_token`.
#[expect(
clippy::too_many_arguments,
reason = "eighteen parts, each load-bearing"
reason = "twenty-one parts, each load-bearing"
)]
pub fn new(
dispatcher: Arc<Dispatcher>,
@@ -167,6 +170,7 @@ impl ClawState {
bridge: Arc<crate::consents::WaitBridge>,
attachments: Arc<crate::attachments::AttachmentStore>,
phone: Arc<crate::phone::PhoneStore>,
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>,
agent_token: Option<String>,
ingest_token: Option<String>,
@@ -190,6 +194,7 @@ impl ClawState {
bridge,
attachments,
phone,
sandbox,
token,
agent_token,
ingest_token,
@@ -289,6 +294,11 @@ impl ClawState {
pub fn watches(&self) -> &ClawStore {
&self.watches
}
/// Where the agent's `bash` runs.
pub fn sandbox(&self) -> &crate::sandbox::SandboxState {
&self.sandbox
}
}
/// The app router: `/healthz` open, `/v1` behind the bearer check when
@@ -343,6 +353,7 @@ pub fn router(state: ClawState) -> Router {
)
.route("/providers/{id}", delete(providers_remove))
.route("/providers/{id}/models", get(providers_models))
.route("/sandbox", get(sandbox_get).put(sandbox_put))
.route(
"/chat/completions",
post(crate::openai::chat_completions)
@@ -652,12 +663,20 @@ pub const MAX_INBOUND_IMAGES: usize = 8;
pub const MAX_MESSAGE_BODY_BYTES: usize =
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
/// `{"text": "..."}` — one chat message, plus the images it carries.
/// A body without `images` is the old shape, unchanged.
/// `{"text": "..."}` — one chat message, plus the images and the chip
/// payloads it carries. A body without `images` or `pastes` is the old
/// shape, unchanged.
#[derive(Deserialize)]
pub struct MessageBody {
/// The message text.
/// The message text, plain: each paste payload appended to it in
/// the fold, its chip noted as a span in the recorded event — no
/// mark form on the wire.
pub text: String,
/// The message's staged chips, payloads in order. A sender that
/// mints the legacy mark form sends none; the fold rewrites that
/// form too.
#[serde(default)]
pub pastes: Vec<String>,
/// The message's inline images, each the full MIME type plus bare
/// base64. The route checks the budget, then the dispatch copies
/// the bytes into the attachment store — the stream carries ids,
@@ -729,6 +748,7 @@ async fn messages(
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
key.as_str(),
&body.text,
&body.pastes,
&body.images,
)) {
return (
@@ -1982,6 +2002,63 @@ pub(crate) async fn drain_owned(
}
}
/// `GET /v1/sandbox`: where the agent's `bash` runs. The token never
/// rides the wire: `token_set` says whether one is stored.
async fn sandbox_get(State(state): State<ClawState>) -> Json<Value> {
Json(sandbox_json(&state))
}
/// The sandbox state as the wire sees it: the shared body of the read
/// and of the write that answers with the new choice.
fn sandbox_json(state: &ClawState) -> Value {
let choice = state.sandbox().choice();
json!({
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
})
}
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` is write-only; `clear_token` drops the
/// stored one. The choice applies on the next turn, no restart.
async fn sandbox_put(
State(state): State<ClawState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let Some(kind) = body["kind"].as_str() else {
return Err(bad_request("body must carry a sandbox kind"));
};
let kind = crate::sandbox::SandboxKind::parse(kind)
.ok_or_else(|| bad_request(format!("unknown sandbox kind {kind:?}")))?;
let current = state.sandbox().choice();
let clear_token = body["clear_token"].as_bool().unwrap_or(false);
let token = if clear_token {
None
} else {
body["token"]
.as_str()
.map(str::to_owned)
.or_else(|| current.token.clone())
};
let choice = crate::sandbox::SandboxChoice {
kind,
url: body["url"]
.as_str()
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
crate::sandbox::SandboxError::Store(_) => internal_error(err),
})?;
Ok(Json(sandbox_json(&state)))
}
/// `GET /v1/providers`: every constructible backend and the active pair.
/// The active pair is runtime state — the config file seeded it, the
/// settings store owns it now. Each provider is one instance, named by
+38 -4
View File
@@ -28,6 +28,7 @@
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};
use rhema_core::paste::PasteSpan;
use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
@@ -74,13 +75,23 @@ pub enum TurnEvent {
/// shows its own messages as it sends them, and skips the live
/// echo.
UserMessage {
/// The input text, verbatim.
/// The input text in the plain form the model read — each
/// paste's payload in place, no marks.
text: String,
/// The batch's images, in arrival order, as the attachment
/// store holds them. `default` because rows recorded before
/// images rode the transcript carry no field.
#[serde(default)]
images: Vec<UserImage>,
/// The paste chips the input carried, the same span record the
/// session's `rhema-code` annotation holds: the byte range
/// each chip stands for in `text`, plus its line count for the
/// label. `default` because rows recorded before chips rode
/// as spans carry the marks in the text instead — a client
/// that finds none scans for them; skipped when empty, so
/// rows without chips replay byte-for-byte as they landed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pastes: Vec<PasteSpan>,
},
/// A piece of the model's reasoning trace, in stream order.
ThinkingDelta {
@@ -565,10 +576,27 @@ mod tests {
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: Vec::new(),
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[]}"#
);
// The chip record rides only when there is one: the span
// shape is the session annotation's own, byte offsets over
// the plain text.
assert_eq!(
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: vec![PasteSpan {
start: 3,
end: 9,
lines: 4,
}],
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[],"pastes":[{"start":3,"end":9,"lines":4}]}"#
);
assert_eq!(
serde_json::to_string(&TurnEvent::ToolResult {
name: "bash".into(),
@@ -600,7 +628,8 @@ mod tests {
event,
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
}
@@ -614,7 +643,8 @@ mod tests {
assert_eq!(
TurnEvent::UserMessage {
text: "x".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
.kind(),
"user_message"
@@ -659,6 +689,7 @@ mod tests {
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text("hi"));
@@ -669,7 +700,8 @@ mod tests {
vec![
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
},
text("hi"),
],
@@ -795,6 +827,7 @@ mod tests {
TurnEvent::UserMessage {
text: "earlier".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
let (history, mut receiver) = hub.subscribe_with_history(&key);
@@ -896,6 +929,7 @@ mod tests {
TurnEvent::UserMessage {
text: format!("q{turn}"),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text(&format!("a{turn}")));
+314 -66
View File
@@ -46,7 +46,8 @@
//! v1's starting point — and the resolver chain are assembled before
//! the first model call; the model never decides its own permissions.
//! The chain is the core toolsets (the shell over the interactive
//! workspace, memory, `bootstrap_save`) plus every
//! workspace, or over the sandbox root when one is selected; memory,
//! `bootstrap_save`) plus every
//! [`crate::extension::ClawExtension`]'s tools in the standard set's
//! order. The system prompt is rendered per dispatch from the
//! bootstrap template over the live SOUL/USER files.
@@ -63,16 +64,18 @@
//! rhema-code's UI draws for a steered turn.
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use rhema_agent_tools::{AllowAll, ExpandPastes, ShellTools, revive_dangling_calls};
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
ModelProvider, Role, Session, ToolContext, ToolResolver, close_orphaned_calls, run_turn,
ModelProvider, Role, Session, ToolContext, ToolResolver, close_orphaned_calls,
revive_dangling_calls, run_turn,
};
use rhema_memory::{MemoryResolver, MemoryStore, Scope};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
@@ -82,6 +85,7 @@ use crate::backends::BackendRegistry;
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
use crate::hub::{EventHub, TurnEvent, UserImage};
use crate::notifications::NotificationStore;
use crate::sandbox::SandboxState;
use crate::steer::{SteerGuard, SteerRegistry};
/// The key prefixes of the resident context (see the module docs):
@@ -162,10 +166,10 @@ pub struct WireImage {
/// The event one chat message becomes. The id is unique per message (a
/// wall-clock millisecond plus a process counter), so a redelivery
/// never dedups a different message away. The payload carries the
/// message's images when it has any, and no `images` key when it has
/// none — old payloads stay byte-identical.
pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
/// never dedups a different message away. The chips' payloads ride
/// beside the text, and the images with them, each only when the
/// message staged any — payloads without chips stay byte-identical.
pub fn user_event(key: &str, text: &str, pastes: &[String], images: &[WireImage]) -> Event {
static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -177,10 +181,18 @@ pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
MESSAGE_SEQ.fetch_add(1, Ordering::Relaxed)
),
source: SOURCE.to_owned(),
payload: if images.is_empty() {
json!({ "key": key, "text": text })
} else {
json!({ "key": key, "text": text, "images": images })
// The chips' payloads ride only when the message staged any,
// and images only when it carried any: the old two-field shape
// rides byte-for-byte otherwise.
payload: {
let mut payload = json!({ "key": key, "text": text });
if !pastes.is_empty() {
payload["pastes"] = json!(pastes);
}
if !images.is_empty() {
payload["images"] = json!(images);
}
payload
},
received_at: now.as_millis() as u64,
}
@@ -232,7 +244,7 @@ pub struct InteractiveHandler {
/// How many tool rounds one turn may run before it is cut off — the
/// config's runaway guard for an agent meant to work unattended; a
/// follow-up message keeps going.
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
/// The extension set the tool half of the chain is cut from, per
/// dispatch, in the standard set's order — the same set whose
/// sources the daemon's tick drives and whose boot pass runs first.
@@ -241,10 +253,14 @@ pub struct InteractiveHandler {
/// decorator refreshes it per request, `zoom` reads it, and it
/// lives here — the agent rebuilds per dispatch, the log must not.
transcript_mirror: Option<Arc<std::sync::Mutex<rhema_transcript::Transcript>>>,
/// The wired [`vision`](rhema_agent_tools::vision) section for the
/// The wired [`vision`](rhema_bash::vision) section for the
/// prompt, when provisioning succeeded — the same wiring whose env
/// map lights the shell's inbox up.
vision: Option<String>,
/// Where commands run: this host when absent, a remote sandbox
/// when the surface selected one. Read per dispatch, so a switch
/// takes effect on the next turn.
sandbox: Option<Arc<SandboxState>>,
}
impl InteractiveHandler {
@@ -265,7 +281,7 @@ impl InteractiveHandler {
hub: Arc<EventHub>,
notifications: Arc<NotificationStore>,
attachments: Arc<crate::attachments::AttachmentStore>,
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
extensions: Arc<crate::extension::Extensions>,
transcript: bool,
) -> Self {
@@ -274,7 +290,7 @@ impl InteractiveHandler {
// chat's commands, and its staged images attach to their
// results. Local shells only — the interactive handler's
// executor is this host's by construction.
let vision = rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV"));
let vision = rhema_bash::vision::wire(std::env::var_os("BASH_ENV"));
let tools = Arc::new(match vision {
Some(wiring) => ShellTools::with_env(&workspace, &wiring.shell_env),
None => ShellTools::new(&workspace),
@@ -301,9 +317,17 @@ impl InteractiveHandler {
)))
}),
vision: vision.map(|wiring| wiring.section.to_owned()),
sandbox: None,
}
}
/// Shares the deployment's sandbox choice: commands run where it
/// says, and a remote sandbox replaces the host shell for `bash`.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// The agent for one dispatch: rebuilt per run over the restored
/// session (the engine's own step counter is per-agent; the
/// conversation lives in the session, not the agent). The system
@@ -314,12 +338,7 @@ impl InteractiveHandler {
/// request advertises.
fn agent(&self, key: &ResourceKey) -> Result<Agent, String> {
let (provider, model) = self.backends.current();
// Chat input may carry embedded pastes — the compact chip form
// the UIs mint and the session keeps — so the provider wraps in
// the same expansion the coding driver wraps its own with: the
// model sees plain text, the transcript keeps the chips.
let provider: Arc<dyn ModelProvider> = Arc::new(ExpandPastes::new(provider));
// The view rides outside the expansion: stubs, whole messages,
// The view rides outside the engine: stubs, whole messages,
// and zoom output all show the text the model would have seen.
let provider: Arc<dyn ModelProvider> = match &self.transcript_mirror {
Some(mirror) => Arc::new(rhema_transcript::TranscriptView::new(
@@ -329,13 +348,23 @@ impl InteractiveHandler {
None => provider,
};
let resolver = self.resolver(key);
let workspace = self.workspace();
let vision = if self
.sandbox
.as_ref()
.is_some_and(|sandbox| sandbox.is_remote())
{
None
} else {
self.vision.as_deref()
};
let system = render_system(
DEFAULT_SYSTEM_MD,
key.as_str(),
&self.workspace,
&workspace,
&self.bootstrap,
&resolver.specs(),
self.vision.as_deref(),
vision,
)
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
Agent::builder()
@@ -356,6 +385,15 @@ impl InteractiveHandler {
self
}
/// The workspace the prompt names: the host path locally, the
/// sandbox root when commands run elsewhere.
fn workspace(&self) -> PathBuf {
match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(&self.workspace),
None => self.workspace.clone(),
}
}
/// The resolver chain one dispatch runs under: the core toolsets —
/// the shell over the interactive workspace, memory,
/// `bootstrap_save` — then every extension's tools in the standard
@@ -364,8 +402,18 @@ impl InteractiveHandler {
/// their asks and cards to the session that asked, and the handler
/// serves every session.
fn resolver(&self, key: &ResourceKey) -> Arc<ResolverChain> {
let shell: Arc<dyn rhema_core::ToolResolver> = match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
let workspace = sandbox.workspace_for(&self.workspace);
let tools =
ShellTools::with_executor(workspace, sandbox.executor(self.workspace.clone()));
tools.install_approval(Arc::new(AllowAll));
Arc::new(tools)
}
_ => self.tools.clone(),
};
let mut resolvers: Vec<Arc<dyn rhema_core::ToolResolver>> = vec![
self.tools.clone(),
shell,
Arc::new(MemoryResolver::new(
self.memory.clone(),
Scope::Workspace(self.workspace.clone()),
@@ -401,7 +449,9 @@ impl InteractiveHandler {
.await
.map_err(|err| format!("inbox poll for {key} failed: {err}"))?;
// Texts fold in arrival order, and so do the images, across
// the whole batch whichever events carried them.
// the whole batch whichever events carried them — each text
// with its chips already composed in, their spans measured
// over it.
let mut texts = Vec::new();
let mut images = Vec::new();
for item in &items {
@@ -411,7 +461,35 @@ impl InteractiveHandler {
.or_else(|| payload.get("prompt"))
.and_then(Value::as_str)
{
texts.push(text);
// The fold owns the chip record. A legacy sender's
// marks ride the text and migrate here, per message;
// a payload chip appends in order right after —
// plain either way before the join, its span
// measured where it lands.
let mut message = [Message::text(Role::User, text.to_owned())];
rhema_core::paste::migrate(&mut message);
let mut spans = rhema_core::paste::spans(&message[0]);
let mut composed = match &message[0].content[0] {
Content::Text(text) => text.clone(),
_ => unreachable!("the message was built with one text block"),
};
for paste in payload
.get("pastes")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(rhema_core::paste::normalize)
{
let span = rhema_core::paste::PasteSpan {
start: composed.len(),
end: composed.len() + paste.len(),
lines: paste.lines().count(),
};
composed.push_str(&paste);
spans.push(span);
}
texts.push((composed, spans));
}
if let Some(carried) = payload.get("images").and_then(Value::as_array) {
images.extend(
@@ -421,7 +499,22 @@ impl InteractiveHandler {
);
}
}
let input = texts.join("\n\n");
let mut input = String::new();
let mut pastes = Vec::new();
let mut first = true;
for (text, spans) in texts {
if !first {
input.push_str("\n\n");
}
let base = input.len();
input.push_str(&text);
pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan {
start: span.start + base,
end: span.end + base,
lines: span.lines,
}));
first = false;
}
if input.trim().is_empty() {
// Round one's emptiness is the dispatch bug it always was:
// the lease exists because something waited. A steered
@@ -472,13 +565,17 @@ impl InteractiveHandler {
}
// The transcript's question, recorded before anything else can
// stream: a replay shows what was asked, not only what was
// answered. Raw input — the notification-contract framing below
// is the model's business, not the viewer's.
// answered. The fold composed the record — plain text, the
// chip spans beside it — and the turn runs this exact input;
// the notification-contract framing below is the model's
// business, not the viewer's.
let recorded_len = input.len();
self.hub.emit(
&ctx.key,
TurnEvent::UserMessage {
text: input.clone(),
images: transcript_images,
pastes: pastes.clone(),
},
);
// A non-chat resident key has no subscriber to read the reply:
@@ -532,10 +629,29 @@ impl InteractiveHandler {
// future at its current await — a streaming request, or a
// running shell command, whose child dies with the drop. The
// next round revives whatever committed before the drop.
// The input rides in the plain form the fold recorded — the
// payloads sit in the text and the model never sees a mark —
// with the span note riding the message, so the checkpoint
// (and a session resumed from it) keeps the chips beside the
// plain text. The framings above live in the model's copy:
// their bytes are known exactly, and each span shifts by them,
// still pointing into the text it annotates.
let framed_len = input.len();
let pastes = pastes
.iter()
.map(|span| rhema_core::paste::PasteSpan {
start: span.start + framed_len - recorded_len,
end: span.end + framed_len - recorded_len,
lines: span.lines,
})
.collect::<Vec<_>>();
let mut question = [Message::text_with_images(Role::User, input, core_images)];
rhema_core::paste::annotate(&mut question[0], &pastes);
let [turn_input] = question;
let mut turn = Box::pin(run_turn(
&mut agent,
&mut session,
Message::text_with_images(Role::User, input, core_images),
turn_input,
&mut sink,
&tools,
self.max_turn_steps,
@@ -679,8 +795,16 @@ enum Round {
fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
match stashed {
Value::Null => Ok(Session::default()),
stashed => serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}")),
stashed => {
let mut session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
// A session stashed before paste spans existed carries the
// embedded form in its prompts; the provider must never see
// a mark. One rewrite on the way in, chips survive as the
// span note — the same pass the driver's from_session runs.
rhema_core::paste::migrate(&mut session.history);
Ok(session)
}
}
}
@@ -794,6 +918,10 @@ impl EventSink for HubSink {
| ModelEvent::Usage(_)
| ModelEvent::RetryWait { .. }
| ModelEvent::StepEnd { .. } => return,
// The engine's event enum is non-exhaustive: a future
// event arrives here, dropped like the rest of the engine's
// own bookkeeping until a turn-event shape exists for it.
_ => return,
};
self.hub.emit(&self.key, turn);
}
@@ -1056,12 +1184,17 @@ mod tests {
}
}
/// The paste contract across the provider seam: a chat input that
/// carries an embedded paste (the compact form the UIs mint) is
/// expanded before the request leaves, while the transcript the hub
/// streams keeps the compact form.
#[tokio::test]
async fn an_embedded_paste_expands_for_the_model_and_not_for_the_transcript() {
/// The environment a paste test drives: the recording provider, the
/// hub, and a dispatcher wired to one interactive handler over a
/// throwaway workspace.
fn paste_env() -> (
Arc<RecordingProvider>,
Arc<EventHub>,
Arc<Dispatcher>,
InteractiveHandler,
Key,
tempfile::TempDir,
) {
let recorder = RecordingProvider::new();
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let hub = Arc::new(EventHub::default());
@@ -1087,7 +1220,7 @@ mod tests {
Arc::new(rhema_memory::VolatileStore::new()),
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
hub.clone(),
notifications.clone(),
notifications,
attachments(),
crate::config::DEFAULT_MAX_TURN_STEPS,
extensions,
@@ -1102,14 +1235,31 @@ mod tests {
Arc::new(VolatileStore::new()),
));
register_user(&dispatcher);
(
recorder,
hub,
dispatcher,
handler,
Key::from("interactive:web"),
workspace,
)
}
/// The legacy intake: a chat input still carrying the embedded
/// mark form migrates at the fold — the model reads the payload in
/// place, and the recorded question is the plain form with the
/// chip noted beside it.
#[tokio::test]
async fn an_embedded_arrival_migrates_at_the_fold() {
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let key = Key::from("interactive:web");
dispatcher
.ingest(user_event(
key.as_str(),
"review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}",
&[],
&[],
))
.expect("ingests");
driver.run_once().await.expect("the run happens");
@@ -1119,17 +1269,61 @@ mod tests {
"review this:fn main() {}\nfn other() {}",
"the model saw the payload, not the marks"
);
// The recorded question is the plain form, the chip record
// riding beside it as spans: the mark form lives on only in
// rows recorded before chips rode as spans.
let (history, _) = hub.subscribe_with_history(&key);
let saw_input = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, .. } => Some(text),
let question = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
_ => None,
});
assert!(
saw_input
.expect("the transcript saw the question")
.contains('\u{FFFC}'),
"the transcript keeps the compact chip form"
let (text, pastes) = question.expect("the transcript saw the question");
let payload = "fn main() {}\nfn other() {}";
assert_eq!(text, "review this:fn main() {}\nfn other() {}", "no marks");
assert_eq!(pastes.len(), 1, "the chip is one span");
assert_eq!(pastes[0].start, "review this:".len());
assert_eq!(pastes[0].end, "review this:".len() + payload.len());
assert_eq!(pastes[0].lines, 2);
}
/// The modern intake: chips ride as payloads beside their message,
/// each appending to it — no mark on the wire, the span record born
/// at the fold. A payload's carriage returns and stray marks
/// normalize there too, so a chip can never re-cut the scan.
#[tokio::test]
async fn a_staged_chip_rides_its_payload_beside_the_question() {
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
dispatcher
.ingest(user_event(
key.as_str(),
"review this:",
&["fn main() {}\r\nfn other() {}\u{FFFC}".to_owned()],
&[],
))
.expect("ingests");
driver.run_once().await.expect("the run happens");
// The model read the draft with the normalized payload
// appended: what the record says is what the request carried.
assert_eq!(
recorder.last_user_text(),
"review this:fn main() {}\nfn other() {}",
"the model saw the payload, normalized, in place"
);
let (history, _) = hub.subscribe_with_history(&key);
let question = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
_ => None,
});
let (text, pastes) = question.expect("the transcript saw the question");
let payload = "fn main() {}\nfn other() {}";
assert_eq!(text, format!("review this:{payload}"), "the plain form");
assert_eq!(pastes.len(), 1, "the chip is one span");
assert_eq!(pastes[0].start, "review this:".len());
assert_eq!(pastes[0].end, "review this:".len() + payload.len());
assert_eq!(pastes[0].lines, 2);
}
/// A scripted tool-call turn: the model asking for `name` with `args`.
@@ -1143,6 +1337,7 @@ mod tests {
args,
provider_data: serde_json::Value::Null,
})],
annotations: Default::default(),
},
stop_reason: StopReason::ToolUse,
usage: Usage::default(),
@@ -1253,8 +1448,8 @@ mod tests {
#[test]
fn user_events_carry_the_key_and_unique_ids() {
let first = user_event("interactive:web", "hello", &[]);
let second = user_event("interactive:web", "again", &[]);
let first = user_event("interactive:web", "hello", &[], &[]);
let second = user_event("interactive:web", "again", &[], &[]);
assert_eq!(first.source, "user");
assert_eq!(first.id, first.id, "stable within itself");
assert_ne!(first.id, second.id, "messages never share a dedup id");
@@ -1268,7 +1463,7 @@ mod tests {
/// order; a plain message carries no `images` key at all.
#[test]
fn user_events_carry_images_only_when_the_message_has_any() {
let bare = user_event("interactive:web", "plain", &[]);
let bare = user_event("interactive:web", "plain", &[], &[]);
assert_eq!(
bare.payload,
json!({"key": "interactive:web", "text": "plain"}),
@@ -1277,6 +1472,7 @@ mod tests {
let carried = user_event(
"interactive:web",
"look",
&[],
&[
WireImage {
media_type: "image/png".to_owned(),
@@ -1309,7 +1505,7 @@ mod tests {
Arc::new(VolatileStore::new()),
);
register_user(&dispatcher);
let event = user_event("interactive:web", "hello", &[]);
let event = user_event("interactive:web", "hello", &[], &[]);
// Ingesting resolves the key through the registered fn: the
// record lands under exactly the payload's key.
dispatcher.ingest(event).expect("ingests");
@@ -1344,11 +1540,13 @@ mod tests {
Content::Text("on it".into()),
Content::Text(" — done.".into()),
],
annotations: Default::default(),
};
assert_eq!(final_text(&message).as_deref(), Some("on it — done."));
let empty = Message {
role: Role::Assistant,
content: vec![Content::Text(" ".into())],
annotations: Default::default(),
};
assert_eq!(final_text(&empty), None);
}
@@ -1459,6 +1657,42 @@ mod tests {
assert!(err.contains("does not parse"), "{err}");
}
/// A session stashed before paste spans existed carries the embedded
/// form in its prompts; the restore pass rewrites it so a provider
/// never sees a mark, and the chip rides as the span note instead.
#[test]
fn a_legacy_stash_is_migrated_on_restore() {
let payload = "l1\nl2\nl3";
let embedded = format!("review this:\u{FFFC}{payload}\u{FFFC} please");
let stashed = json!({
"history": [
{
"role": "user",
"content": [embedded]
}
],
"driver_state": serde_json::Value::Null
});
let session = restore_session(&stashed, "interactive:web").expect("the legacy stash loads");
assert_eq!(
final_text(&session.history[0]),
Some(format!("review this:{payload} please")),
"the mark and its payload land as plain text"
);
let text = final_text(&session.history[0]).expect("the prompt is text");
// The chip rides as the span note: one span, over exactly the
// payload's range, and no mark survives the restore.
assert_eq!(
rhema_core::paste::spans(&session.history[0]).as_slice(),
&[rhema_core::paste::PasteSpan {
start: "review this:".len(),
end: "review this:".len() + payload.len(),
lines: 3,
}]
);
assert!(!text.contains('\u{FFFC}'), "no mark survives the restore");
}
/// The full dispatch, in-process: one message in, one scripted reply
/// out, the turn streamed through the hub, the conversation stashed.
#[tokio::test]
@@ -1507,7 +1741,7 @@ mod tests {
let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key);
dispatcher
.ingest(user_event(key.as_str(), "hello", &[]))
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
@@ -1520,7 +1754,8 @@ mod tests {
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
@@ -1596,7 +1831,7 @@ mod tests {
let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key);
dispatcher
.ingest(user_event(key.as_str(), "hello", &[]))
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
@@ -1616,7 +1851,7 @@ mod tests {
// Steer, in the route's order: ingest first, signal second.
dispatcher
.ingest(user_event(key.as_str(), "stop that", &[]))
.ingest(user_event(key.as_str(), "stop that", &[], &[]))
.expect("ingests");
assert!(registry.signal(key.as_str()));
@@ -1633,7 +1868,8 @@ mod tests {
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
@@ -1647,7 +1883,8 @@ mod tests {
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "stop that".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
@@ -1821,6 +2058,7 @@ mod tests {
.ingest(user_event(
key.as_str(),
"look at this",
&[],
&[WireImage {
media_type: "image/png".to_owned(),
data: png.clone(),
@@ -1831,6 +2069,7 @@ mod tests {
.ingest(user_event(
key.as_str(),
"and at this",
&[],
&[WireImage {
media_type: "Image/JPEG".to_owned(),
data: jpeg.clone(),
@@ -1838,7 +2077,7 @@ mod tests {
))
.expect("ingests");
dispatcher
.ingest(user_event(key.as_str(), "no picture here", &[]))
.ingest(user_event(key.as_str(), "no picture here", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("the run happens"),
@@ -1851,7 +2090,11 @@ mod tests {
let question = history
.iter()
.find_map(|event| match event {
TurnEvent::UserMessage { text, images } => Some((text.clone(), images.clone())),
TurnEvent::UserMessage {
text,
pastes,
images,
} => Some((text.clone(), images.clone(), pastes.clone())),
_ => None,
})
.expect("the transcript saw the question");
@@ -1957,7 +2200,7 @@ mod tests {
// Dispatch 1: the model saves through the chain's memory tools.
dispatcher
.ingest(user_event(key.as_str(), "remember the channel", &[]))
.ingest(user_event(key.as_str(), "remember the channel", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("first run"),
@@ -1976,7 +2219,7 @@ mod tests {
// Dispatch 2: the model searches the same chain and answers from
// memory — a fresh session turn, the same durable store.
dispatcher
.ingest(user_event(key.as_str(), "where do releases go?", &[]))
.ingest(user_event(key.as_str(), "where do releases go?", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("second run"),
@@ -2064,7 +2307,7 @@ mod tests {
// Dispatch 1: the model writes SOUL.md through the chain. A key
// with a session continues, so both calls ride one key.
dispatcher
.ingest(user_event(key.as_str(), "call me claw", &[]))
.ingest(user_event(key.as_str(), "call me claw", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("first run"),
@@ -2083,7 +2326,7 @@ mod tests {
// Dispatch 2: USER.md, same chain — and the pending flag clears.
dispatcher
.ingest(user_event(key.as_str(), "and I am Ana", &[]))
.ingest(user_event(key.as_str(), "and I am Ana", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("second run"),
@@ -2141,7 +2384,7 @@ mod tests {
register_user(&dispatcher);
let key = Key::from("interactive:web");
dispatcher
.ingest(user_event(key.as_str(), "hello", &[]))
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
driver.run_once().await.expect("the run happens");
@@ -2281,7 +2524,7 @@ mod tests {
// An interactive reply is the chat surface's business: notified
// nowhere.
dispatcher
.ingest(user_event("interactive:web", "hello", &[]))
.ingest(user_event("interactive:web", "hello", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("the run happens"),
@@ -2359,7 +2602,12 @@ mod tests {
// The evening's work, in the chat session.
dispatcher
.ingest(user_event(key.as_str(), "we shipped the claw tonight", &[]))
.ingest(user_event(
key.as_str(),
"we shipped the claw tonight",
&[],
&[],
))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("first run"),
+45 -11
View File
@@ -13,7 +13,7 @@
//! instance and job resolve through the store, the workspace is the
//! instance's path, the session blob (or a fresh agent) is loaded, the
//! allowlist is permissive exactly as the forge path's — and then one
//! `CodingAgent` turn runs. The final text lands in the job row and
//! `HostAgent` turn runs. The final text lands in the job row and
//! the user's notifications; the turn itself streams nowhere, its
//! observability is the stderr tool log.
//!
@@ -22,11 +22,13 @@
//! fails before any model call. The trust boundary is unchanged from
//! the forge path — the bearer-gated surface and the instance list.
use std::num::NonZeroU32;
use std::sync::Arc;
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
use rhema_coding_agent::{AllowAll, CodingAgent, CodingAgentConfig};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Event as ModelEvent, EventSink};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use crate::backends::BackendRegistry;
@@ -34,6 +36,7 @@ use crate::handler::final_text;
use crate::interactive::passthrough_key_fn;
use crate::job_store::{CodingJobStore, JobStatus};
use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
use crate::sandbox::SandboxState;
/// The source name the coding jobs ingest under.
pub const JOBS_SOURCE: &str = "jobs";
@@ -137,10 +140,13 @@ pub struct CodingJobHandler {
backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>,
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
/// Whether the jobs run the bounded request view (the config's
/// `transcript`, on unless set false).
transcript: bool,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>,
}
impl CodingJobHandler {
@@ -151,7 +157,7 @@ impl CodingJobHandler {
backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>,
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
transcript: bool,
) -> Self {
Self {
@@ -160,9 +166,17 @@ impl CodingJobHandler {
notifications,
max_turn_steps,
transcript,
sandbox: None,
}
}
/// Shares the deployment's sandbox choice: a job's commands run
/// where it says, seeded from the instance's host path.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// One dispatch, failed with a reason on any step; every failure
/// lands in the job row before it lands in the outcome, so the
/// model's `status` read and the user's notification agree.
@@ -212,7 +226,11 @@ impl CodingJobHandler {
.map_err(|err| format!("job {job_id} could not start: {err}"))?;
let (provider, model) = self.backends.current();
let mut config = CodingAgentConfig::new(model, &workspace);
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(&workspace),
None => workspace.clone(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
config.max_turn_steps = self.max_turn_steps;
// A job's stashed session carries across runs and only ever
// grows; the view is what keeps a repeat run's steps cheap.
@@ -221,8 +239,18 @@ impl CodingJobHandler {
config.transcript = self
.transcript
.then(rhema_transcript::TranscriptSettings::default);
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display,
sandbox.executor(workspace.clone()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
}
}
let stashed = self
.store
.session(&instance_name)
@@ -236,9 +264,9 @@ impl CodingJobHandler {
self.fail(job_id, &instance_name, &reason);
reason
})?;
CodingAgent::from_session(provider, config, session)
HostAgent::from_session(config, session)
}
None => CodingAgent::new(provider, config),
None => HostAgent::new(config),
}
.map_err(|err| {
let reason = format!("cannot start the coding agent for {instance_name:?}: {err}");
@@ -248,12 +276,12 @@ impl CodingJobHandler {
// Commit-before-execute rides the dispatcher exactly as the
// forge handler's does: the intent is in the store before the
// first tool runs, and a crash-left dangling call revives at
// turn entry (CodingAgent::turn's own revive, over the resumed
// turn entry (HostAgent::turn's own revive, over the resumed
// session).
agent.set_commit_hook(Some(ctx.commit_hook()));
let mut sink = JobSink;
let output = match agent.turn(&job.prompt, &mut sink, Arc::new(AllowAll)).await {
let output = match agent.turn(&job.prompt, &mut sink).await {
Ok(output) => output,
Err(err) => {
let reason = format!("the coding turn for {instance_name:?} failed: {err}");
@@ -280,7 +308,7 @@ impl CodingJobHandler {
Ok(Outcome::Handled)
}
fn save_session(&self, instance: &str, agent: &CodingAgent) {
fn save_session(&self, instance: &str, agent: &HostAgent) {
match serde_json::to_string(agent.session()) {
Ok(blob) => {
let _ = self.store.save_session(instance, &blob);
@@ -360,7 +388,13 @@ mod tests {
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"),
);
CodingJobHandler::new(backends, store, notifications, 16, true)
CodingJobHandler::new(
backends,
store,
notifications,
NonZeroU32::new(16).unwrap(),
true,
)
}
fn reply(text: &str) -> ModelOutput {
+8 -2
View File
@@ -42,6 +42,8 @@
//! workspace files handed to the human as fetchable cards
//! - [`phone`] — the phone state and command queue: reported status to
//! read, consent-gated control actions the device executes
//! - [`sandbox`]: where `bash` runs, this host, or a remote daemon
//! speaking the sandbox protocol over HTTP
//! - [`watch_tools`] — the agent's watch-management tool set
//! - [`notify_tools`] — the `notify` tool: the queue a device polls
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
@@ -89,6 +91,7 @@ pub mod notifications;
pub mod notify_tools;
pub mod openai;
pub mod phone;
pub mod sandbox;
pub mod settings;
pub mod steer;
pub mod task_source;
@@ -105,7 +108,7 @@ pub use bootstrap::{
render_system,
};
pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, run_once};
pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
pub use environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource;
@@ -117,8 +120,11 @@ pub use interactive::InteractiveHandler;
pub use mock::MockLoop;
pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError};
pub use rhema_forge_integration::{ForgeKind, resolve_token};
pub use sandbox::{SandboxChoice, SandboxError, SandboxKind, SandboxState};
pub use settings::SettingsStore;
pub use task_source::{TASKS_SOURCE, TaskScheduler};
pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError};
pub use turn_store::{TurnStore, TurnStoreError};
pub use watch_store::{ClawStore, Watch, WatchRecord, WatchShapeError, WatchStoreError};
pub use watch_store::{
ClawStore, SCOPE_ACCOUNT, SCOPE_REPO, Watch, WatchRecord, WatchShapeError, WatchStoreError,
};
+5 -5
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once};
use rhema_rsd::{DispatcherConfig, Outcome};
use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::Outcome;
/// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)]
@@ -74,9 +74,9 @@ async fn main() {
}
if let Some(Command::Vision { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1);
argv.push(std::ffi::OsString::from(rhema_agent_tools::vision::MODE));
argv.push(std::ffi::OsString::from(rhema_bash::vision::MODE));
argv.extend(rest.iter().cloned());
std::process::exit(rhema_agent_tools::vision::cli_run(&argv));
std::process::exit(rhema_bash::vision::cli_run(&argv));
}
if let Err(err) = run(args).await {
eprintln!("error: {err}");
@@ -135,7 +135,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on.
config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts");
let daemon = Daemon::build(&config, backends, DispatcherConfig::default())?;
let daemon = Daemon::build(&config, backends, forge_dispatch())?;
daemon.run().await
}
}
+8 -3
View File
@@ -9,7 +9,7 @@
use std::collections::BTreeSet;
use std::sync::{Arc, OnceLock};
use rhema_coding_agent::CodingAgentConfig;
use rhema_host_agent::HostAgentConfig;
/// What one wiring produced, held for the process.
struct Wired {
@@ -61,7 +61,7 @@ fn wired() -> Option<&'static Wired> {
/// init file, the socket, the token), the prompt's `mcp` lines, and
/// the persisted off switch. A frontend without wiring changes
/// nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) {
pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else {
return;
};
@@ -82,7 +82,12 @@ mod tests {
/// same map).
#[test]
fn apply_without_any_wiring_leaves_the_config_alone() {
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
let before = config.shell_env.clone();
apply(&mut config);
// The wiring only appears when the machine's global mcp.yaml
+1
View File
@@ -65,6 +65,7 @@ impl ModelProvider for MockLoop {
message: Message {
role: Role::Assistant,
content: vec![Content::Text(text)],
annotations: Default::default(),
},
stop_reason: StopReason::EndTurn,
usage: Usage::default(),
+1
View File
@@ -259,6 +259,7 @@ pub async fn chat_completions(
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
key.as_str(),
&input.text,
&[],
&input.images,
)) {
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
+577
View File
@@ -0,0 +1,577 @@
//! Where the claw's `bash` runs: this host's processes, or a daemon
//! speaking the sandbox protocol over HTTP.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
//! and gives the handlers a `ShellSandbox` executor over it. The tool
//! spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes `/workspace` and, when it is empty,
//! sends the host workspace as a tarball through the protocol's seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use base64::Engine as _;
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path a remote sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
const PROBE_TIMEOUT: Duration = Duration::from_secs(20);
/// Which machine runs the shell.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxKind {
/// The daemon's own host, the original path.
#[default]
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
}
impl SandboxKind {
/// The stored spelling.
pub fn as_str(self) -> &'static str {
match self {
Self::Local => "local",
Self::Http => "http",
}
}
/// Parses a stored spelling. Anything else is `None`, which every
/// caller turns into the local default.
pub fn parse(value: &str) -> Option<Self> {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
_ => None,
}
}
}
/// One sandbox choice: the kind and whatever it needs. `local` needs
/// nothing; `http` needs a base URL and may carry a token.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct SandboxChoice {
/// The machine kind.
pub kind: SandboxKind,
/// The `http` sandbox's base URL, no trailing slash after
/// normalization.
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
impl SandboxChoice {
/// Trims the strings, drops blank ones, and validates what `http`
/// needs to run. A choice that fails reads as a 400 at the route,
/// never as a silent fallback.
pub fn normalized(mut self) -> Result<Self, SandboxError> {
self.url = self
.url
.map(|url| url.trim().trim_end_matches('/').to_owned())
.filter(|url| !url.is_empty());
self.token = self
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
if self.kind == SandboxKind::Http {
let url = self
.url
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the http sandbox needs a url".to_owned()))?;
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err(SandboxError::Invalid(
"the http sandbox url must start with http:// or https://".to_owned(),
));
}
}
Ok(self)
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind == SandboxKind::Http
}
}
/// Why a sandbox choice or operation failed.
#[derive(Debug, thiserror::Error)]
pub enum SandboxError {
/// The choice cannot run as written.
#[error("{0}")]
Invalid(String),
/// The settings table failed.
#[error("sandbox store failed: {0}")]
Store(String),
}
/// The chosen sandbox and the executors built over it, shared by every
/// handler so a switch takes effect on the next turn without a restart.
pub struct SandboxState {
choice: RwLock<SandboxChoice>,
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
}
impl SandboxState {
/// The state over `settings`, seeded by `seed` when no choice was
/// stored. `local_workspace` is the chat workspace the settings
/// surface reports; `shell_env` is layered over local commands.
pub fn load(
settings: Arc<SettingsStore>,
seed: Option<SandboxChoice>,
local_workspace: PathBuf,
shell_env: &BTreeMap<String, String>,
) -> Result<Self, SandboxError> {
let stored = settings
.get(SANDBOX_KEY)
.map_err(|err| SandboxError::Store(err.to_string()))?;
let choice = stored
.as_deref()
.and_then(|raw| serde_json::from_str::<SandboxChoice>(raw).ok())
.and_then(|choice| choice.normalized().ok())
.or_else(|| seed.and_then(|choice| choice.normalized().ok()))
.unwrap_or_default();
Ok(Self {
choice: RwLock::new(choice),
settings,
local_workspace,
local: default_executor_with(shell_env),
remote: Mutex::new(HashMap::new()),
})
}
/// The current choice.
pub fn choice(&self) -> SandboxChoice {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.is_remote()
}
/// Saves and applies a choice. The next turn reads it; nothing is
/// rebuilt in place. Answers the normalized choice that was stored.
pub fn set(&self, choice: SandboxChoice) -> Result<SandboxChoice, SandboxError> {
let choice = choice.normalized()?;
let raw =
serde_json::to_string(&choice).map_err(|err| SandboxError::Store(err.to_string()))?;
self.settings
.set(SANDBOX_KEY, &raw)
.map_err(|err| SandboxError::Store(err.to_string()))?;
*self.choice.write().unwrap_or_else(PoisonError::into_inner) = choice.clone();
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
Ok(choice)
}
/// The workspace a handler should name and start commands in: the
/// host path locally, `/workspace` on a remote sandbox.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
if self.is_remote() {
PathBuf::from(REMOTE_WORKSPACE)
} else {
host.to_path_buf()
}
}
/// The chat workspace under the current choice, for the settings
/// surface.
pub fn workspace(&self) -> PathBuf {
self.workspace_for(&self.local_workspace)
}
/// The host workspace path, whatever the current choice.
pub fn local_workspace(&self) -> &Path {
&self.local_workspace
}
/// An executor for one host workspace. Remote sessions are derived
/// from the workspace path, so two workspaces never share a root.
pub fn executor(
self: &Arc<Self>,
host_workspace: impl Into<PathBuf>,
) -> Arc<dyn ShellExecutor> {
Arc::new(ClawShell {
state: Arc::clone(self),
host_workspace: host_workspace.into(),
local: self.local.clone(),
seeded: AtomicBool::new(false),
last: Mutex::new(None),
})
}
/// The cached HTTP client for one session. The map is cleared
/// whenever the choice changes, so a new URL or token builds a new
/// client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<HttpSandbox>, ShellError> {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(sandbox) = remote.get(&session) {
return Ok(sandbox.clone());
}
}
let token = choice.token.as_deref().unwrap_or("");
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(session, sandbox.clone());
Ok(sandbox)
}
}
/// One handler's view of the choice: local commands go straight to the
/// host executor; remote commands go through the sandbox, seeded from
/// the host workspace once per choice.
struct ClawShell {
state: Arc<SandboxState>,
host_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
seeded: AtomicBool,
last: Mutex<Option<SandboxChoice>>,
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty `/workspace` gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox.
async fn seed(
&self,
sandbox: &Arc<HttpSandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let mut sink = |_line: &str| {};
let probe = sandbox
.exec(
ExecRequest {
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
cwd: REMOTE_WORKSPACE.to_owned(),
timeout: PROBE_TIMEOUT,
},
cancelled,
&mut sink,
)
.await
.map_err(protocol_error)?;
if !probe.stdout.is_empty() {
return Ok(());
}
let root = self.host_workspace.clone();
let archive = tokio::task::spawn_blocking(move || tarball(&root))
.await
.map_err(|err| {
ShellError::Failed(format!("the workspace archive task failed: {err}"))
})??;
let Some(tar_gz_base64) = archive else {
return Ok(());
};
sandbox
.seed(&WorkspaceSeed::Tarball {
name: "workspace.tar.gz".to_owned(),
tar_gz_base64,
})
.await
.map_err(protocol_error)?;
Ok(())
}
}
#[async_trait]
impl ShellExecutor for ClawShell {
async fn run(
&self,
command: &str,
cwd: &Path,
timeout: Duration,
cancelled: &AtomicBool,
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
) -> Result<Executed, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self
.local
.run(command, cwd, timeout, cancelled, progress)
.await;
}
{
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
if last.as_ref() != Some(&choice) {
*last = Some(choice.clone());
self.seeded.store(false, Ordering::Relaxed);
}
}
let sandbox = self.state.remote_sandbox(&choice, &self.host_workspace)?;
if !self.seeded.load(Ordering::Relaxed) {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let sandbox: Arc<dyn Sandbox> = sandbox;
ShellSandbox::new(sandbox)
.run(
command,
Path::new(REMOTE_WORKSPACE),
timeout,
cancelled,
progress,
)
.await
}
}
/// Maps a protocol failure onto the shell error the tool shapes into an
/// `is_error` result.
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still
// a failure, reported in-band with its own text.
_ => ShellError::Failed(err.to_string()),
}
}
/// The sandbox session name for one host workspace: a stable FNV-1a
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
fn session_name(host: &Path) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in host.to_string_lossy().as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("rhema-claw-{hash:016x}")
}
/// One host workspace as a gzipped tar, base64 for the protocol.
/// `None` when the directory is missing or empty: nothing to seed.
fn tarball(root: &Path) -> Result<Option<String>, ShellError> {
if !root.is_dir() {
return Ok(None);
}
let mut entries = std::fs::read_dir(root)
.map_err(|err| ShellError::Failed(format!("cannot read the workspace {root:?}: {err}")))?;
if entries.next().is_none() {
return Ok(None);
}
let output = std::process::Command::new("tar")
.arg("-czf")
.arg("-")
.arg("-C")
.arg(root)
.arg(".")
.output()
.map_err(|err| {
ShellError::Failed(format!("cannot archive the workspace with tar: {err}"))
})?;
if !output.status.success() {
let detail = String::from_utf8_lossy(&output.stderr);
let detail = detail.trim();
return Err(ShellError::Failed(if detail.is_empty() {
"tar failed to archive the workspace".to_owned()
} else {
format!("tar failed to archive the workspace: {detail}")
}));
}
Ok(Some(
base64::engine::general_purpose::STANDARD.encode(output.stdout),
))
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn state(choice: SandboxChoice) -> Arc<SandboxState> {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
Arc::new(
SandboxState::load(
settings,
Some(choice),
PathBuf::from("/state/claw/workspaces/interactive"),
&BTreeMap::new(),
)
.expect("the state loads"),
)
}
#[test]
fn a_bare_choice_is_local() {
let choice = SandboxChoice::default().normalized().unwrap();
assert_eq!(choice.kind, SandboxKind::Local);
assert!(!choice.is_remote());
assert_eq!(choice.kind.as_str(), "local");
}
#[test]
fn an_http_choice_needs_an_absolute_url() {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
token: None,
}
.normalized();
assert!(missing.is_err(), "a URL is required");
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
token: None,
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
token: None,
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
state.choice().url.as_deref(),
Some("http://box:7600"),
"the trailing slash is trimmed"
);
}
#[test]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
assert_eq!(state.choice().kind, SandboxKind::Local);
state
.set(SandboxChoice {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Http);
assert_eq!(reloaded.choice().url.as_deref(), Some("https://box:7600"));
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
// The emptiness probe: nothing at /workspace.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "",
"stderr": "",
"timed_out": false
})))
.up_to_n_times(1)
.mount(&server)
.await;
// The command itself.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "hi\n",
"stderr": "",
"timed_out": false
})))
.mount(&server)
.await;
// The seed: accepted, and the host workspace is not empty.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/seed$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"error": null
})))
.expect(1)
.mount(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("README.md"), "seed me").expect("the file writes");
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
token: None,
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = |_line: &str| {};
let executed = executor
.run(
"echo hi",
Path::new(REMOTE_WORKSPACE),
Duration::from_secs(5),
&cancelled,
&mut sink,
)
.await
.expect("the remote command answers");
assert_eq!(executed.stdout, b"hi\n");
assert_eq!(executed.code, Some(0));
}
}
+3 -1
View File
@@ -325,6 +325,7 @@ mod tests {
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new(),
},
text_delta("hi"),
],
@@ -348,7 +349,8 @@ mod tests {
0,
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
),
(1, text_delta("hi")),
+14 -15
View File
@@ -9,21 +9,15 @@
#![forbid(unsafe_code)]
use std::sync::{Arc, OnceLock};
use std::sync::Arc;
use rhema_coding_agent::CodingAgentConfig;
use rhema_host_agent::HostAgentConfig;
static WIRED: OnceLock<Option<Arc<rhema_agent_tools::vision::Wiring>>> = OnceLock::new();
/// The daemon's wiring, established at first use and kept for the
/// process's life. `None` only when provisioning failed, cached like
/// every answer this static gives.
pub(crate) fn wired() -> Option<&'static Arc<rhema_agent_tools::vision::Wiring>> {
WIRED
.get_or_init(|| {
rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV")).map(Arc::clone)
})
.as_ref()
/// The daemon's wiring, provisioned at first use and kept for the
/// process's life — the toolkit's own process-wide cache holds it, so
/// `None` only when provisioning failed, and a failure does not retry.
pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
}
/// The init file a later provisioner chains through — `None` when the
@@ -36,7 +30,7 @@ pub(crate) fn init_path() -> Option<std::ffi::OsString> {
/// Layers the wiring onto one agent config: the shell env map (the
/// init file, the binary, the staging directory) and the prompt's
/// vision section. A frontend without wiring changes nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) {
pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else {
return;
};
@@ -52,7 +46,12 @@ mod tests {
/// values are constants, so extending twice is the same map.
#[test]
fn apply_twice_is_apply_once() {
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
apply(&mut config);
let once = config.shell_env.clone();
apply(&mut config);
+114
View File
@@ -114,6 +114,13 @@ CREATE TABLE IF NOT EXISTS watch_health (
consecutive_failures INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (scope, forge, subject)
);
CREATE TABLE IF NOT EXISTS watch_cursors (
scope TEXT NOT NULL,
forge TEXT NOT NULL,
subject TEXT NOT NULL,
cursor TEXT NOT NULL,
PRIMARY KEY (scope, forge, subject)
);
";
/// Why a watch-table operation failed.
@@ -315,6 +322,14 @@ impl ClawStore {
"DELETE FROM watches WHERE forge = ?1 AND repo = ?2",
params![forge.trim(), repo.trim()],
)?;
// The cursor goes with the watch: a re-add is a new watch, and it
// starts at *now* like any other rather than resuming where the
// old one stopped (which would replay everything that happened in
// between as fresh news).
conn.execute(
"DELETE FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3",
params![SCOPE_REPO, forge.trim(), repo.trim()],
)?;
Ok(removed == 1)
}
@@ -419,6 +434,51 @@ impl ClawStore {
.map_err(WatchStoreError::from)?;
Ok(rows)
}
/// The cursor one watch polls from: the last position it reported to
/// the dispatcher, in the forge's own spelling. `None` before the
/// watch has ever polled.
pub fn cursor(
&self,
scope: &str,
forge: &str,
subject: &str,
) -> Result<Option<String>, WatchStoreError> {
let conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
let mut statement = conn
.prepare(
"SELECT cursor FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3",
)
.map_err(WatchStoreError::from)?;
let mut rows = statement
.query_map(params![scope, forge, subject], |row| row.get(0))
.map_err(WatchStoreError::from)?;
match rows.next() {
Some(row) => Ok(Some(row.map_err(WatchStoreError::from)?)),
None => Ok(None),
}
}
/// Advances one watch's cursor. Last write wins: the cursor only ever
/// moves forward, and a stale write is one poll's worth of replay that
/// the dispatcher's dedup lane already covers.
pub fn set_cursor(
&self,
scope: &str,
forge: &str,
subject: &str,
cursor: &str,
) -> Result<(), WatchStoreError> {
let conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
conn.execute(
"INSERT INTO watch_cursors (scope, forge, subject, cursor) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(scope, forge, subject) DO UPDATE SET cursor = excluded.cursor",
params![scope, forge, subject, cursor],
)
.map_err(WatchStoreError::from)?;
Ok(())
}
/// Records a successful poll: the streak resets, and the row stops
/// reading as broken.
pub fn record_poll_ok(
@@ -637,6 +697,60 @@ mod tests {
assert_eq!(store.list_health().expect("list reads").len(), 1);
}
/// A watch remembers where it was: the cursor is a row, so a daemon
/// restart resumes instead of replaying the repository's history.
#[test]
fn a_cursor_is_kept_per_watch_and_moves_forward() {
let store = ClawStore::in_memory().expect("store opens");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
None,
"a watch that never polled has no cursor"
);
store
.set_cursor(SCOPE_REPO, "gitea", "acme/barn", "2026-10-08T00:00:00Z")
.expect("cursor lands");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
Some("2026-10-08T00:00:00Z".to_owned())
);
// Another watch of the same forge is another cursor.
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/quarry")
.expect("read"),
None
);
store
.set_cursor(SCOPE_REPO, "gitea", "acme/barn", "2026-10-09T00:00:00Z")
.expect("the cursor advances");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
Some("2026-10-09T00:00:00Z".to_owned())
);
// Removing the watch forgets its place: a re-add starts over from
// now instead of resuming into a backlog.
store
.add("gitea", "acme/barn", Some("https://git.example"), "tok")
.expect("add");
store.remove("gitea", "acme/barn").expect("remove");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
None
);
}
#[test]
fn validation_fails_a_watch_loudly_and_specificly() {
assert_eq!(
+15 -2
View File
@@ -13,10 +13,22 @@ use rhema_claw::{ClawConfig, run_once};
/// carrying watches, and the test speaks to the daemon the way an
/// integration would: through the store the routes share.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
rhema_claw::ClawStore::open(dir.path().join("dispatch.db"))
.expect("the watch table opens")
let store =
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
// An established watch: it already has a cursor, so the pass reads
// the feed from there instead of seeding one at *now* (which a
// never-polled watch does, and which feeds nothing).
store
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.expect("the cursor seeds");
}
use rhema_core::{Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
use rhema_rsd::{KeyState, Outcome, ResourceKey, SqliteStore, Store};
@@ -81,6 +93,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+15 -2
View File
@@ -59,6 +59,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -67,10 +68,22 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
/// carrying watches, and the test speaks to the daemon the way an
/// integration would: through the store the routes share.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
rhema_claw::ClawStore::open(dir.path().join("dispatch.db"))
.expect("the watch table opens")
let store =
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
// An established watch: it already has a cursor, so the pass reads
// the feed from there instead of seeding one at *now* (which a
// never-polled watch does, and which feeds nothing).
store
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.expect("the cursor seeds");
}
#[tokio::test]
+228 -6
View File
@@ -18,7 +18,7 @@ use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, Sto
use rhema_rsd::{ResourceKey, SqliteStore, Store};
use serde_json::{Value, json};
use tokio_stream::StreamExt;
use wiremock::matchers::{method, path};
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
/// The scripted assistant turn: one text reply, nothing else.
@@ -34,6 +34,7 @@ fn reply(text: &str) -> ModelOutput {
fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput {
ModelOutput {
message: Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall {
id: id.to_owned(),
@@ -65,6 +66,7 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
tools_bin: None,
ingest_token: None,
transcript: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -232,9 +234,11 @@ impl rhema_core::ModelProvider for RecordingProvider {
/// One quiet GitHub repo, for the watches test: an issues list with a
/// single closed issue and a quiet comments feed.
async fn mount_github(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([{
// The issues feed filters by `since` server-side, as GitHub does: a
// watch seeded at *now* sees nothing, and one rewound to before the
// row sees it. Without the filter a fresh watch would replay whatever
// the mock always answers.
let row = json!([{
"id": 1007,
"number": 7,
"state": "closed",
@@ -246,7 +250,18 @@ async fn mount_github(server: &MockServer) {
"updated_at": "2026-10-02T10:00:00Z",
"closed_at": "2026-10-02T10:00:00Z",
"html_url": "https://github.com/acme/widgets/issues/7"
}])))
}]);
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.and(query_param("since", "2026-10-01T00:00:00Z"))
.respond_with(ResponseTemplate::new(200).set_body_json(row))
.with_priority(1)
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
.with_priority(2)
.mount(server)
.await;
Mock::given(method("GET"))
@@ -655,6 +670,77 @@ async fn chat_messages_carry_images_into_the_attachment_store() {
);
}
/// A staged chip rides beside its draft and records as spans: the
/// echo on the stream and the stashed session both carry the plain
/// text with the `rhema-code` annotation beside it, and no mark ever
/// crosses the wire.
#[tokio::test]
async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
let provider = Arc::new(MockProvider::new([reply("on it")]));
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(provider),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// The chip rides as a payload beside the plain draft.
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({
"text": "review this:",
"pastes": ["fn main() {}\nfn other() {}"],
}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
// The echo on the stream: the payload in place, the span record
// beside it, no marks in the text.
let events = client
.get(format!("{base}/v1/sessions/interactive:web/events"))
.send()
.await
.expect("the events request goes out");
let mut stream = sse_body(events).await;
let mut seen = String::new();
read_until(&mut stream, &mut seen, r#""type":"turn_done""#).await;
assert!(
seen.contains(r#""type":"user_message","text":"review this:fn main() {}\nfn other() {}""#),
"the echo carries the composed plain form: {seen}"
);
assert!(
seen.contains(r#""pastes":[{"start":12,"end":38,"lines":2}]"#),
"the chip notes itself as the span it stands for: {seen}"
);
assert!(!seen.contains('\u{FFFC}'), "no marks ride the wire: {seen}");
// The stash: the checkpoint's user message carries the payload in
// the text and the annotation that outlives the turn.
let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
let key = ResourceKey::from("interactive:web");
let record = store
.load(&key)
.expect("the record loads")
.expect("the key has a record");
let stashed: Session =
serde_json::from_value(record.session.expect("a session").core.driver_state)
.expect("the stash parses");
let ask = stashed
.history
.iter()
.find(|message| message.role == Role::User)
.expect("the question is stashed");
assert_eq!(rhema_core::paste::spans(ask).len(), 1);
assert_eq!(rhema_core::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_core::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2);
}
/// A turn nobody watched is still replayable: a client arriving after
/// the fact — a reloaded browser, a reopened phone — subscribes cold and
/// gets the finished turns back before the live feed. The same holds
@@ -1109,7 +1195,23 @@ async fn watches_added_over_http_feed_the_next_detect_pass() {
"the token is not serialized: {listed}"
);
// The next pass detects through the new watch — no restart.
// The next pass reads the new watch — no restart. Its first pass only
// seeds a cursor: a watch starts at *now* and reports news, so the
// repository's existing history is not replayed as a burst of
// dispatches (and, from the handler, a burst of comments).
let report = daemon.tick().await.expect("the pass runs");
assert_eq!(report.detected, 0, "a fresh watch seeds its cursor");
// Rewound to before the feed's rows — an established watch — the same
// pass detects the feed's event.
Arc::new(rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("reopens"))
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.expect("the cursor rewinds");
let report = daemon.tick().await.expect("the pass runs");
assert_eq!(report.detected, 1, "the new watch's feed event was fed");
@@ -2209,6 +2311,126 @@ async fn providers_gain_and_lose_backends_over_the_surface() {
assert_eq!(gone.status(), 400);
}
/// The sandbox surface: the default is this host, a remote choice
/// persists across a rebuild, the token is write-only, and a choice
/// without a URL or with an unknown kind is refused.
#[tokio::test]
async fn the_sandbox_choice_is_listed_and_switchable() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let listed: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(listed["kind"], "local");
assert_eq!(listed["token_set"], false);
assert_eq!(listed["remote_workspace"], "/workspace");
assert!(
listed["workspace"]
.as_str()
.is_some_and(|path| !path.is_empty())
);
// A remote choice: the URL and token go in, the token never comes
// back.
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "http",
"url": "https://box.example:7600/",
"token": "s3cret"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "http");
assert_eq!(switched["url"], "https://box.example:7600");
assert_eq!(switched["token_set"], true);
assert_eq!(switched["workspace"], "/workspace");
assert!(
switched.get("token").is_none(),
"the token stays write-only"
);
// A remote choice without a URL is a 400, and an unknown kind too.
let missing = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "http", "url": ""}))
.send()
.await
.expect("the refusal posts");
assert_eq!(missing.status(), 400);
let unknown = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "quantum"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(unknown.status(), 400);
// Back to this host: the remote fields stay staged for the next
// switch, and the workspace path flips with the choice.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["token_set"], true);
// The persisted choice wins after a restart.
drop(base);
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon rebuilds");
let base = serve(&daemon).await;
let reloaded: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(reloaded["kind"], "local");
assert_eq!(reloaded["token_set"], true);
// `clear_token` drops the stored secret without moving the URL.
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local", "clear_token": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["token_set"], false);
assert_eq!(cleared["url"], "https://box.example:7600");
}
/// The agent identity surface: the text fields round-trip with
/// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type,
+221
View File
@@ -0,0 +1,221 @@
//! The mention gate, end to end: a comment that names the daemon runs a
//! turn and posts a reply; a comment that names nobody is drained and
//! ignored — no snapshot, no model call, no comment. Zero network.
use std::sync::Arc;
use rhema_claw::{ClawConfig, run_once};
use rhema_core::{Message, MockProvider, ModelOutput, Role, StopReason, Usage};
use rhema_rsd::Outcome;
use serde_json::{Value, json};
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
/// The one issue the tests watch, updated inside the seeded cursor's
/// window so the pass sees it as news alongside the comment.
fn issue_row() -> Value {
json!({
"id": 1007,
"number": 7,
"state": "open",
"title": "crash on save",
"user": { "login": "alice" },
"labels": [],
"body": "steps to reproduce…",
"created_at": "2026-10-01T09:00:00Z",
"updated_at": "2026-10-02T10:00:00Z",
"closed_at": null,
"html_url": "https://github.com/acme/widgets/issues/7"
})
}
/// A comment on thread 7: the author and the body are the test's subject.
fn comment_row(author: &str, body: &str) -> Value {
json!({
"id": 8001,
"user": { "login": author },
"body": body,
"created_at": "2026-10-03T09:00:00Z",
"updated_at": "2026-10-03T09:00:00Z",
"issue_url": "https://api.github.com/repos/acme/widgets/issues/7",
"html_url": "https://github.com/acme/widgets/issues/7#issuecomment-8001"
})
}
fn reply(text: &str) -> ModelOutput {
ModelOutput {
message: Message::text(Role::Assistant, text),
stop_reason: StopReason::EndTurn,
usage: Usage::default(),
}
}
fn config(dir: &tempfile::TempDir) -> ClawConfig {
ClawConfig {
db: Some(dir.path().join("dispatch.db")),
workspace_root: Some(dir.path().join("workspaces")),
memory_root: None,
bootstrap_root: None,
poll_interval_secs: 60,
max_turn_steps: rhema_claw::config::DEFAULT_MAX_TURN_STEPS,
provider: Some("google".to_owned()),
model: Some("test-model".to_owned()),
listen: None,
token: None,
agent_token: None,
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
/// An established watch: the cursor is what makes the pass read the feed
/// as news rather than seeding a start line at *now*.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
let store =
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
store
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.expect("the cursor seeds");
}
/// The feeds every pass reads, plus the forge's answer to "who am I" —
/// the watch's token is a bare value that names nobody, so the mention
/// gate asks the forge rather than guess.
async fn mount_repo(server: &MockServer, author: &str, comment: &str) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([issue_row()])))
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues/comments"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([comment_row(author, comment)])),
)
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos" })))
.mount(server)
.await;
}
/// The orientation call the turn makes once the gate has opened.
async fn mount_snapshot(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues/7"))
.respond_with(ResponseTemplate::new(200).set_body_json(issue_row()))
.mount(server)
.await;
}
/// The headline case: "hey @kosmos, can you take a look at this?" — one
/// comment addressed by name, one turn, one reply.
#[tokio::test]
async fn a_comment_that_names_the_daemon_runs_a_turn() {
let server = MockServer::start().await;
mount_repo(&server, "dave", "hey @kosmos can you take a look at this?").await;
mount_snapshot(&server).await;
let posted = Mock::given(method("POST"))
.and(path("/repos/acme/widgets/issues/7/comments"))
.and(body_partial_json(json!({ "body": "on it" })))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 })))
.expect(1)
.mount_as_scoped(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(report.outcomes, vec![Outcome::Handled]);
drop(posted);
}
/// The gate's whole point: somebody else's conversation on a watched
/// repository is context, not a request. The news is drained and dropped
/// — and the snapshot is deliberately not mocked, so a dispatch that got
/// past the gate would fail loudly instead of posting quietly.
#[tokio::test]
async fn a_comment_that_names_nobody_runs_nothing() {
let server = MockServer::start().await;
mount_repo(&server, "dave", "any progress on this?").await;
let posted = Mock::given(method("POST"))
.and(path("/repos/acme/widgets/issues/7/comments"))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 })))
.expect(0)
.mount_as_scoped(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(
report.outcomes,
vec![Outcome::Superseded],
"nothing was asked, and nothing ran"
);
drop(posted);
}
/// Our own replies are news too — and they quote the mention they answer.
/// Without the actor check, every answer would open the gate for the next
/// turn: the daemon talking to itself, forever.
#[tokio::test]
async fn the_daemons_own_reply_does_not_reopen_the_gate() {
let server = MockServer::start().await;
// Written by the daemon itself, quoting the mention it answers.
mount_repo(
&server,
"kosmos",
"> hey @kosmos can you take a look?\n\nDone — branch pushed.",
)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(
report.outcomes,
vec![Outcome::Superseded],
"the daemon answered itself"
);
}
/// A registry whose only backend is the scripted mock — the shape every
/// integration test runs on.
fn mock_registry(provider: Arc<dyn rhema_core::ModelProvider>) -> Arc<rhema_claw::BackendRegistry> {
Arc::new(
rhema_claw::BackendRegistry::new(
vec![rhema_claw::Backend::headless("mock", provider)],
None,
)
.expect("a single mock backend always constructs"),
)
}
+2 -43
View File
@@ -10,55 +10,14 @@ WORKDIR /build
# Manifests first: the registry cache this populates survives source edits.
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./
COPY crates/rhema-acp/Cargo.toml crates/rhema-acp/Cargo.toml
COPY crates/rhema-agent-tools/Cargo.toml crates/rhema-agent-tools/Cargo.toml
COPY crates/rhema-autonomous-agent/Cargo.toml crates/rhema-autonomous-agent/Cargo.toml
COPY crates/rhema-claw/Cargo.toml crates/rhema-claw/Cargo.toml
COPY crates/rhema-cloud-agent/Cargo.toml crates/rhema-cloud-agent/Cargo.toml
COPY crates/rhema-cloudflare-code/Cargo.toml crates/rhema-cloudflare-code/Cargo.toml
COPY crates/rhema-code/Cargo.toml crates/rhema-code/Cargo.toml
COPY crates/rhema-coding-agent/Cargo.toml crates/rhema-coding-agent/Cargo.toml
COPY crates/rhema-config/Cargo.toml crates/rhema-config/Cargo.toml
COPY crates/rhema-core/Cargo.toml crates/rhema-core/Cargo.toml
COPY crates/rhema-identity/Cargo.toml crates/rhema-identity/Cargo.toml
COPY crates/rhema-memory/Cargo.toml crates/rhema-memory/Cargo.toml
COPY crates/rhema-mcp/Cargo.toml crates/rhema-mcp/Cargo.toml
COPY crates/rhema-provider/Cargo.toml crates/rhema-provider/Cargo.toml
COPY crates/rhema-provider-anthropic/Cargo.toml crates/rhema-provider-anthropic/Cargo.toml
COPY crates/rhema-provider-chatgpt/Cargo.toml crates/rhema-provider-chatgpt/Cargo.toml
COPY crates/rhema-provider-copilot/Cargo.toml crates/rhema-provider-copilot/Cargo.toml
COPY crates/rhema-provider-google/Cargo.toml crates/rhema-provider-google/Cargo.toml
COPY crates/rhema-provider-llama-cpp/Cargo.toml crates/rhema-provider-llama-cpp/Cargo.toml
COPY crates/rhema-provider-openai-compatible/Cargo.toml crates/rhema-provider-openai-compatible/Cargo.toml
COPY crates/rhema-provider-opencode/Cargo.toml crates/rhema-provider-opencode/Cargo.toml
COPY crates/rhema-provider-openrouter/Cargo.toml crates/rhema-provider-openrouter/Cargo.toml
COPY crates/rhema-provider-registry/Cargo.toml crates/rhema-provider-registry/Cargo.toml
COPY crates/rhema-rsd/Cargo.toml crates/rhema-rsd/Cargo.toml
COPY crates/rhema-sandbox/Cargo.toml crates/rhema-sandbox/Cargo.toml
COPY crates/rhema-sandbox-docker/Cargo.toml crates/rhema-sandbox-docker/Cargo.toml
COPY crates/rhema-sandbox-ecrou/Cargo.toml crates/rhema-sandbox-ecrou/Cargo.toml
COPY crates/rhema-sandbox-http/Cargo.toml crates/rhema-sandbox-http/Cargo.toml
COPY crates/rhema-sandbox-local/Cargo.toml crates/rhema-sandbox-local/Cargo.toml
COPY crates/rhema-sandbox-lxd/Cargo.toml crates/rhema-sandbox-lxd/Cargo.toml
COPY crates/rhema-sandbox-server/Cargo.toml crates/rhema-sandbox-server/Cargo.toml
COPY crates/rhema-sandbox-ssh/Cargo.toml crates/rhema-sandbox-ssh/Cargo.toml
COPY crates/rhema-subagents/Cargo.toml crates/rhema-subagents/Cargo.toml
COPY crates/rhema-transcript/Cargo.toml crates/rhema-transcript/Cargo.toml
COPY integrations/rhema-calendar-integration/Cargo.toml integrations/rhema-calendar-integration/Cargo.toml
COPY integrations/rhema-forge-integration/Cargo.toml integrations/rhema-forge-integration/Cargo.toml
# rhema-claw path-depends on the tools contract, which lives in its own
# workspace: the member manifests inherit from that root, so the root
# rides along with them.
COPY integrations/rhema-calendar-integration/Cargo.toml integrations/rhema-calendar-integration/Cargo.toml
COPY tools/Cargo.toml tools/Cargo.toml
COPY tools/contract/Cargo.toml tools/contract/Cargo.toml
COPY tools/common/Cargo.toml tools/common/Cargo.toml
COPY tools/notify/Cargo.toml tools/notify/Cargo.toml
# Resolution reads the vendored crossterm (the root manifest path-patches
# to it) even though the image builds the daemon, which does not link it.
COPY vendor/ vendor/
# Cargo validates explicit target
# paths at manifest-parse time, so the fetch needs stub files at every
# declared target path: src/ for every member, plus examples/tests/benches
@@ -89,7 +48,7 @@ FROM debian:stable-slim
# bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+5 -42
View File
@@ -12,53 +12,16 @@ WORKDIR /build
# Manifests first: the registry cache this populates survives source edits.
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./
COPY crates/rhema-acp/Cargo.toml crates/rhema-acp/Cargo.toml
COPY crates/rhema-agent-tools/Cargo.toml crates/rhema-agent-tools/Cargo.toml
COPY crates/rhema-autonomous-agent/Cargo.toml crates/rhema-autonomous-agent/Cargo.toml
COPY crates/rhema-claw/Cargo.toml crates/rhema-claw/Cargo.toml
COPY crates/rhema-cloud-agent/Cargo.toml crates/rhema-cloud-agent/Cargo.toml
COPY crates/rhema-cloudflare-code/Cargo.toml crates/rhema-cloudflare-code/Cargo.toml
COPY crates/rhema-code/Cargo.toml crates/rhema-code/Cargo.toml
COPY crates/rhema-coding-agent/Cargo.toml crates/rhema-coding-agent/Cargo.toml
COPY crates/rhema-config/Cargo.toml crates/rhema-config/Cargo.toml
COPY crates/rhema-core/Cargo.toml crates/rhema-core/Cargo.toml
COPY crates/rhema-identity/Cargo.toml crates/rhema-identity/Cargo.toml
COPY crates/rhema-memory/Cargo.toml crates/rhema-memory/Cargo.toml
COPY crates/rhema-mcp/Cargo.toml crates/rhema-mcp/Cargo.toml
COPY crates/rhema-provider/Cargo.toml crates/rhema-provider/Cargo.toml
COPY crates/rhema-provider-anthropic/Cargo.toml crates/rhema-provider-anthropic/Cargo.toml
COPY crates/rhema-provider-chatgpt/Cargo.toml crates/rhema-provider-chatgpt/Cargo.toml
COPY crates/rhema-provider-copilot/Cargo.toml crates/rhema-provider-copilot/Cargo.toml
COPY crates/rhema-provider-google/Cargo.toml crates/rhema-provider-google/Cargo.toml
COPY crates/rhema-provider-llama-cpp/Cargo.toml crates/rhema-provider-llama-cpp/Cargo.toml
COPY crates/rhema-provider-openai-compatible/Cargo.toml crates/rhema-provider-openai-compatible/Cargo.toml
COPY crates/rhema-provider-opencode/Cargo.toml crates/rhema-provider-opencode/Cargo.toml
COPY crates/rhema-provider-openrouter/Cargo.toml crates/rhema-provider-openrouter/Cargo.toml
COPY crates/rhema-rsd/Cargo.toml crates/rhema-rsd/Cargo.toml
COPY crates/rhema-sandbox/Cargo.toml crates/rhema-sandbox/Cargo.toml
COPY crates/rhema-sandbox-docker/Cargo.toml crates/rhema-sandbox-docker/Cargo.toml
COPY crates/rhema-sandbox-ecrou/Cargo.toml crates/rhema-sandbox-ecrou/Cargo.toml
COPY crates/rhema-sandbox-http/Cargo.toml crates/rhema-sandbox-http/Cargo.toml
COPY crates/rhema-sandbox-local/Cargo.toml crates/rhema-sandbox-local/Cargo.toml
COPY crates/rhema-sandbox-lxd/Cargo.toml crates/rhema-sandbox-lxd/Cargo.toml
COPY crates/rhema-sandbox-server/Cargo.toml crates/rhema-sandbox-server/Cargo.toml
COPY crates/rhema-sandbox-ssh/Cargo.toml crates/rhema-sandbox-ssh/Cargo.toml
COPY crates/rhema-subagents/Cargo.toml crates/rhema-subagents/Cargo.toml
COPY crates/rhema-transcript/Cargo.toml crates/rhema-transcript/Cargo.toml
COPY integrations/rhema-calendar-integration/Cargo.toml integrations/rhema-calendar-integration/Cargo.toml
COPY integrations/rhema-forge-integration/Cargo.toml integrations/rhema-forge-integration/Cargo.toml
# rhema-claw path-depends on the tools contract, which lives in its own
# workspace: the member manifests inherit from that root, so the root
# rides along with them.
COPY integrations/rhema-calendar-integration/Cargo.toml integrations/rhema-calendar-integration/Cargo.toml
COPY tools/Cargo.toml tools/Cargo.toml
COPY tools/contract/Cargo.toml tools/contract/Cargo.toml
COPY tools/common/Cargo.toml tools/common/Cargo.toml
COPY tools/notify/Cargo.toml tools/notify/Cargo.toml
# Resolution reads the vendored crossterm (the root manifest path-patches
# to it) even though the image builds the daemon, which does not link it.
COPY vendor/ vendor/
# rhema-claw path-depends on the tools contract, which lives in its own
# workspace: the member manifests inherit from that root, so the root
# rides along with them.
# Cargo validates explicit target
# paths at manifest-parse time, so the fetch needs stub files at every
@@ -104,7 +67,7 @@ FROM debian:stable-slim
# load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
# neither).
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+2 -2
View File
@@ -3,5 +3,5 @@ name: rhema-claw
description: "The resident forge-watching agent daemon: forge watches and a
chat HTTP surface over one SQLite store."
type: application
version: 0.1.0
appVersion: "0.1.0"
version: 0.4.0
appVersion: "0.4.0"
@@ -15,10 +15,10 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's
rhema-autonomous-agent = { path = "../../crates/rhema-autonomous-agent", version = "0.2.3" }
rhema-autonomous-agent = "0.4.0"
# The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's
rhema-rsd = { path = "../../crates/rhema-rsd", version = "0.2.3" }
rhema-rsd = "0.4.0"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -13,7 +13,7 @@ publish = false
[dependencies]
# The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = { path = "../../crates/rhema-rsd", version = "0.2.3" }
rhema-rsd = "0.4.0"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -380,6 +380,46 @@ impl Timestamp {
pub fn epoch_secs(&self) -> i64 {
self.secs
}
/// The instant `millis` milliseconds past the Unix epoch, in the
/// canonical `YYYY-MM-DDThh:mm:ss[.mmm]Z` spelling.
///
/// This is how a cursor is born without a forge: a subsystem that
/// starts watching *now* (rather than replaying a feed's history)
/// needs a `since` spelled the way the forges spell theirs, and this
/// is the one place that conversion lives.
pub fn from_epoch_millis(millis: i64) -> Option<Self> {
let secs = millis.div_euclid(1000);
let sub_millis = millis.rem_euclid(1000);
let (days, of_day) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
let (year, month, day) = civil_from_days(days);
let (hour, minute, second) = (of_day / 3_600, (of_day / 60) % 60, of_day % 60);
let raw = if sub_millis == 0 {
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
} else {
format!(
"{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{sub_millis:03}Z"
)
};
Self::parse(&raw)
}
}
/// The civil date `days` days past 1970-01-01, as `(year, month, day)` —
/// the inverse of [`days_from_civil`] (Howard Hinnant's algorithm).
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let day_of_era = z - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year = year_of_era + era * 400;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let mp = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if month <= 2 { year + 1 } else { year };
(year, month as u32, day as u32)
}
/// A run of ASCII digits at `range`, as its number.
@@ -524,4 +564,32 @@ mod tests {
.expect("deserializes");
assert_eq!(round, event);
}
#[test]
fn a_timestamp_is_born_from_epoch_millis() {
// The whole-second spelling the forges send, and the fractional
// one GitLab sends: both round-trip back to the same instant.
let whole =
Timestamp::from_epoch_millis(1_791_417_600_000).expect("a millis instant parses");
assert_eq!(whole.raw(), "2026-10-08T00:00:00Z");
assert_eq!(whole.epoch_secs(), 1_791_417_600);
let fractional =
Timestamp::from_epoch_millis(1_791_417_600_081).expect("a millis instant parses");
assert_eq!(fractional.raw(), "2026-10-08T00:00:00.081Z");
assert_eq!(fractional.epoch_secs(), whole.epoch_secs());
// The epoch itself, and a leap day, so the civil-date inverse is
// exercised somewhere other than "today".
assert_eq!(
Timestamp::from_epoch_millis(0).expect("parses").raw(),
"1970-01-01T00:00:00Z"
);
assert_eq!(
Timestamp::from_epoch_millis(1_709_164_800_000)
.expect("parses")
.raw(),
"2024-02-29T00:00:00Z"
);
}
}
@@ -99,6 +99,19 @@ pub trait Forge: Send + Sync {
&self,
since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>;
/// The login this client authenticates as — the backend's own answer
/// to "who am I".
///
/// A consumer that must recognize its own handle (to see an @-mention
/// in a body, and to ignore its own replies) cannot always read it off
/// its credential: a token pasted into a watch row, or an environment
/// variable, names nobody. `None` is the honest default — a backend
/// with no such route simply cannot say who it is — and a backend that
/// can say answers with its `/user` row.
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
Ok(None)
}
}
#[cfg(test)]
@@ -477,20 +477,17 @@ fn review_event(
/// The comment event a repo-wide comments row carries.
fn comment_event(row: &WireComment, repo: &RepoRef) -> Result<Option<ForgeEvent>, ForgeError> {
let id = required(row.id, "comment id")?;
let issue_url = required(row.issue_url.clone(), "comment issue_url")?;
let number = parent_number(&issue_url).ok_or_else(|| {
let number = comment_parent(row).ok_or_else(|| {
ForgeError::Parse(format!(
"comment issue_url without a thread number: {issue_url}"
"comment {id} names no thread: issue_url {:?}, pull_request_url {:?}, html_url {:?}",
row.issue_url, row.pull_request_url, row.html_url
))
})?;
let timestamp = required(
row.updated_at.clone().or_else(|| row.created_at.clone()),
"comment timestamp",
)?;
let is_pr = row
.pull_request_url
.as_deref()
.is_some_and(|url| !url.is_empty());
let is_pr = comment_is_pr(row);
Ok(Some(ForgeEvent {
id: format!("gitea:comment:{id}"),
kind: EventKind::Comment,
@@ -505,9 +502,48 @@ fn comment_event(row: &WireComment, repo: &RepoRef) -> Result<Option<ForgeEvent>
}))
}
/// The parent thread number: a forge thread URL's trailing segment.
/// Every URL a comment row carries, most specific first.
fn comment_urls(row: &WireComment) -> [Option<&str>; 3] {
[
row.issue_url.as_deref(),
row.pull_request_url.as_deref(),
row.html_url.as_deref(),
]
}
/// The thread number a comment row names.
///
/// `issue_url` is the field the API documents for it, but it is not
/// reliable: the instance behind `git.vhaudiquet.fr` (28.3.0) sends it
/// as an empty string on every row of the repo-wide `/issues/comments`
/// feed, while `pull_request_url` and `html_url` stay populated. The
/// number is therefore read from the first URL that carries one, in
/// order of directness.
fn comment_parent(row: &WireComment) -> Option<u64> {
comment_urls(row)
.into_iter()
.flatten()
.find_map(parent_number)
}
/// [`comment_parent`]'s "is it a pull request" half: `pull_request_url`
/// is set exactly on PR conversation comments, and stays set on the
/// instances whose `issue_url` is blank — but a row that lost both still
/// says so in its `html_url` path.
fn comment_is_pr(row: &WireComment) -> bool {
comment_urls(row)
.into_iter()
.flatten()
.any(|url| url.contains("/pulls/") || url.contains("/pull/"))
}
/// The parent thread number: a forge thread URL's trailing segment,
/// with any fragment dropped first — a comment's `html_url` points at
/// the comment (`…/pulls/1#issuecomment-164`), and its fragment is not
/// a number at all.
fn parent_number(url: &str) -> Option<u64> {
url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
let path = url.split('#').next()?;
path.trim_end_matches('/').rsplit('/').next()?.parse().ok()
}
/// The fixed [`NotificationReason::Other`] spelling every reason-less
@@ -690,6 +726,11 @@ impl Forge for GiteaForge {
Ok(())
}
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
let user: WireUser = decode(self.send(self.get("/user")).await?).await?;
Ok(user.login.filter(|login| !login.trim().is_empty()))
}
async fn snapshot(
&self,
repo: &RepoRef,
@@ -895,4 +936,57 @@ mod tests {
.expect("comment carries an event");
assert!(!event.is_pr);
}
#[test]
fn a_comment_with_a_blank_issue_url_still_names_its_thread() {
// git.vhaudiquet.fr (28.3.0) sends `issue_url: ""` on every row
// of the repo-wide comments feed. The poll used to fail on the
// first such row, which is why that watch never reported a single
// event: a PR comment must still resolve to its pull request.
let comment: WireComment = serde_json::from_str(
r#"{"id": 164, "user": {"login": "alice"}, "body": "thanks",
"created_at": "2026-10-19T08:14:39Z",
"updated_at": "2026-10-19T08:14:39Z",
"issue_url": "",
"pull_request_url": "https://forge.example/acme/widgets/pulls/3",
"html_url": "https://forge.example/acme/widgets/pulls/3#issuecomment-164"}"#,
)
.expect("comment fixture parses");
let event = comment_event(&comment, &repo())
.expect("a blank issue_url is not a parse failure")
.expect("comment carries an event");
assert_eq!(event.number, 3);
assert!(event.is_pr);
}
#[test]
fn a_comment_with_only_an_html_url_reads_the_thread_off_its_path() {
// The last resort: no issue_url and no pull_request_url. The
// html_url points at the comment, so the fragment has to go
// before the trailing segment means anything.
let comment: WireComment = serde_json::from_str(
r#"{"id": 165, "created_at": "2026-10-19T09:00:00Z",
"updated_at": "2026-10-19T09:00:00Z",
"html_url": "https://forge.example/acme/widgets/issues/7#issuecomment-165"}"#,
)
.expect("comment fixture parses");
let event = comment_event(&comment, &repo())
.expect("maps")
.expect("comment carries an event");
assert_eq!(event.number, 7);
assert!(!event.is_pr);
}
#[test]
fn a_comment_whose_urls_name_no_thread_is_still_loud() {
// The fallbacks must not degrade into a silent skip: a row with
// no number anywhere is a vocabulary gap, and the poll says so.
let comment: WireComment = serde_json::from_str(
r#"{"id": 166, "created_at": "2026-10-19T09:00:00Z",
"issue_url": "", "html_url": "https://forge.example/acme/widgets/issues/"}"#,
)
.expect("comment fixture parses");
let err = comment_event(&comment, &repo()).expect_err("no thread number names a thread");
assert!(matches!(err, ForgeError::Parse(_)), "got {err:?}");
}
}
@@ -287,7 +287,9 @@ struct WireComment {
/// One row of the account notifications feed.
#[derive(Debug, Clone, Deserialize)]
struct WireNotification {
#[serde(default)]
/// GitHub sends this one as a JSON string, unlike every other id in
/// this adapter; see [`lenient_id`].
#[serde(default, deserialize_with = "lenient_id")]
id: Option<i64>,
#[serde(default)]
reason: Option<String>,
@@ -452,6 +454,32 @@ fn parent_number(url: &str) -> Option<u64> {
url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
}
/// An id that arrives as either a JSON number or a JSON string.
///
/// GitHub's notifications feed is the odd one out: `id` there is a
/// string (`"27210544329"`), while issues, comments and reviews send
/// numbers. One row that refuses to decode fails the whole page, so the
/// notification id is read leniently.
fn lenient_id<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum IdWire {
Number(i64),
Text(String),
}
match Option::<IdWire>::deserialize(deserializer)? {
None => Ok(None),
Some(IdWire::Number(n)) => Ok(Some(n)),
Some(IdWire::Text(text)) => text.trim().parse().map(Some).map_err(|_| {
serde::de::Error::custom(format!("notification id is not a number: {text}"))
}),
}
}
/// The notification a notifications row carries. GitHub's `reason` field
/// is the row's whole why; the subject's API URL yields the thread.
fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> {
@@ -646,6 +674,16 @@ impl Forge for GitHubForge {
Ok(())
}
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
let response = self
.get("/user")
.send()
.await
.map_err(ForgeError::network)?;
let user: WireUser = decode(response).await?;
Ok(user.login.filter(|login| !login.trim().is_empty()))
}
async fn snapshot(
&self,
repo: &RepoRef,
@@ -860,4 +898,61 @@ mod tests {
assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3");
assert!(event.raw.get("title").is_none());
}
fn notification(json: &str) -> WireNotification {
serde_json::from_str(json).expect("notification fixture parses")
}
// Captured from the live feed on 2026-11-21: `id` there is a string,
// and one such row used to fail the whole page's decode.
#[test]
fn a_notification_id_sent_as_a_string_decodes() {
let row = notification(
r#"{"id": "27210544329", "unread": true, "reason": "mention",
"updated_at": "2026-11-21T22:33:00Z", "last_read_at": null,
"subject": {"title": "Snap build failed for v2.5.1",
"url": "https://api.github.com/repos/acme/widgets/issues/10",
"latest_comment_url": "https://api.github.com/repos/acme/widgets/issues/comments/7070",
"type": "Issue"},
"repository": {"id": 1239653662, "full_name": "acme/widgets"},
"url": "https://api.github.com/notifications/threads/27210544329"}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 10);
assert_eq!(notification.repo, RepoRef::new("acme", "widgets"));
assert_eq!(notification.reason, NotificationReason::Mention);
assert!(!notification.is_pr);
assert_eq!(
notification.id,
"github:notification:27210544329@2026-11-21T22:33:00Z"
);
}
#[test]
fn a_notification_id_sent_as_a_number_still_decodes() {
let row = notification(
r#"{"id": 42188, "reason": "review_requested",
"updated_at": "2026-10-08T12:00:00Z",
"subject": {"title": "tidy the parser", "type": "PullRequest",
"url": "https://api.github.com/repos/acme/widgets/pulls/8"},
"repository": {"full_name": "acme/widgets"}}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 8);
assert!(notification.is_pr);
assert_eq!(
notification.id,
"github:notification:42188@2026-10-08T12:00:00Z"
);
}
#[test]
fn a_notification_id_that_is_not_a_number_is_a_parse_error() {
let err = serde_json::from_str::<WireNotification>(r#"{"id": "not-a-number"}"#)
.expect_err("a junk id is loud, not silently dropped");
assert!(err.to_string().contains("not-a-number"), "got: {err}");
}
}
@@ -523,6 +523,18 @@ impl Forge for GitLabForge {
Ok(())
}
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
// GitLab spells the login `username`, like every author object it
// sends.
let response = self
.get("/user")
.send()
.await
.map_err(ForgeError::network)?;
let user: WireAuthor = decode(response).await?;
Ok(user.username.filter(|login| !login.trim().is_empty()))
}
async fn snapshot(
&self,
repo: &RepoRef,
@@ -177,12 +177,24 @@ impl Watcher {
.cloned()
}
/// One poll of `repo`: the page's events are ingested in feed order
/// and the cursor advances to the page's. Returns how many events were
/// fed to the dispatcher — replayed ids included, they dedup there.
/// One poll of `repo` from the watcher's own cursor.
pub async fn poll(&self, forge: &dyn Forge, repo: &RepoRef) -> Result<usize, WatchError> {
let since = self.cursor(repo);
let page = forge.poll(repo, since.as_ref()).await?;
self.poll_since(forge, repo, since.as_ref()).await
}
/// One poll of `repo` from an explicit `since`, for the embedder that
/// keeps the cursor somewhere durable: the page's events are ingested
/// in feed order and the watcher's cursor advances to the page's.
/// Returns how many events were fed to the dispatcher — replayed ids
/// included, they dedup there while they sit in an inbox.
pub async fn poll_since(
&self,
forge: &dyn Forge,
repo: &RepoRef,
since: Option<&Timestamp>,
) -> Result<usize, WatchError> {
let page = forge.poll(repo, since).await?;
let now = SystemClock.now_millis();
let mut fed = 0;
for event in &page.events {
@@ -557,3 +557,74 @@ async fn notifications_poll_maps_the_subject_feed() {
assert_eq!(note.repo, RepoRef::new("acme", "widgets"));
assert_eq!(note.title.as_deref(), Some("Fix the gate"));
}
/// The instance behind `git.vhaudiquet.fr` sends `issue_url: ""` on every
/// row of the repo-wide comments feed. A poll with one such row used to
/// fail outright, so the watch it fed never reported anything at all.
#[tokio::test]
async fn poll_survives_a_comments_feed_with_blank_issue_urls() {
let server = MockServer::start().await;
for (endpoint, body) in [
("/api/v1/repos/acme/widgets/issues", json!([])),
("/api/v1/repos/acme/widgets/pulls", json!([])),
] {
Mock::given(method("GET"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(body))
.mount(&server)
.await;
}
Mock::given(method("GET"))
.and(path("/api/v1/repos/acme/widgets/issues/comments"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([
{ "id": 164, "user": { "login": "alice" }, "body": "thanks",
"created_at": "2026-10-19T08:14:39Z",
"updated_at": "2026-10-19T08:14:39Z",
"issue_url": "",
"pull_request_url": "https://forge.example/acme/widgets/pulls/1",
"html_url": "https://forge.example/acme/widgets/pulls/1#issuecomment-164" },
{ "id": 165, "user": { "login": "bob" }, "body": "still broken",
"created_at": "2026-10-19T09:00:00Z",
"updated_at": "2026-10-19T09:00:00Z",
"issue_url": "",
"pull_request_url": Value::Null,
"html_url": "https://forge.example/acme/widgets/issues/2#issuecomment-165" }
])))
.mount(&server)
.await;
let since = Timestamp::parse(SINCE).expect("cursor parses");
let page = forge(&server)
.poll(&RepoRef::new("acme", "widgets"), Some(&since))
.await
.expect("a blank issue_url is not a poll failure");
let summary: Vec<(EventKind, u64, bool)> = page
.events
.iter()
.map(|event| (event.kind, event.number, event.is_pr))
.collect();
assert_eq!(
summary,
vec![
(EventKind::Comment, 1, true),
(EventKind::Comment, 2, false)
]
);
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos".to_owned())
);
}
@@ -532,3 +532,19 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses"))
);
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos-ai-bot" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos-ai-bot".to_owned())
);
}
@@ -572,3 +572,20 @@ async fn todos_poll_maps_actions_targets_and_projects() {
Some("https://gitlab.com/acme/widgets/-/merge_requests/12")
);
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody. GitLab spells the login
/// `username`.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v4/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "username": "kosmos" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos".to_owned())
);
}
Executable
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
# Run the claw and the web UI together against scratch state — the quick
# debug loop. Nothing here touches your real rhema config or sessions:
# the daemon gets a throwaway config under $RHEMA_DEV_DIR (default
# /tmp/rhema-dev), persisted across runs so sessions survive a restart
# of the script; wipe the directory for a clean slate.
#
# Usage:
# scripts/dev.sh # real provider (CLAW_DEV_PROVIDER, key from
# # the provider's env var; default google)
# scripts/dev.sh --mock # zero credentials: canned streamed replies
#
# The UI proxies /v1 to the claw, so one URL matters:
# http://localhost:3000
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SCRATCH="${RHEMA_DEV_DIR:-/tmp/rhema-dev}"
PROVIDER="${CLAW_DEV_PROVIDER:-google}"
MOCK=0
for arg in "$@"; do
case "$arg" in
--mock) MOCK=1 ;;
*) echo "unknown argument: $arg (supported: --mock)" >&2; exit 2 ;;
esac
done
mkdir -p "$SCRATCH/workspaces"
CONFIG="$SCRATCH/claw.yaml"
if [ "$MOCK" = 1 ]; then
cat > "$CONFIG" <<EOF
# Scratch debug config (scripts/dev.sh --mock): no model is called.
db: $SCRATCH/claw.db
workspace_root: $SCRATCH/workspaces
memory_root: $SCRATCH/memory
bootstrap_root: $SCRATCH/bootstrap
listen: 127.0.0.1:7799
poll_interval_secs: 60
EOF
FEATURES=(--features mock)
RUN_FLAGS=(--mock)
else
case "$PROVIDER" in
google) KEY_VAR=GOOGLE_API_KEY ;;
anthropic) KEY_VAR=ANTHROPIC_API_KEY ;;
openai) KEY_VAR=OPENAI_API_KEY ;;
openrouter) KEY_VAR=OPENROUTER_API_KEY ;;
llama-cpp) KEY_VAR="" ;;
*) echo "CLAW_DEV_PROVIDER must be google, anthropic, openai, openrouter, or llama-cpp" >&2; exit 2 ;;
esac
if [ -n "$KEY_VAR" ] && [ -z "${!KEY_VAR:-}" ]; then
echo "set $KEY_VAR first (or run scripts/dev.sh --mock for zero credentials)" >&2
exit 1
fi
cat > "$CONFIG" <<EOF
# Scratch debug config (scripts/dev.sh): throwaway db and workspaces.
provider: $PROVIDER
db: $SCRATCH/claw.db
workspace_root: $SCRATCH/workspaces
memory_root: $SCRATCH/memory
bootstrap_root: $SCRATCH/bootstrap
listen: 127.0.0.1:7799
poll_interval_secs: 60
EOF
FEATURES=()
RUN_FLAGS=()
fi
echo "[dev] claw config: $CONFIG"
cargo build -p rhema-claw "${FEATURES[@]}"
if [ ! -d "$ROOT/web/claw/node_modules" ]; then
echo "[dev] installing web/claw dependencies"
(cd "$ROOT/web/claw" && npm install)
fi
# exec so the trap's kill reaches the servers, not a wrapper.
"$ROOT/target/debug/rhema-claw" --config "$CONFIG" "${RUN_FLAGS[@]}" &
CLAW_PID=$!
(cd "$ROOT/web/claw" && exec ./node_modules/.bin/nuxt dev) &
UI_PID=$!
cleanup() {
kill "$CLAW_PID" "$UI_PID" 2>/dev/null || true
}
trap cleanup EXIT
echo "[dev] claw: http://127.0.0.1:7799 (config: $CONFIG)"
echo "[dev] ui: http://localhost:3000 (ctrl-c stops both)"
wait "$CLAW_PID"
+397
View File
@@ -0,0 +1,397 @@
# rhema-tools — the claw's model-facing tools as bash skills + thin clients
*One project, independent of the claw: the resident's data tools become small
executables and the markdown that teaches them, speaking the daemon's existing
HTTP surface through a scoped agent credential.*
## 0. Scope
This spec moves the claw's model-facing data tools out of the daemon binary and
its system prompt. After it, the model's view of tasks, watches, identity,
notifications, and the phone is: `bash`, a handful of short-named executables
on `PATH`, and one markdown skill per domain. The daemon keeps the state, the
schedulers, and the sources; the tools project owns everything the model
touches.
Two consumers change:
- the model, which stops seeing sixteen tool schemas on every step of every
session and starts composing tool calls in the shell;
- the claw, which stops being the only place a tool can live;
- tool authors — users or the agent itself — who can add a capability without
touching rhema at all (§8).
Non-goals v1: extracting the server side (stores, schedulers, sources) out of
the claw; extracting memory, attachments, or the bootstrap prompt; any
transport other than the daemon's existing HTTP surface; a daemon-side timer
service (tier-1 tools use system schedulers; §8).
## 1. Problem statement
The claw's tools are native: one `TOOL.yaml` manifest and one Rust builtin per
tool, resolved through the `ClawExtension` chain, rendered as a JSON-schema
bullet into every `SYSTEM.md` render. Sixteen of them today, and the list
grows with every feature.
Four costs, all structural:
1. **Context.** Every session pays the schema of every tool on every step, the
resident's whole life long, whether or not the turn touches them.
2. **Round trips.** "Unwatch every archived repo" is one native call per repo —
one model step each. The model cannot loop, filter, or pipeline across tool
results; only the harness can.
3. **Coupling.** A new tool is a manifest, a builtin, an extension-struct line,
and a registry test — all inside `rhema-claw`. Nothing tool-shaped can be
written, versioned, or shipped without the daemon crate.
4. **Reuse.** A second agent (a forge worker, a phone-side helper) cannot share
the tools without depending on the daemon's binary.
That is the signal that the tool surface is a missing boundary, not a missing
feature list. The boundary is a wire contract.
## 2. Design goals
- The model-facing surface is code: `bash` + executables + skills. Skills are
read when a domain is relevant; `--help` is always current.
- The tools project compiles with zero `rhema-claw` dependencies. Independence
is a dependency arrow, not a directory layout, and CI enforces the arrow.
- The daemon's state stays in the daemon. Clients hold no stores, no
schedulers, no caches; they are request printers.
- One trust boundary, made explicit and enforced: a scoped agent credential
that cannot answer consents, forge chats, or ingest events.
- Incremental: each domain migrates alone, and its native tool stays until its
client ships.
## 3. The shape
Three pieces:
1. **Skills.** One markdown file per domain, shipped next to its binary and
installed into the global skills directory that
`rhema_agent_tools::skills::discover` already reads. The skill carries the
examples; the binary carries the behavior; they never drift apart because
they are versioned and installed together.
2. **Thin clients.** One short-named executable per domain: `notify`, `tasks`,
`watches`, `identity`, `phone`. Parse arguments, make one or a few HTTP
calls, print JSON, exit.
3. **The contract.** The daemon's `/v1` HTTP surface — the same routes the web
UI and the phone client already speak. The contract is the tools project's
entire knowledge of the claw.
One call, end to end — `schedule_task` becoming `tasks add`:
1. The user: "check CI hourly for me."
2. The model runs `bash`: `tasks add --every 3600 "check CI" --json`.
3. The `bash` tool spawns `tasks` inside the sandbox.
4. `tasks` reads `RHEMA_URL` and `RHEMA_TOKEN` from its environment and does
`POST /v1/tasks` with the JSON body.
5. The daemon's route writes the same `TaskStore` row the native builtin used
to write. The scheduler picks it up exactly as before — it never notices
the row arrived over HTTP.
6. `tasks` prints `{"id":"t-7"}` and exits 0. The model reads stdout and
replies.
```
model turn
| bash: tasks add --every 3600 "check CI"
v
+----------------+ POST /v1/tasks +----------------------+
| tools project | Authorization: agent | claw daemon |
| tasks, notify, | --------------------> | route -> TaskStore |
| watches, ... | <-------------------- | (state lives HERE) |
| (stateless) | {"id":"t-7"} | scheduler fires |
+----------------+ +----------------------+
```
"HTTP client" is the role, not a framework: the client is to the daemon what
`gh` is to GitHub. The state cannot live in the client — it is a different,
short-lived process, possibly inside a sandbox container — so it forwards, and
the independence is precisely that forwarding: no `rhema-claw` import exists
anywhere in the tools project.
## 4. The wire contract
Transport: the daemon's existing axum router (`crates/rhema-claw/src/http.rs`)
— loopback plus bearer today, an env-provisioned base URL when a deployment
puts the sandbox on another host.
Routes that already serve clients as-is: `GET/POST /v1/watches`,
`DELETE /v1/watches/{forge}/{repo}`, `GET/POST/DELETE /v1/calendars`
(removal takes `/v1/calendars/{name}`; the reminders source reads the
calendar table fresh every pass, so a route write is live without a
restart), `GET/POST /v1/accounts`, `DELETE /v1/accounts/{id}`,
`GET /v1/notifications`, `POST /v1/notifications/{id}/ack`,
`GET /v1/phones`.
Watches and calendars are the pattern for every data domain the
daemon reconfigures at runtime: the domain lives in a SQLite table —
not in `claw.yaml` — the routes are the one write door, validation
runs at the door (an invalid watch or calendar is refused loudly
wherever it enters), and the config file carries only what boot
needs. A config still carrying the retired `watches:` or
`calendars:` keys is refused at parse time, not silently ignored.
Routes the extraction adds, because the operation exists today only as an
in-process tool: `POST /v1/notifications` (the push), `GET/POST /v1/tasks`,
`DELETE /v1/tasks/{id}`, `POST /v1/phones/{device}/commands`. Promoting a tool
to a route is not new work twice — the web UI and phone gain the same
operations the model does.
Conventions, fixed once:
- Every client prints JSON: one object per call, one object per line for
lists. `--json` exists as a no-op flag for readability of examples.
- Exit codes: `0` ok, `1` usage (clap), `2` daemon unreachable, `3` denied.
- On failure the last stdout line is a single JSON object
`{"error": "..."}` — the model parses one shape, always.
- Version: every request carries `X-Rhema-Contract: 1`; a daemon speaking a
different contract answers `409` with that same error shape. A stale
installed binary fails loudly on first use, with no discovery round trip.
## 5. The agent credential
Today one `token: Option<String>` guards all of `/v1`, and the model never
holds it — tools run in-process. Bash-accessible clients change who holds a
credential, and the current token is the wrong one to hold:
`POST /v1/consents/{id}` answers a consent, and an agent that can answer
consents can answer its own `ask_secret`.
Two token classes, checked per route in the router:
- the **human token**, unchanged, for the web UI, the phone, and the scripts a
user runs themselves;
- the **agent token** (`agent_token` in the claw config), provisioned into the
agent environment as `RHEMA_URL` + `RHEMA_TOKEN`, allowed on exactly the
data routes the clients speak (§4), denied on consent resolve/deny, session
and message creation, `phones_forget`, and `/v1/ingest`.
Boot refuses to start extracted-tool mode without `agent_token` configured —
the failure belongs at boot, where the operator is looking, not mid-turn,
where the model is. This is the step that turns the README's "the
bearer-gated surface plus the watch list are the trust boundary" from a
sentence into enforced code.
## 6. What stays native
- `bash` — the substrate the whole design stands on.
- `ask_secret` — the consent round-trip waits inside the tool call, woken by
the hub, its answer arriving through routes the agent credential must never
reach (§5). Making it a client would hand the model its own approval path.
- `coding_agent` — spawns a whole coding session, inherits the parent turn's
approval hook, answers with a job id. Orchestration, not data access.
- `zoom` — reads the in-process transcript mirror; no daemon state behind it.
- memory and `attach_file` — native in v1. Memory is the first later-extraction
candidate: its store is already behind a `MemoryStore` contract, so a
`/v1/memory` route family plus a client is a shape, not a research project.
## 7. What moves
| current tool | client | route | wave |
|---|---|---|---|
| `list_watches` / `watch_repo` / `unwatch_repo` | `watches ls/add/rm` | `/v1/watches` (exists) | 1 |
| `notify` | `notify push` | `POST /v1/notifications` (new) | 1 |
| `schedule_task` / `cancel_task` / `list_tasks` | `tasks add/rm/ls` | `/v1/tasks` (new) | 2 |
| `identity_save` / `identity_set` / `identity_list` / `identity_forget` | `identity save/set/ls/forget` | `/v1/accounts` (exists) | 3 |
| `phone` | `phone run` | `POST /v1/phones/{device}/commands` (new) | 3 |
| `bootstrap_save` | — | `PUT /v1/agent` (exists) | later candidate |
Wave 1 is watches plus notify: watches has complete routes, notify has the
smallest state, and between them they exercise the whole path — scoped
credential, `PATH` provisioning, skill discovery, contract versioning —
before anything harder follows it.
## 8. Self-contained tools
The client extraction frees the tools from the daemon's binary. A second
question follows: can a tool exist that was never part of rhema at all —
written by a user, or by the agent itself mid-session, without a fork or a
patch? Yes — and it needs no new API, because the generic API is the surface
this spec already builds on. Three primitives, all HTTP, all daemon-side:
- **`POST /v1/ingest`** — wake the agent with an event. The route takes
`{source, key, payload}`, registers unknown source names lazily on the RSD
dispatcher, and rejects the daemon's reserved source names. A third-party
tool's events therefore get the same guarantees the built-in integrations
get: at most one live handler per resource key, races queued into the live
inbox, crash recovery by lease.
- **`POST /v1/notifications`** (§4) — reach the user's devices.
- **`GET /v1/sessions/{key}/events`** — read back what the agent said.
Plus two non-daemon primitives: **files** (the tool keeps its own state in its
own directory) and **system schedulers** (cron, launchd, schtasks — the tool
installs its own trigger).
### Anatomy
A self-contained tool is four files and no rhema code:
- an executable, dropped in a bin directory the daemon puts on the agent's
`PATH`;
- a skill markdown next to it, installed into the global skills directory;
- its own state directory under the state root (one subdir per tool, owned by
the tool, `0600` for anything credential-shaped);
- optionally one scheduler entry it installed itself.
### The watch table, from outside
Even the case that motivated native integration works through the front door.
A third-party CI watcher: a cron entry runs its poller every five minutes; the
poller calls the forge's API itself, with a token kept in its own state
directory; it triages what is new against its own last-seen file; and for each
new item it does
`POST /v1/ingest {source: "ciwatch", key: "github/acme/widgets#123", payload: {...}}`.
The dispatcher admits the key, the resident gets a turn, and a second event
racing a live handler queues instead of doubling the work. The tool is a
script; nothing in rhema changed.
### The two tiers
- **Tier 1 — self-contained.** Executable + skill + state dir + scheduler.
Writable by anyone, including the agent. No daemon custody of anything.
- **Tier 2 — native extension.** The `ClawExtension` seam stays for what
genuinely needs the daemon: secret custody (rhema-identity's use-never-read
contract — a tier-1 tool cannot receive a secret through the consent
round-trip, whose answers land in the identity store, not in the tool),
tick-rate and webhook latency (cron is minute-grained, has no catch-up, and
the task table's re-arm semantics are the reference for what a daemon-side
timer would have to do), and deep hub integration (auto-notify on non-chat
replies, the phone command loop). The forge and calendar integrations live
here and are not demoted — they are just no longer the only way.
### What this forbids
No plugin SDK, no tool manifest registry, no new IPC protocol. The platform is
HTTP + files + `PATH` — the same surface the model itself uses. The only
daemon additions this spec asks for are the §4 routes and the directory
conventions. A `toolctl` helper in the tools project (`toolctl new`,
`toolctl schedule` wrapping crontab/launchd/schtasks) is convenience, not
contract.
### The agent as tool author
Tier 1 is writable from inside a session: the model writes a script into the
bin dir, a skill into the skills dir, a crontab line — and the resident has
grown itself a capability. That is the codemode endgame, and it costs only the
conventions. One honest line comes with it: such a tool runs with the agent's
privileges and persists past the session through its scheduler entry. The
trust boundary is the shell, exactly as it already is, and `ENVIRONMENT.md`
says what is installed.
## 9. Provisioning and discovery
The daemon installs the clients (a `bin` directory it controls, added to the
agent's `PATH`) and their skills (the global skills directory). Boot-time
`ENVIRONMENT.md` already inventories what is on `PATH`, so a missing binary is
visible before the first model call. A client that cannot reach the daemon
prints which environment variable is missing or wrong — the model reports it
instead of retrying.
## 10. Approvals, replay, crash
A `bash` call that runs three clients is one approval unit and one
commit-before-execute unit — coarser than three native calls, and already true
of any compound shell command. Resident sessions auto-approve the shell
anyway (the daemon says so at startup), so nothing is lost in practice. In
exchange, mutating verbs are upsert-shaped (`add`, `rm`, `save`), so a replay
after a mid-command crash converges instead of duplicating. The manifests'
`replay_safety: safe` moves into the contract: `GET` verbs are safe,
`POST`/`DELETE` are not, and the exit code says which one ran.
## 11. Layout and the dependency arrow
New project — `rhema-tools`:
- `rhema-claw-tools-contract` — route constants, JSON payload types, a mock router,
and the conformance suite. Depends on nothing.
- one crate per domain — the binary and its skills directory.
- one thin shared client crate — base-URL/token env handling, the HTTP calls,
the error printing every binary shares.
Dependency arrows, both enforced in CI: the claw depends on
`rhema-claw-tools-contract` (to run the conformance suite against its real router)
and never on the domain crates; the tools project depends on nothing of
rhema-claw.
`TOOL.yaml` is retired for extracted domains. The manifest existed to make a
Rust builtin model-facing; a clap surface plus a skill markdown is that now.
The old guarantee — every manifest loads against its builtin — becomes two:
every skill's examples parse against the binary (`--help`/dry-run), and every
route the contract names is exercised by the conformance suite.
## 12. Migration
1. The scoped agent credential lands in the claw: token classes, route
middleware, boot check. No model-facing change.
2. The contract crate lands; the claw grows the new routes
(`POST /v1/notifications`, the `/v1/tasks` family) and passes conformance.
3. Wave 1: `watches` and `notify` clients + skills; the agent environment gets
`PATH`, skills, `RHEMA_URL`/`RHEMA_TOKEN`, and the tier-1 state root; the
two domains' manifests and builtins stop rendering and are deleted.
4. Waves 2–3 repeat step 3 per domain: routes if new, client + skill, delete
manifest + builtin + extension line.
5. When the last wave lands, the claw's `SYSTEM.md` tools section lists
`bash`, `zoom`, `ask_secret`, `coding_agent`, memory — plus a two-line
pointer to the installed skills.
## 13. How we know it works
- Conformance: the contract's suite runs against the claw's real router and
against the contract's mock router, with the same results.
- Arrow test: the tools workspace builds with `rhema-claw` absent.
- End to end: a mock-provider turn whose scripted model runs `tasks add`
through `bash`; the daemon's scheduler fires the task; the phone poll sees
the notification; the agent token's `POST /v1/consents/{id}` answers `403`.
- Skill lint: every fenced shell example in every skill parses (usage check /
dry-run), so doc rot fails a test instead of fooling a model.
- Tier-1 end to end: a test drops a two-line shell script and a skill into the
provisioned dirs, runs it, and its `POST /v1/ingest` lands as a turn;
`POST /v1/ingest` under a reserved source name answers `400`.
## 14. Explicitly not decided here
- Binary naming: short domain names (`tasks`) versus a prefix
(`rhema-tasks`). Short names read best in skills; switch if a collision
appears on a real system.
- Whether the project starts as a repo-local directory (the `integrations/`
shape) and extracts to its own repo later, or is born separate.
- Extraction waves for memory, `attach_file`, and `bootstrap_save`.
- Transports beyond bearer-over-HTTP: a unix-socket listener, mTLS for a
remote daemon, a quota on client calls per turn.
- Whether `toolctl` (scaffolder + scheduler wrapper) ships in v1 or stays
documentation.
- A daemon-side timer service (`POST /v1/timers`) for cronless hosts — the
task table's fire-guards are the reference semantics. Not v1.
- Whether tier-1 tools ever get a consent-shaped way to receive secrets. V1
answer: no — users place credentials in the tool's state dir themselves.
## 15. Decisions
- Model-facing data tools become bash skills + thin executables; the schema
list leaves `SYSTEM.md`.
- Wire contract, not crate dependency; the arrows claw → contract ← tools are
enforced.
- The scoped agent credential precedes every client; consents, sessions, and
ingest are unreachable by it.
- Native keeps: `bash`, `ask_secret`, `coding_agent`, `zoom`, memory,
`attach_file` (v1).
- Waves: watches + notify, then tasks, then identity + phone.
- Self-contained tools are files + system schedulers + the three HTTP
primitives; no plugin SDK, no manifest registry, no new IPC.
- Two tiers: tier 1 writable by anyone, including the agent mid-session;
tier 2 (`ClawExtension`) keeps secret custody, tick/webhook latency, and
hub depth.
---
## Status
Wave 1 is built: `tools/contract` (allowlist, header, conformance
suite), `tools/notify` (the first client tool), the claw's contract
enforcement (the scoped agent token, the allowlist middleware, the
push and schedule routes, the JSON error shape everywhere), and the
provisioning seam (`agent_token` + `tools_bin` → the daemon's tool
environment → `ShellTools::with_env` → the coding agent's commands).
The conformance suite runs against the daemon's real router in
`crates/rhema-claw/tests/http.rs`; `tools/notify/tests` drives the
`notify` binary against a mock. Waves 2–4 (skills mounts, packaging,
more tools) are still future work.
+1 -1
View File
@@ -7,7 +7,7 @@ version = "0.1.0"
edition = "2024"
rust-version = "1.85"
license = "MIT"
repository = "https://github.com/vhaudiquet/rhema"
repository = "https://git.vhaudiquet.fr/vhaudiquet/rhema-claw"
authors = ["Valentin Haudiquet"]
[workspace.dependencies]
+19 -9
View File
@@ -90,12 +90,21 @@ Two consequences worth knowing before changing this code:
## What the transcript does with the stream
- **Replies, asks and files only.** The stream carries tool calls and
the model's thinking trace; this surface drops both and renders the
reply. A consent card and an attachment card still appear inline,
because the reader has to answer or open them. The mirror still
folds those other events; only the render ignores them.
- **Long pastes travel as chips.** A paste over three lines (the TUI's
`PASTE_INLINE_LINES`) never lands in the composer; it stages as a
droppable chip (`▣1 42L`) and embeds into the sent text as
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s
`paste::embed` keeps — so the transcript renders each embed back as
a chip in place of the payload. An unpaired mark is literal text.
droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
the plain draft — the claw composes the record (the payload in
place, the span note beside it) — so no mark ever crosses the wire.
The `user_message` echo names each chip as the byte span it stands
for (the session record's own shape, `paste::PasteSpan`), and the
transcript renders from that. Rows recorded before spans rode the
stream carry the legacy mark form in the text instead; the render
still scans for those, and an unpaired mark stays literal.
- **The agent can ask.** A `consent_request` event renders as an
inline card: kind `secret` gets a password input plus submit, kind
`phone` gets Approve/Deny, and both carry a deny link
@@ -175,10 +184,10 @@ app/
raw HTML escaped, styles in main.css .md)
ClawBanner.vue the one error/notice banner surface
ChatPanel.vue transcript: sent lines (paste chips),
streamed turns as bash shell lines and
glyph rows, consent + attachment
cards; the growing composer; agent
replies render through AppMarkdown
streamed turns as reply text plus
consent + attachment cards; the growing
composer; agent replies render through
AppMarkdown
SessionsSidebar.vue conversable dispatch keys (phone status
keys hidden), interactive first; the
+ form creates a session
@@ -193,7 +202,8 @@ app/
composables/
useClaw.ts the typed API client + fetch-based SSE
useTranscript.ts folds TurnEvents into renderable turn
blocks; owns the paste-embed text form
blocks; owns the paste span record (and
the legacy mark form old rows carry)
server/
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
```
+55 -8
View File
@@ -17,9 +17,11 @@ import type {
NewAccount,
ProviderCredentials,
ProvidersState,
SandboxSelection,
SandboxState,
StreamStatus,
} from '~/composables/useClaw'
import { useTranscript } from '~/composables/useTranscript'
import { composeChips, useTranscript } from '~/composables/useTranscript'
import type { StagedImage } from '~/composables/useTranscript'
const TOKEN_STORE_KEY = 'claw.token'
@@ -58,7 +60,13 @@ const SETTINGS_SECTIONS: { label: string; entries: { id: string; label: string }
],
},
{ label: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] },
{ label: 'System', entries: [{ id: 'about', label: 'About' }] },
{
label: 'System',
entries: [
{ id: 'sandbox', label: 'Sandbox' },
{ id: 'about', label: 'About' },
],
},
]
function parseHash(): Route {
@@ -265,6 +273,8 @@ const mutatingIdentity = ref(false)
const accounts = ref<ClawAccount[] | null>(null)
const accountsLoading = ref(false)
const mutatingAccounts = ref(false)
const sandboxState = ref<SandboxState | null>(null)
const savingSandbox = ref(false)
const streamStatus = ref<StreamStatus>('connecting')
const busy = ref(false)
const authRequired = ref(false)
@@ -499,21 +509,50 @@ async function removeProvider(id: string): Promise<void> {
}
}
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews; the stream's
// user_message echo carries the stored ids and dedupes against it.
async function refreshSandbox(): Promise<void> {
try {
sandboxState.value = await claw.sandbox()
apiError.value = null
} catch (err) {
noteApiError(err)
}
}
async function saveSandbox(choice: SandboxSelection): Promise<void> {
savingSandbox.value = true
try {
sandboxState.value = await claw.setSandbox(choice)
pushNotice(
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine',
)
apiError.value = null
} catch (err) {
noteApiError(err)
} finally {
savingSandbox.value = false
}
}
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews and the composed
// chip record — the same plain text and spans the fold records on
// the other side — so the stream's user_message echo, which
// carries the stored ids beside that record, dedupes against it.
const composed = composeChips(message.text, message.pastes)
const rowId = transcript.addSent(
message.text,
composed.text,
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
composed.pastes,
)
busy.value = true
try {
// Fire-and-forget by design: the claw answers 202 and the reply
// arrives on the event stream. The body carries the images only
// when there are some.
// arrives on the event stream. The chips and the images ride the
// body only when there are some.
await claw.sendMessage(
activeKey.value,
message.text,
message.pastes,
message.images.map(({ media_type, data }) => ({ media_type, data })),
)
apiError.value = null
@@ -581,6 +620,7 @@ function saveToken(): void {
void refreshSessions()
void refreshIdentity()
void refreshAccounts()
void refreshSandbox()
}
// --- the one live subscription ---------------------------------------
@@ -657,6 +697,7 @@ onMounted(() => {
void refreshIdentity()
void refreshProviders()
void refreshAccounts()
void refreshSandbox()
void refreshSessions()
healthTimer = setInterval(checkHealth, 30000)
sessionsTimer = setInterval(() => void refreshSessions(), 20000)
@@ -789,6 +830,12 @@ onUnmounted(() => {
@add="addProvider"
@remove="removeProvider"
/>
<SettingsSandboxPage
v-show="route.section === 'sandbox'"
:state="sandboxState"
:saving="savingSandbox"
@save="saveSandbox"
/>
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
</template>
</main>
+34 -19
View File
@@ -10,12 +10,14 @@
import {
PASTE_INLINE_LINES,
chipLabel,
embedPastes,
byteToIndex,
chipLinesLabel,
lineCount,
normalizePaste,
pasteParts,
} from '~/composables/useTranscript'
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
import type { PasteSpan } from '~/composables/useClaw'
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
const props = defineProps<{
@@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
* the staged images, previews included for the optimistic row. */
interface SendPayload {
text: string
/** The chip payloads, in staging order — the wire carries them
* beside the plain draft; the fold composes the record. */
pastes: string[]
images: StagedImage[]
}
@@ -136,20 +141,12 @@ watch(
},
)
// Thinking grows inside the trailing entry without changing the
// entries length, so its total length joins the watch to keep the
// stream pinned at the bottom.
function liveThinkingLength(): number {
return (
props.live?.entries.reduce(
(count, entry) => (entry.kind === 'thinking' ? count + entry.text.length : count),
0,
) ?? 0
)
}
// A consent or attachment card opening inside the trailing turn
// changes the rendered height, so the reply length and the entries
// length both join the watch that keeps the stream pinned at the
// bottom.
watch(
() => [props.items.length, props.live?.reply.length, liveThinkingLength(), props.live?.entries.length],
() => [props.items.length, props.live?.reply.length, props.live?.entries.length],
async () => {
if (!pinned.value) return
await nextTick()
@@ -165,7 +162,7 @@ function submit(): void {
// answers 202 at once) — a running turn never blocks the composer,
// because a send into one steers it.
if (!text || !props.canSend || props.busy) return
emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value })
emit('send', { text, pastes: pastes.value, images: stagedImages.value })
stageGeneration++
draft.value = ''
pastes.value = []
@@ -367,8 +364,12 @@ function storedImageName(image: SentImage): string {
type MessageSegment = PastePart | { kind: 'chip'; label: string }
/** The message's render pieces: literal text and resolved chips, the
* chips' one-based ids counted across the message. */
function messageSegments(text: string): MessageSegment[] {
* chips' one-based ids counted across the message. The chips come
* from the row's span record — the plain text sliced at the spans'
* byte boundaries — and a row from before spans rode the wire
* carries none; that one still scans the mark form in its text. */
function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] {
if (pastes.length === 0) {
const segments: MessageSegment[] = []
let chip = 0
for (const part of pasteParts(text)) {
@@ -379,6 +380,21 @@ function messageSegments(text: string): MessageSegment[] {
}
}
return segments
}
const indexOf = byteToIndex(text)
const segments: MessageSegment[] = []
let chip = 0
let cut = 0
for (const span of [...pastes].sort((a, b) => a.start - b.start)) {
const start = indexOf(span.start)
const end = indexOf(span.end)
if (start === -1 || end === -1 || start < cut || end < start) continue
if (start > cut) segments.push({ kind: 'text', text: text.slice(cut, start) })
segments.push({ kind: 'chip', label: chipLinesLabel(span.lines, chip++) })
cut = end
}
if (cut < text.length) segments.push({ kind: 'text', text: text.slice(cut) })
return segments
}
const displayName = computed(() => props.activeKey.replace(/^interactive:/, ''))
@@ -453,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
</button>
</div>
<div class="reply plain">
<template v-for="(segment, index) in messageSegments(item.text)" :key="index">
<template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
<template v-else>{{ segment.text }}</template>
</template>
@@ -498,7 +514,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="who">{{ agentName }}</div>
<TurnEntries
:entries="live.entries"
:open-thinking="true"
@consent-answer="(id, answer) => emit('consentAnswer', id, answer)"
@consent-deny="(id) => emit('consentDeny', id)"
@download-attachment="(id, name) => emit('downloadAttachment', id, name)"
+16 -39
View File
@@ -1,17 +1,22 @@
<script setup lang="ts">
// A turn's stream-ordered middle: tool rows, pieces of the thinking
// trace, the agent's asks, its handovers — each at the position the
// stream delivered it, so an ask sits at the tool call that raised it
// and thinking sits between the calls it precedes.
// The turn's middle, as the web surface shows it: the agent's asks
// (consent cards) and its handovers (attachment cards), each at the
// position the stream delivered it. Tool calls and the thinking trace
// stay off this surface; the reply is what it shows, and these two
// cards are the only things the reader must act on or can open.
import { computed } from 'vue'
import type { TurnEntry } from '~/composables/useTranscript'
import type { ConsentAnswer } from '~/composables/useClaw'
defineProps<{
const props = defineProps<{
entries: TurnEntry[]
/** A live turn's thinking blocks start expanded; finished ones collapse. */
openThinking?: boolean
}>()
/** Cards only: a turn's tool rows and thinking blocks never render. */
const cards = computed(() =>
props.entries.filter((entry) => entry.kind === 'consent' || entry.kind === 'attachment'),
)
const emit = defineEmits<{
consentAnswer: [id: string, answer: ConsentAnswer]
consentDeny: [id: string]
@@ -20,21 +25,16 @@ const emit = defineEmits<{
</script>
<template>
<div v-if="entries.length > 0" class="entries">
<template v-for="(entry, index) in entries" :key="index">
<TurnToolRow v-if="entry.kind === 'tool'" :row="entry.row" />
<details v-else-if="entry.kind === 'thinking'" class="thinking" :open="openThinking">
<summary>thinking</summary>
<pre>{{ entry.text }}</pre>
</details>
<div v-if="cards.length > 0" class="entries">
<template v-for="(entry, index) in cards" :key="index">
<TurnConsentCard
v-else-if="entry.kind === 'consent'"
v-if="entry.kind === 'consent'"
:consent="entry.consent"
@answer="(id, answer) => emit('consentAnswer', id, answer)"
@deny="(id) => emit('consentDeny', id)"
/>
<TurnAttachmentCard
v-else
v-else-if="entry.kind === 'attachment'"
:attachment="entry.attachment"
@download="(id, name) => emit('downloadAttachment', id, name)"
/>
@@ -49,27 +49,4 @@ const emit = defineEmits<{
gap: 4px;
margin-bottom: 10px;
}
.thinking {
color: var(--text3);
}
.thinking summary {
cursor: pointer;
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.thinking pre {
margin: 6px 0 0;
padding: 8px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text3);
font-style: italic;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
-102
View File
@@ -1,102 +0,0 @@
<script setup lang="ts">
// One tool call in a turn: running, completed, or failed — shell lines
// for bash (the TUI's tool_row), glyph rows for everything else.
import type { ToolRow } from '~/composables/useTranscript'
defineProps<{ row: ToolRow }>()
/** Command rows render as shell lines, not glyph rows; run_command is
* the bash tool's other name. */
function isShellTool(name: string): boolean {
return name === 'bash' || name === 'run_command'
}
</script>
<template>
<div class="tool-row" :class="{ error: row.isError === true }">
<template v-if="isShellTool(row.name)">
<span class="shell-mark" aria-hidden="true">$ </span>
<span class="shell-command mono">{{ row.command ?? '…' }}</span>
<span
v-if="typeof row.code === 'number'"
class="shell-code mono"
:class="row.code === 0 ? 'ok' : 'failed'"
>[{{ row.code }}]</span>
<span v-else-if="row.isError === true" class="shell-code failed">✗</span>
</template>
<template v-else>
<span class="glyph" aria-hidden="true">{{
row.isError === null ? '…' : row.isError ? '✗' : '✓'
}}</span>
<span class="name mono">{{ row.name }}</span>
<span v-if="row.summary" class="summary mono">{{ row.summary }}</span>
</template>
</div>
</template>
<style scoped>
.tool-row {
display: flex;
gap: 8px;
align-items: baseline;
padding: 5px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-left: 3px solid var(--ok);
border-radius: 6px;
}
.tool-row.error {
border-left-color: var(--error);
}
.glyph {
flex: none;
color: var(--ok);
}
.tool-row.error .glyph {
color: var(--error);
}
.name {
color: var(--text);
}
.summary {
color: var(--text3);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A bash row reads as the shell line it ran: dim $ prefix, the
command, and the exit code pushed to the row's right end. */
.shell-mark {
flex: none;
color: var(--text3);
white-space: pre;
}
.shell-command {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text);
}
.shell-code {
flex: none;
font-size: 11px;
}
.shell-code.ok {
color: var(--ok);
}
.shell-code.failed {
color: var(--error);
}
</style>
@@ -0,0 +1,259 @@
<script setup lang="ts">
// The Sandbox page: where the agent's `bash` runs. The choice saves as
// a whole; the token is write-only, so an empty field keeps whatever
// the claw already stored. Presentational: data flows in as props,
// intent flows up as events.
import type { SandboxKind, SandboxSelection, SandboxState } from '~/composables/useClaw'
const props = defineProps<{
state: SandboxState | null
saving: boolean
}>()
const emit = defineEmits<{
save: [choice: SandboxSelection]
}>()
const kind = ref<SandboxKind>('local')
const url = ref('')
const token = ref('')
const clearToken = ref(false)
const dirty = computed(() => {
const state = props.state
if (!state) return false
if (kind.value !== state.kind) return true
if (kind.value !== 'http') return false
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const ready = computed(() => kind.value !== 'http' || urlValid.value)
const urlHint = computed(() =>
url.value.trim() && !urlValid.value
? 'The URL must start with http:// or https://.'
: 'The sandboxd base URL, for example https://box.example:7600.',
)
function sync(): void {
const state = props.state
if (!state) return
kind.value = state.kind
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
}
watch(
() => props.state,
(state) => {
if (state) sync()
},
{ immediate: true },
)
function discard(): void {
sync()
}
function save(): void {
if (!dirty.value || props.saving || !ready.value) return
const choice: SandboxSelection = { kind: kind.value }
if (kind.value === 'http') {
choice.url = url.value.trim()
if (token.value.trim() !== '') {
choice.token = token.value.trim()
} else if (clearToken.value) {
choice.clear_token = true
}
}
emit('save', choice)
}
// The path the staged choice would use, not the saved one.
const workspacePath = computed(() => {
const state = props.state
if (!state) return ''
return kind.value === 'http' ? state.remote_workspace : state.local_workspace
})
</script>
<template>
<div class="page">
<PageHeader title="Sandbox" subtitle="Where the agent's bash runs.">
<template #actions>
<button :disabled="!dirty || saving" @click="discard">Discard</button>
<button class="primary" :disabled="!dirty || saving || !ready" @click="save">
{{ saving ? 'Saving…' : 'Save' }}
</button>
</template>
</PageHeader>
<div class="scroll">
<p v-if="!state" class="muted">loading sandbox…</p>
<template v-else>
<SettingCard title="Execution" meta="applies on the next turn">
<label class="option" :class="{ selected: kind === 'local' }">
<input v-model="kind" type="radio" value="local" :disabled="saving" />
<span class="option-text">
<span class="option-title">
This machine
<span v-if="state.kind === 'local'" class="current">current</span>
</span>
<span class="option-detail">
Commands run as processes on the daemon's host.
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'http' }">
<input v-model="kind" type="radio" value="http" :disabled="saving" />
<span class="option-text">
<span class="option-title">
Remote sandbox
<span v-if="state.kind === 'http'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a host that speaks the sandbox protocol over HTTP.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
<SettingRow
title="URL"
:description="urlHint"
>
<input
v-model="url"
type="text"
class="mono"
placeholder="https://box.example:7600"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Token"
:description="state.token_set
? 'A token is stored. Leave this blank to keep it.'
: 'The shared secret the daemon checks. Leave it blank when the daemon has none.'"
>
<input
v-model="token"
type="password"
:placeholder="state.token_set ? 'stored' : 'optional'"
autocomplete="off"
:disabled="saving || clearToken"
/>
</SettingRow>
<SettingRow
v-if="state.token_set"
title="Stored token"
:description="clearToken
? 'The stored token is removed when you save.'
: 'The token stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearToken = !clearToken">
{{ clearToken ? 'Keep token' : 'Forget token' }}
</button>
</SettingRow>
</SettingCard>
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy">
On first use the claw sends the local workspace to the sandbox as a tarball.
Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout>
<SettingCard title="Workspace">
<SettingRow
title="Path"
description="Where the agent's bash starts under this choice."
>
<code>{{ workspacePath }}</code>
</SettingRow>
</SettingCard>
</template>
</div>
</div>
</template>
<style scoped>
.page {
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
flex: 1;
}
.scroll {
flex: 1;
overflow-y: auto;
padding: 0 24px 24px;
display: flex;
flex-direction: column;
gap: 16px;
max-width: 860px;
}
.muted {
color: var(--text3);
padding: 8px 2px;
}
.option {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 13px 16px;
cursor: pointer;
}
.option:hover {
background: var(--elevated);
}
.option.selected {
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
}
.option input[type='radio'] {
flex: none;
margin: 3px 0 0;
accent-color: var(--accent);
}
.option-text {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
.option-title {
display: flex;
align-items: baseline;
gap: 8px;
color: var(--text);
font-weight: 600;
}
.option-detail {
color: var(--text3);
font-size: 12.5px;
}
.current {
color: var(--accent-text);
font-size: 12px;
font-weight: 500;
}
</style>
+130 -9
View File
@@ -56,9 +56,20 @@ export interface UserImage {
media_type: string
}
/** One paste chip a `user_message` carries: the record the session's
* `rhema-code` annotation holds — the byte range in the plain text the
* chip stands for (UTF-8 offsets; see useTranscript's
* `byteToIndex`), plus the payload's line count for the chip's label
* (rhema-core `PasteSpan`). */
export interface PasteSpan {
start: number
end: number
lines: number
}
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
export type TurnEvent =
| { type: 'user_message'; text: string; images: UserImage[] }
| { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
| { type: 'thinking_delta'; text: string }
| { type: 'text_delta'; text: string }
| { type: 'tool_start'; name: string }
@@ -220,6 +231,34 @@ export interface ActiveBackend {
active: { provider: string; model: string }
}
/** Where the agent's `bash` runs: this host or a daemon speaking the
* sandbox protocol over HTTP. */
export type SandboxKind = 'local' | 'http'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */
export interface SandboxState {
kind: SandboxKind
url: string | null
token_set: boolean
/** Where `bash` starts under the current choice. */
workspace: string
/** The daemon's chat workspace, whatever the choice. */
local_workspace: string
/** The path a remote sandbox exposes. */
remote_workspace: string
}
/** The body `PUT /v1/sandbox` takes. `token` is write-only, and
* `clear_token` drops the stored one. An omitted `url` keeps the
* current one. */
export interface SandboxSelection {
kind: SandboxKind
url?: string
token?: string
clear_token?: boolean
}
/** A failed API call: the status plus the claw's `error` string when it sent one. */
export class ClawError extends Error {
/** HTTP status; 0 when the claw was unreachable at all. */
@@ -240,7 +279,9 @@ const INTERACTIVE_PREFIX = 'interactive:'
* connection and reconnects: the claw sends a keep-alive comment every
* fifteen seconds (hub.rs), so three missed ones means the path is
* black-holed — a half-open TCP after a laptop sleep shows the same
* 'live' badge a healthy stream does without this check. */
* 'live' badge a healthy stream does without this check. The watchdog
* is paused while the tab is hidden: browsers throttle timers and can
* stall the reader there, and a tab switch is not a dead stream. */
const STREAM_SILENCE_TIMEOUT_MS = 45000
/** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */
@@ -368,8 +409,8 @@ export interface ClawApi {
* a plain src will not do). Cached per id: attachments are immutable,
* so a replayed event never refetches. */
attachmentUrl(id: string): Promise<string>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
/** `GET /v1/providers` — the constructible backends and the active pair. */
providers(): Promise<ProvidersState>
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
@@ -383,6 +424,11 @@ export interface ClawApi {
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers
* the new providers state. The last backend is refused claw-side. */
removeProvider(id: string): Promise<ProvidersState>
/** `GET /v1/sandbox`: where the agent's `bash` runs. */
sandbox(): Promise<SandboxState>
/** `PUT /v1/sandbox`: switch the sandbox, persisted claw-side. The
* choice applies on the next turn. */
setSandbox(choice: SandboxSelection): Promise<SandboxState>
/** `GET /v1/accounts` — the stored accounts, redacted. */
accounts(): Promise<ClawAccount[]>
/** `POST /v1/accounts` — store an account (the secret is write-only),
@@ -498,11 +544,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})
}
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> {
async function sendMessage(
key: string,
text: string,
pastes?: string[],
images?: OutboundImage[],
): Promise<void> {
const body: { text: string; pastes?: string[]; images?: OutboundImage[] } = { text }
if (pastes?.length) body.pastes = pastes
if (images?.length) body.images = images
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(images?.length ? { text, images } : { text }),
body: JSON.stringify(body),
})
}
@@ -563,6 +617,18 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})) as ProvidersState
}
async function sandbox(): Promise<SandboxState> {
return (await get('/v1/sandbox', token.value)) as SandboxState
}
async function setSandbox(choice: SandboxSelection): Promise<SandboxState> {
return (await send('/v1/sandbox', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(choice),
})) as SandboxState
}
async function accounts(): Promise<ClawAccount[]> {
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
return body.accounts
@@ -639,11 +705,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
* notice says so instead of naming an opaque abort error. */
let timedOut = false
let silence: ReturnType<typeof setTimeout> | null = null
const isHidden = (): boolean =>
typeof document !== 'undefined' && document.hidden
/** Whether the attempt in flight crossed a hidden tab: a drop there
* is a backgrounded connection, not a stream the user needs a notice
* about. */
let hiddenDuringAttempt = isHidden()
const rearmSilence = (): void => {
if (silence !== null) clearTimeout(silence)
silence = null
if (closed || isHidden()) return
silence = setTimeout(() => {
if (closed) return
if (closed || isHidden()) return
timedOut = true
current?.abort()
}, STREAM_SILENCE_TIMEOUT_MS)
@@ -652,6 +726,23 @@ export function useClaw(token: Ref<string | null>): ClawApi {
if (silence !== null) clearTimeout(silence)
silence = null
}
/** A frame or keep-alive proved this attempt alive: from here on a
* drop is real, even if the tab was hidden earlier. */
const noteActivity = (): void => {
hiddenDuringAttempt = false
rearmSilence()
}
const visibility = (): void => {
if (isHidden()) {
hiddenDuringAttempt = true
stopSilence()
return
}
if (current !== null && !current.signal.aborted) rearmSilence()
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', visibility)
}
const status = (next: StreamStatus) => {
if (!closed) handlers.onStatus?.(next)
@@ -663,6 +754,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const controller = new AbortController()
current = controller
timedOut = false
hiddenDuringAttempt = isHidden()
rearmSilence()
try {
const resume = cursor === null ? '' : `?since=${cursor}`
@@ -684,7 +776,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
await readFrames(
response.body,
(data, id) => {
rearmSilence()
noteActivity()
const event = parseTurnEvent(data)
if (!event) return
const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null
@@ -694,7 +786,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
(comment) => {
// Keep-alives come through here too; each one proves the
// path alive.
rearmSilence()
noteActivity()
// The record lost what this mirror holds: drop the cursor
// so the next open asks for the tail, and let the consumer
// drop its items before the tail that already followed
@@ -720,11 +812,16 @@ export function useClaw(token: Ref<string | null>): ClawApi {
// Backoff caps at 15s: a live stream of a running turn is the
// UI's whole job, so retries stay eager but not tight-looped.
const backoff = Math.min(15000, 1000 * 2 ** attempt++)
// A connection that crossed a hidden tab reconnects quietly:
// the browser held it while the page was in the background,
// and the operator did not just lose a live stream.
if (!isHidden() && !hiddenDuringAttempt) {
handlers.onNotice?.(
timedOut
? `the event stream went quiet (no keep-alive for ${STREAM_SILENCE_TIMEOUT_MS / 1000}s); reconnecting in ${backoff / 1000}s`
: `event stream dropped (${cause instanceof Error ? cause.message : String(cause)}); retrying in ${backoff / 1000}s`,
)
}
status('reconnecting')
await new Promise((resolve) => setTimeout(resolve, backoff))
} finally {
@@ -738,6 +835,9 @@ export function useClaw(token: Ref<string | null>): ClawApi {
close() {
closed = true
stopSilence()
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', visibility)
}
current?.abort()
},
}
@@ -757,6 +857,8 @@ export function useClaw(token: Ref<string | null>): ClawApi {
models,
setCredentials,
removeProvider,
sandbox,
setSandbox,
accounts,
addAccount,
removeAccount,
@@ -836,6 +938,24 @@ function parseUserImages(raw: unknown): UserImage[] {
return images
}
/** The paste chips a `user_message` carries: rows recorded before
* chips rode as spans carry the mark form in the text instead and no
* field at all — empty, the render falls back to scanning — and a
* span without whole-number bounds or a line count is not one. */
function parseUserPastes(raw: unknown): PasteSpan[] {
if (!Array.isArray(raw)) return []
const pastes: PasteSpan[] = []
for (const entry of raw) {
const span = entry as Record<string, unknown>
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
if (typeof span.lines !== 'number') continue
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
pastes.push({ start: span.start, end: span.end, lines: span.lines })
}
return pastes
}
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
function parseTurnEvent(data: string): TurnEvent | null {
try {
@@ -846,6 +966,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'user_message',
text: String(raw.text ?? ''),
images: parseUserImages(raw.images),
pastes: parseUserPastes(raw.pastes),
}
case 'thinking_delta':
case 'text_delta':
+50 -16
View File
@@ -6,7 +6,7 @@
// mirror when the stream reopens and folds what arrives, never the other
// way around.
import { ref } from 'vue'
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw'
import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
/** One tool call inside a turn: started, then completed by its result. */
export interface ToolRow {
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
/** A transcript line: a message the local user sent, or one streamed turn. */
export type TranscriptItem =
| { kind: 'sent'; id: number; text: string; images: SentImage[] }
| { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
| { kind: 'turn'; id: number; turn: TurnBlock }
| { kind: 'consent'; id: number; consent: ConsentCard }
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
return lines.length
}
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
* payload's line count (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return `▣${index + 1} ${lineCount(paste)}L`
/** A chip's label from its line count: `▣1 5L` — the chip's
* one-based id and the payload's line count (the TUI's chip_label). */
export function chipLinesLabel(lines: number, index: number): string {
return `▣${index + 1} ${lines}L`
}
/** Appends each paste as one MARK-payload-MARK embed, in order — the
* session's record of the prompt (paste::embed; a web draft holds no
* anchors, so every payload lands at the end). */
export function embedPastes(draft: string, pastes: string[]): string {
return (
draft +
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
)
/** A chip's label from its payload (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return chipLinesLabel(lineCount(paste), index)
}
/** The modern record the wire carries: each paste a byte span in the
* plain text (the `rhema-code` annotation's own shape), one walk over
* the composed text mapping every code-point boundary — a span that
* splits a code point maps to none, the render skips it. */
export function byteToIndex(text: string): (byte: number) => number {
const at = new Map<number, number>([[0, 0]])
const bytesOf = new TextEncoder()
let bytes = 0
let units = 0
for (const cp of text) {
bytes += bytesOf.encode(cp).length
units += cp.length
at.set(bytes, units)
}
return (byte) => at.get(byte) ?? -1
}
/** Composes a send the way the fold composes its record: each paste's
* normalized payload appends to the draft, its chip's span measured
* over the composed plain text. The same form the `user_message`
* echo carries, so the optimistic row and the replay render rows of
* one shape and the echo dedupes against what this surface sent. */
export function composeChips(
draft: string,
pastes: string[],
): { text: string; pastes: PasteSpan[] } {
const bytesOf = new TextEncoder()
let text = draft
const spans: PasteSpan[] = []
for (const paste of pastes) {
const payload = normalizePaste(paste)
const start = bytesOf.encode(text).length
text += payload
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
}
return { text, pastes: spans }
}
/** One scanned piece of embedded-form text. */
@@ -244,6 +277,7 @@ export function useTranscript() {
id: nextId++,
text: event.text,
images: event.images.map((image) => ({ ...image, url: null, name: null })),
pastes: event.pastes,
})
break
}
@@ -356,10 +390,10 @@ export function useTranscript() {
* Its images render from the staged previews — the claw stores them
* and the stream's echo dedupes against this row. Returns the row's
* id, so a failed POST can retract it. */
function addSent(text: string, images: SentImage[] = []): number {
function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
const id = nextId++
pendingSent.push({ text, images: images.length, itemId: id })
items.value.push({ kind: 'sent', id, text, images })
items.value.push({ kind: 'sent', id, text, images, pastes })
return id
}