Compare commits

...
44 Commits
Author SHA1 Message Date
vhaudiquet 9e3890c568 fix(claw): release the turns a restart cut as superseded
android / debug (push) Successful in 2m24s
android / release (push) Successful in 2m1s
ci / checks (push) Successful in 1m5s
ci / test (push) Successful in 37s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m51s
ci / web (push) Successful in 12s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m51s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 8s
ci / publish-edge-chart (push) Successful in 4s
A record keeps the outcome of its last release. A dispatch that was
checkpointing when the process died left nothing newer, so its thread
wore the outcome of the turn before it: a handled turn, ending on the
first line the model streamed. The mention had been drained before the
turn ran, so no reply was ever posted and nothing re-ran the key.

Boot now reads the leases the dead process left, recovers them as
before, and releases each one as superseded. The cut turn reads aborted
instead of borrowing the previous outcome, and the superseded outcome
says what the store knows: the work nobody finished is not wanted any
longer.
2026-11-24 21:52:00 +01:00
vhaudiquet d1c1e7c8d9 fix(claw): read a turn with no release as running or aborted
The read-only transcript closes its newest turn with the record's last
outcome, and a record that never released has none, so the turn closed as
"handled". A turn a restart cut read back as finished work, with the
model's first line standing in for the answer it never gave.

No release now reads as what it is: the record holds the lease, so the
turn is running, or it does not, so the turn was cut. Handled still means
a dispatch finished and posted.
2026-11-24 21:52:00 +01:00
vhaudiquet 70b53665d5 fix(web/claw): fetch an image again for a card the mirror rebuilt
android / debug (push) Successful in 2m31s
ci / docker (push) Successful in 2m3s
ci / web (push) Successful in 15s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 2m3s
android / release (push) Successful in 2m13s
ci / checks (push) Successful in 1m7s
ci / test (push) Successful in 39s
ci / chart (push) Successful in 5s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 13s
ci / publish-edge-chart (push) Successful in 3s
A page read, a mirror reset, or a turn folding into the record builds
new card objects, and the pass that fetches image bytes remembered
attachment ids, so a rebuilt card whose bytes had not landed was never
asked for again. The guard now rides the card object: a new card gets
its fetch, and the useClaw cache answers a repeat with the blob it
already holds, so nothing is requested twice.

The object URL also lands on every card naming the id, not only the
first. A page's open tail is dropped and re-read with the turn's
beginning above it, which can leave two cards for one attachment, and
the second stayed blank.
2026-11-24 21:33:15 +01:00
vhaudiquet ea6edfe67a fix(claw): open a fresh stream on the newest turn's first event
A client with no cursor opens on the newest 400 events, and the route cut
that window back to the first question in it. A turn longer than the
window has no question inside it, so the cut did nothing and the replay
started mid-turn. A reload then landed on the middle of a reply: the
question was gone from the top, and so was everything the turn began
with, attachments included. A turn that attaches a file and then streams
a long answer hits this every time.

The window now widens by doubling while it sits inside one turn, up to
the history scan cap, and a record that opens inside a turn comes back
whole. A record with no question in it reads once to its start and
stops, so the walk still terminates.
2026-11-24 21:33:15 +01:00
vhaudiquet 04b06e7623 fix(web/claw): render and download the images a turn hands over
ci / checks (push) Successful in 1m13s
android / debug (push) Successful in 2m17s
android / release (push) Successful in 2m13s
ci / test (push) Successful in 42s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m52s
ci / web (push) Successful in 12s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m57s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 13s
ci / publish-edge-chart (push) Successful in 3s
An attachment card lands inside the turn that produced it, and both
passes that touch image cards scanned only the top-level rows. The pass
that fetches bytes never saw the card, so it stayed a name and a size
with no picture. The pass that stores the fetched object URL had the
same blind spot, so even a fetch that ran dropped its result. Both now
walk finished turns and the live one, through one helper that knows
where cards live. Consents move to the same helper: a card whose turn
already closed had the same problem.

The download control was hidden for `media: "image"`, which left an
image with no way out of the store when its bytes did not paint, as
they never did. Every card offers it now. The anchor also joins the
document for the click, which some browsers require before they follow
a `download` on a blob URL.
2026-11-24 21:17:02 +01:00
vhaudiquet 1a1ace014a feat(web/claw): open every key, read-only when it has no stream
android / debug (push) Successful in 2m29s
ci / test (push) Successful in 42s
ci / docker (push) Successful in 2m0s
ci / web (push) Successful in 12s
android / release (push) Successful in 2m17s
ci / checks (push) Successful in 1m13s
ci / chart (push) Successful in 6s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 2m0s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 13s
ci / publish-edge-chart (push) Successful in 3s
Every row in the sidebar was disabled unless its key started with a
resident prefix, so a forge thread or a finished job could only be
paused or aborted, never read.

Now every row opens. A resident key subscribes as before. Any other key
loads the snapshot its history route serves, which carries `read_only`;
the header says `snapshot` instead of claiming a live stream, and the
composer becomes a line saying why there is none. The mirror is the same
one the stream feeds, so paging, outcomes, and the turn renderer come
for free.

That view has no stream to tell it a dispatch ran, so the inventory's
revision drives reloads: a poll that sees it move fetches the newest
page again, and nothing else does, so the pages a reader walked back to
survive polling.

`phone:` joins the client's resident prefixes, which the daemon already
carried: those rows were dead ends that refused the message the phone
client sends every day.

The user label follows the key: a chat or phone key's rows are the
human's, any other key's are the prompt its dispatch started with.
2026-11-24 20:58:02 +01:00
vhaudiquet 8d7dc7c4c7 feat(claw): read a non-chat key's history back as a snapshot
The history route served only the resident prefixes, and every other key
in the inventory answered 400: a forge thread, a finished coding job.
Those keys never stream, because their handlers run outside the hub, so
the daemon holds no turn record to page.

What it does hold is the session stash the step engine checkpoints after
every step, with the engine's own history in it. `thread` turns that
history back into the hub's event shapes and cuts pages at turn
boundaries with the hub's own rule, so one client renderer paints both a
live chat and a finished thread. The store's `last_outcome` lands on the
newest turn; earlier turns closed handled.

The response carries `read_only`: the key takes no message, which the
message route and the event stream already enforce. A key with no stash
answers an empty page, since the inventory lists it and an empty
transcript is the truth about it.

A page ends at `before` and starts on the first user message in its
window, widening by doubling while the window sits inside one turn. A
turn longer than the limit comes back whole, and `more` says whether
anything sits below the page.
2026-11-24 20:57:58 +01:00
vhaudiquet 23aea1195d refactor(claw): carry the tool seam the 0.4.2 line removed
android / debug (push) Successful in 2m18s
android / release (push) Successful in 2m10s
ci / checks (push) Successful in 2m25s
ci / test (push) Successful in 1m1s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m56s
ci / web (push) Successful in 12s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m52s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 18s
ci / publish-edge-chart (push) Successful in 3s
The 0.4.2 line deletes the resident tool machinery from
rhema-autonomous-agent. The claw was its only consumer, so the
registry, the TOOL.yaml loader, the allowlist, and the resolver chain
now live in `toolkit`, beside the manifests and builtins that feed
them. The shapes do not change; only the owner does.

The compiler marked the rest of the release's edges:

- The resolver seam grew `resolve_streaming`, so the chain returns the
  shell's output as deltas and a filtered registry still answers the
  plain call.
- `ShellExecutor::run` now takes a `RunRequest` and a `ToolProgress`
  sink. The sandbox adapter re-roots the request for the wrapped
  sandbox and relays its `RunOutcome`; `Sandbox::exec` became
  `Sandbox::run`, so the seed probe follows.
- `SandboxError::OutOfMemory` joins the error mapping.
- `rhema_core::paste` left the engine with the display encodings, so
  `paste` here carries the span record, the annotation, and the legacy
  migration. A stash from either line loads unchanged.
- `rhema_bash::exec` no longer re-exports `async_trait`; the tool
  modules import it from the crate.

The dependency pins and both integrations move to 0.4.2 together; the
lock refreshes with them.
2026-11-24 20:02:46 +01:00
vhaudiquet ea26019f0c build: ship gob in the claw image
A coding turn that starts a dev server or a build has to either wait for
it or background it with `&`, and a backgrounded process is gone from the
next turn's view: no id, no logs, no port. gob keeps the process table
that the agent and the operator both read, so the turn returns and a
later one asks what happened.

The release carries a static linux binary for amd64 and arm64. The image
downloads one from a pinned tag (GOB_VERSION, a build arg) and unpacks it
to /usr/local/bin/gob; no package rides along. No other arch is
published, so a build for one fails at the download instead of shipping a
container whose shell has no gob.

The image gains XDG_RUNTIME_DIR=/tmp/run with it. Left unset, gob looks
for /run/user/1000, which nothing creates here, and its daemon dies with
"socket not created" even though the job table is writable. The socket
stays off the volume, where an NFS PVC cannot hold one. The state
(state.db, the run logs) follows XDG_STATE_HOME to /data/state, so jobs
survive a restart of the container.

Checked on the image's own base: gob run, gob add, gob list and gob
shutdown as uid 1000, no flags. The full image still cannot build before
the 0.4.2 sandbox release (cargo fetch rejects the unpublished pin), so
the runtime stage was built from the Dockerfile's own lines.
2026-11-23 22:54:07 +01:00
vhaudiquet dc269472eb feat(web/claw): list every key and control its dispatch
The sidebar listed only the resident prefixes. The phone's status keys,
the coding jobs' `job:<instance>#<id>` keys and the forge threads were
on the wire and invisible in the client: an operator watching a job fill
a queue had no row to look at, let alone act on. *Others* now carries
the whole inventory, folded to the working count as before and every row
listed unfolded. A row the chat cannot open is a control row — the
resident prefixes are the only ones with a transcript — so it renders
as a disabled entry rather than a dead click-through, and it keeps the
status dot, the held badge and the depth that every row has.

Beside the delete button, on hover: `hold` posts the pause and the row
badges `held` in the warn tone, `run` posts the resume, `stop` posts the
abort. `stop` is disabled when there is neither a live turn nor queued
work, so an idle row sends nothing instead of collecting a no-op
answer. What the abort did reads in the notice — the turn stopped, N
queued items dropped, or nothing running — straight from the answer's
`cut` and `dropped`.

An aborted turn renders in the warn tone too: cut by the operator, not
failed, and unlike a steered turn nothing replaces it. The About page's
route list gains the three, and the README's inventory and delete
paragraphs follow the fold and the controls.

nuxt typecheck and build pass; checked against a mock daemon on a
seeded store, folded and unfolded, with a held row, a queued job and an
aborted turn.
2026-11-23 22:38:26 +01:00
vhaudiquet 38292b6344 feat(claw): pause, resume and abort a key's dispatch
The inventory could show a key's queue and delete the key, and nothing
in between: a key wedged on a long turn, or a queue filling from a
source the operator wanted stopped, had no control short of a restart.
Three routes now sit beside the delete.

Pause is an operator's hold, not a dispatcher state: rhema-rsd has
idle, leased and re-acquire, and none of them means "keep the events,
run nothing". So the hold lives beside the store, a set of keys the
drivers' ownership predicates decline, persisted as `paused:<key>` rows
in the settings table and reloaded at boot. A held key ingests as
always, its inbox accumulates, `admit` offers it, and every driver
passes it by until resume lifts the hold. Deleting a key drops its
hold with it, so a name created again starts clean.

Abort stops what a pause cannot: a live turn is a dispatch minutes deep
in tool rounds, and only the dispatch itself can end it. An abort
registry carries the signal to the handler's own select, which drops
the turn future at its current await — a streaming request, or a
running shell command whose child dies with the drop. What the turn
committed is already the session (the commit hook), so the handler
repairs the dangling calls and releases as superseded rather than
failed: the work is no longer wanted. The chat closes on an `aborted`
end marker, the forge thread gets no half-answer, and a coding job's
row lands failed with `aborted`. An idle key's queued work is drained
and dropped under a throwaway lease instead, and a job row moves with
the queue it lost, or it would sit queued forever with nothing left to
run it.

The jobs handler arms its listener at dispatch entry rather than after
the agent is built: the route signals the moment it sees the lease, and
a listener arriving later would let an early abort fall through as a
no-op. Signalling a key with no listener stays a no-op, which is what
lets the route call it unconditionally before its idle path.

GET /v1/sessions carries `paused` beside the state, and the abort
answer says which shape it took: `{"key", "cut", "dropped"}`.

Verified with fmt, clippy -D warnings and the suite (266 lib, 40 http,
including a surface test for the three routes and one proving a dropped
queued job key lands its row aborted). The three sandbox deps still pin
unpublished 0.4.2, so the gates ran against a temporary 0.4.1 pin with
the one 0.4.2 call stubbed, then reverted.
2026-11-23 22:38:22 +01:00
vhaudiquet cbd52b3b3f feat(claw): carry the ssh private key in the sandbox choice
The ssh sandbox took its credential from a key file the local
disk had to hold, so a daemon whose secrets live in a store could
not reach a far box without staging a file first. The choice
gains private_key, the key text itself, threaded to the ssh
backend's with_private_key; unset, the built-in hunt tries the
agent and the default key files as before.

The route keeps the token's write-only contract: GET /v1/sandbox
answers private_key_set and never the key, PUT takes private_key
and clear_private_key, an absent field keeps the stored one, a
present-but-blank one clears it, and config.yaml's sandbox
section accepts the field for boot seeding. The settings page
grows the key textarea with its forget row, the token UI's
shape.

The three sandbox deps move to 0.4.2 for the seam, so the crate
builds once the rhema 0.4.2 release lands on crates.io; until
then the Rust gates cannot run and were checked by hand (cargo
fmt parses the tree, vue-tsc passes).
2026-11-22 20:02:06 +01:00
vhaudiquet 49c2fa42df chore(web/claw): refresh the npm dependencies in range
npm update moves every package inside its declared range:
markdown-it 15.0.3, nuxt 4.6.4, vue 3.5.46, vue-tsc 3.3.14. The
lockfile rewrite is larger than the moves because npm re-resolves
the tree; npm ls and the build agree on the result.

typescript stays on 5.9. The 7.0 line on the index is the Go
rewrite, a different compiler with its own migration; that moves
when the web surface is checked against it, not in a dependency
pass.

nuxt typecheck passes.
2026-11-22 14:22:15 +01:00
vhaudiquet 4887e1c6d3 build: release 0.4.1 and refresh the dependencies
The workspace moves to 0.4.1 and the helm chart's version and
appVersion follow.

cargo update takes every compatible refresh the index offers (24
patch bumps across the tree). Three direct requirements move a
semver line: reqwest 0.12 to 0.13, quick-xml 0.41 to 0.42, base64
0.22 to 0.23.

reqwest 0.13 gates the query builder behind a feature of its own,
so the claw's dev dependency and both integrations carry query
beside json. The 0.12 line stays in the tree: the published rhema
crates still require it, and semver-incompatible dependencies
coexist where links allows.

quick-xml 0.42 makes LocalName hold a &str and xml10_content
infallible, so the CalDAV multistatus parser drops its from_utf8
unwrap and the map_err on a Result that no longer exists.

rusqlite stays on 0.40. The published rhema-identity 0.4.1 still
requires ^0.40, and libsqlite3-sys declares links = sqlite3, which
the resolver allows exactly once per binary: two versions cannot
coexist the way reqwest's do. The requirement moves when the
published family publishes a rusqlite 0.43 build.

Verified with fmt, clippy -D warnings, and the full workspace test
suite with all features (449 tests).
2026-11-22 14:22:12 +01:00
vhaudiquet fa135acbc6 fix(git-identity): read and write git's global scope, not a guessed file
android / debug (push) Successful in 3m1s
android / release (push) Successful in 2m44s
ci / checks (push) Successful in 1m11s
ci / test (push) Successful in 41s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m31s
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 9s
ci / publish-edge-chart (push) Successful in 4s
The provisioning resolved its target itself: GIT_CONFIG_GLOBAL when
set, `.gitconfig` in the home otherwise. That guess is wrong on half
the machines git runs on — git's global scope spans both `.gitconfig`
and the XDG `~/.config/git/config`, and when the user's identity lives
in the XDG file, writing `.gitconfig` shadows it: the daemon's values
win silently over the user's, and the guard — which read only the file
it was about to write — never saw the existing identity it was built
to respect. On this machine the daemon then booted once during testing
and the next commit was authored claw <claw@k6>, and pushed.

The scope is git's now. Reads and writes run through `git config
--global`, so the guard sees whatever a commit would actually carry,
from whichever file holds it; writes land in the file git itself
picks — the established XDG config when that is the one, `.gitconfig`
otherwise. A scope given explicitly pins `GIT_CONFIG_GLOBAL` on the
child process only, which keeps the tests isolated without touching
the caller's environment.

Verified on the machine that was bitten: booting the daemon bare now
resolves the defaults and then keeps the user's identity — no file
written, the XDG values untouched.
2026-11-22 13:58:31 +01:00
vhaudiquet 163fdbf6c9 feat(claw): forge turns answer as the resident
The claw's forge account spoke with a nameless stranger. The forge
handler built its agent on the host crate's built-in prompt — "You are
an agent operating on a host computer" — with no SOUL.md, no USER.md,
and nothing of the resident in it, so the comments posted on a review
request or a mention were written by a generic coding persona wearing
the claw's account. The chat answered as the character the user knows;
the forge answered as nobody.

Forge dispatches render the resident's own prompt now. The handler
holds the bootstrap store and renders the same template per dispatch
the chat renders — SOUL.md, USER.md, the environment report, live, so
a file the chat wrote this morning is what tonight's review carries —
over the thread's workspace, stamped into the agent as a verbatim
system prompt. The tool list renders from the same assembly the host
agent does for its own prompt (the shell built-ins, the transcript's
zoom when the view is on), so the prompt and the request's tools
cannot drift; the vision and MCP sections render from the same wired
values, which the claw template now carries as its own.

Who answers is the system prompt's to say. The reviewer and
implementer framing stays in the dispatch prompt, reworded as the
job — "this dispatch is a review request" — instead of a persona
claim ("you are acting as this thread's reviewer"). Onboarding never
renders on a forge dispatch: a GitHub thread is nobody's first
conversation. The memory section renders only when the roster
actually carries the memory tools, which a forge dispatch does not:
the chat-only rosters (memory, notifications, the key-scoped asks)
still do not ride forge turns.

jobs.rs keeps the bare coding agent on purpose. A background coding
job is the resident delegating — a different persona doing the work
the resident then reviews is the design, not a gap.
2026-11-22 13:54:10 +01:00
vhaudiquet 1b85cd8937 feat(claw): provision the workspace git identity at boot
Every forge thread works in a per-thread workspace, and implementer
turns end in commits. git commit refuses to run without user.name and
user.email, and a fresh workspace carries no gitconfig: the first
commit on a fresh image fails, or succeeds with whatever the agent
improvised. The agent commits as itself — its own name and address,
never the user's, never inferred from whatever accounts happen to
exist.

The identity store gains an email field beside the name, so what
onboarding collects with identity_set and the Agent · General page
edits is what commits carry. The config gains an optional git
section, an operator's override. Each field resolves independently:
config, then identity, then defaults (claw, claw@hostname).

The resolved pair is written into the daemon user's global git config
at boot, in both run shapes — a cron pass commits too. The write is
guarded: the settings store remembers the last pair the daemon wrote,
and boot rewrites a field only when the config still holds that pair
or nothing. A value anyone else set wins outright; the daemon is a
tenant of its user's machine, not the owner of its git config.

Provisioning runs from the binary's boot, not daemon assembly, so the
tests that build daemons never touch a real gitconfig. An ssh sandbox
runs git on another host and stays unprovisioned — a later story.

The web UI gains an Email row on Agent · General; the phone's wire
model gains the optional field.
2026-11-22 11:53:15 +01:00
vhaudiquet 6a81dfa466 fix(forge): persist the account notification cursor
The account poll kept its notifications cursor in a Mutex<HashMap> on
ForgeSource. A restart emptied the map, so the next poll asked the feed
from nothing, and every row the forge still considered unread came back
to be triaged again. mark_read usually consumes a row, but the call is
best-effort, and one failure leaves the row in the feed forever, with
every pass re-deciding it and dispatching a fresh turn for a thread
that already had one.

The repo watches already solve this one scope over: their cursors live
in the watch_cursors table, and a restart resumes from the stored row.
The account poll does the same now, under SCOPE_ACCOUNT, keyed by forge
and account id. The first pass of a new watch still asks from nothing,
because an unread feed is news. A restart asks from the durable row,
and an unreadable row reads as absent, like a repo watch's, so a
corrupted cursor cannot fire a backlog.

Removing an account watch deletes its cursor row with it, as removing a
repo watch already does. A re-add is a new watch.

The new test builds a second ForgeSource over the same store, the shape
every restart takes, and checks its notifications poll carries
since=2026-10-05T12:00:00Z, the cursor the first pass left.
2026-11-22 11:41:32 +01:00
kosmos d887026ff6 fix(daemon): run the long lanes off the tick path
`tick` awaited `forge_driver.run_once()` (and the jobs one before it), and
`Driver::run_once` awaits every run it admits. So while a turn was under
way the loop stopped doing everything else: no forge poll, no watch
health, no due task, no calendar reminder, no phone delivery. With a 60s
poll interval and a ten-minute turn, the daemon polled once per turn —
which is why `last_ok_at` sat frozen at 00:35:02 while the turn that
started at 00:35:03 ran. Not a network problem, and not the watch.

Worse in combination with a longer lease: an hour-long turn would freeze
detection for an hour.

Split the pass. The resident loop (`run`) now uses `resident_tick`, which
detects and then hands the forge and jobs passes to their own tasks; the
interactive drain stays inline, since its runs are the chat itself. One
pass per lane at a time — a tick that fires mid-pass leaves its events in
the dispatcher's inbox for the next one, which is the queue the
dispatcher already is; a second concurrent pass would only lose lease
acquisitions to the first. The in-flight flag is cleared by a drop guard,
so a panicking pass cannot strand its lane permanently.

`tick` keeps its exact shape and semantics: `--once` and the tests still
mean "the work happened" when a pass returns, and the forge-line log
(`[claw] pass: N detected, H handled, F failed`) is unchanged there. The
detached passes log without the detected count, which they do not own.
2026-11-22 02:43:27 +01:00
vhaudiquet 5383b69f7b build: install curl in the claw and sandboxd images
The runtime layer ships bash, git and tar for the shells the agent
runs, but no HTTP client: a turn asked to fetch a URL had nothing to
fetch with. curl joins the same apt line in both images;
ca-certificates was already in the list, so HTTPS needs nothing else.

Checked against debian:stable-slim: the line installs curl 8.14.1 and
an HTTPS fetch resolves.
2026-11-22 02:39:00 +01:00
vhaudiquet d306527792 feat(web/claw): a working line until the turn speaks
The web surface drops a turn's tool rows and thinking trace (only
consent and attachment cards render), so the span between a turn's
first event and its first text delta showed a bare name over empty
space. Now a small ring plus `<agent> is working…` sits below where
the reply will land, on screen exactly while `live.reply` is empty.

The first delta takes the line away and the streaming cursor takes
over from there; the two never show together. Text already streamed
keeps the line gone for the rest of the turn, and a consent card
waiting on the human does not stop it, the turn still being live.
The gap between send and the turn's first event stays bare: no live
block exists there yet, and that is the POST round-trip, not the
model.

The ring is a tokened CSS spinner, muted under the accent name, with
role=status and a prefers-reduced-motion fallback to a static ring.

Verified against a scripted claw (thinking_delta, tool_start, then a
text_delta): the line shows through the tool phase and is gone with
the cursor on the reply.
2026-11-22 02:39:00 +01:00
vhaudiquet 178d0af82b feat(web/claw): fold the other keys to a working count
The task: and calendar: keys sat in the sidebar at full height all
the time, a block of rows most of them idle. The group folds now: by
default it shows one line, the count of other sessions holding a
lease (the same `leased` state the status dot paints green) beside a
more button, and the button unfolds every row and becomes less. The
count stays visible unfolded, so the header does not jump when it
toggles.

The count is gray at zero and takes the ok color only when something
runs. The Sessions header still counts folded rows, and the fold
state is in-memory like the rest of the page: a reload folds again.
2026-11-22 02:39:00 +01:00
vhaudiquet 473a7765e7 feat(claw): run bash on an ssh login, no daemon on the far end
The framework ships rhema-sandbox-ssh; the claw's sandbox seam now
wires it as a third kind beside local and http. The ssh choice carries
a host (any destination the local ssh config resolves) and a workspace
base, default /root, with one directory per claw workspace under it so
two sessions never share a root. The seed probe makes the root first
and quotes it for the remote bash. The settings screen gains the SSH
host card, and /v1/sandbox carries host and workspace.

The rhema family moves to 0.4.1 in lockstep to pick the crate up.
2026-11-22 02:39:00 +01:00
kosmos 24d2323cd3 fix(forge): consume a decided account notification
The account feed is at-least-once in a way the dedup ids do not cover.
`since` is inclusive at the boundary and `NotificationPage::finish`
advances its cursor only to the newest row seen, so a row the poll cannot
get past — anything at or before the cursor, which is every poll — comes
back for as long as the forge still considers it unread. Nothing marked
it read, and the daemon's cursor map is in memory, so a restart asked for
the whole unread feed again.

The result is a re-dispatch loop: the same notification id re-triaged
every pass, a fresh turn for a thread that already has one, and a second
comment on that thread if the first turn ever finished inside its lease.
Observed live on `vhaudiquet/orcaslicer-snap#10`: key revision 1 → 2 at
the 00:35 poll, `inbox_depth: 0`, no outcome — a re-dispatch of a turn
that was already running.

So consume what the poll decides:

- `Forge::mark_read` — a new default no-op on the trait, implemented for
  GitHub as `PUT /notifications/threads/{id}`;
- `Notification::read_key` carries what that route keys on (GitHub keys
  on the notification id, which the dedup id embeds only as text), and
  defaults on deserialize so a payload already in an inbox still decodes;
- `poll_account` marks each row read once it is triaged — dispatched,
  surfaced, or ignored; best-effort, since an unread row costs a repeat
  and never a lost event.

Gitea and GitLab keep the no-op: neither has an account watch here yet.
2026-11-22 01:34:11 +00:00
kosmos 6777eaa247 fix(daemon): lease a forge turn for an hour, not ten minutes
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 96d8bf1d1e fix(forge): read a GitHub notification id as a string or a number
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 701a17c978 feat(claw): a mention of the daemon is an ask, not a phone buzz
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 d4758131fc feat(android): render chips from the span record, not the mark scan
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 dd91501e10 feat: chips travel as span records, not mark embeds
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 22c502a9eb build: move the claw to rhema 0.4.0
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 dc71ac224e fix(web/claw): keep the stream watchdog quiet on a tab switch
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 a583e11e67 build: bump the chart base version past the 0.2.3 release
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 1aa8d5578e feat(claw): choose where bash runs, this host or a remote sandbox
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 5dc8402107 build: move the claw to rhema 0.3.0
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 6d5de9a574 feat(web/claw): render the reply, not the tool calls or the thinking
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 3b32e02ebb docs: add the tools spec, carried from the rhema repository
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 f1a3d3b4ed feat(claw): answer a thread only when somebody addresses the daemon
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 a9c41be440 test(claw): the github mock answers since, as the forge does
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 721efceec5 fix(claw): a repo watch resumes from its durable cursor, or starts now
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 1cab66173f 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 03bdadc2b6 chore: carry dev.sh over — the claw+UI debug loop from the old tree
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 d3af001831 ci: port the rust, chart, docker, web and edge-publish gates from the rhema repository
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 86488320bb 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 5d32588410 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
87 changed files with 16341 additions and 2852 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"
+2
View File
@@ -0,0 +1,2 @@
/target/
.rhema/
Generated
+5088
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.1"
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 **subscribe first, then POST**, the reply arrives on the stream. Thinking
deltas render dim and collapsible, tool rows show name/summary with error deltas render dim and collapsible, tool rows show name/summary with error
coloring (bash-like tools render as shell lines instead: dim `$` prefix, coloring (bash-like tools render as shell lines instead: dim `$` prefix,
the command line, and an exit-code badge), pasted payloads embedded in a the command line, and an exit-code badge), a message's paste chips render
message as paired `U+FFFC` marks render as compact `▣N 5L` chips, and 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 `attachment` events render as cards: file name, size, caption, an inline
preview for small (≤ 2 MB) images, and a download-and-open row (bytes 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 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.ClawEvent
import rs.rhema.phone.net.ClawResult import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.OutboundImage import rs.rhema.phone.net.OutboundImage
import rs.rhema.phone.net.PasteSpan
import rs.rhema.phone.net.SseFrame import rs.rhema.phone.net.SseFrame
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -61,6 +62,10 @@ class ChatController(
override val id: Long, override val id: Long,
val text: String, val text: String,
val images: List<SentImage> = emptyList(), 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 ) : Item
data class Thinking(override val id: Long, val text: String) : Item data class Thinking(override val id: Long, val text: String) : Item
data class ToolCall( data class ToolCall(
@@ -355,14 +360,15 @@ class ChatController(
is ClawEvent.UserMessage -> { is ClawEvent.UserMessage -> {
// The recorded question — replayed on reload, echoed live // The recorded question — replayed on reload, echoed live
// for a message this surface just sent. An identical last // for a message this surface just sent. An identical last
// row — same text, same image count — is that echo's // row — same text, same image count, same chip record —
// stand-in; skip it, previews and all. // is that echo's stand-in; skip it, previews and all.
val last = list.lastOrNull() 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( list = list + UserMessage(
newId(), newId(),
event.text, event.text,
event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) }, event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) },
event.pastes,
) )
} }
} }
@@ -117,6 +117,13 @@ data class RhemaNotification(
@Serializable @Serializable
data class UserImage(val id: String, @SerialName("media_type") val mediaType: String) 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, // One event of GET /v1/sessions/{key}/history: the record's seq for it,
// beside the event itself. Seq order is the wire order. // beside the event itself. Seq order is the wire order.
@Serializable @Serializable
@@ -138,11 +145,13 @@ data class HistoryPage(val events: List<HistoryEvent> = emptyList(), val more: B
sealed interface ClawEvent { sealed interface ClawEvent {
@Serializable @Serializable
@SerialName("user_message") @SerialName("user_message")
// Rows recorded before images rode the stream carry no field at // Rows recorded before images — and then before chips — rode the
// all; absent folds to none, never a guessed shape. // stream carry no field at all; absent folds to none, never a
// guessed shape.
data class UserMessage( data class UserMessage(
val text: String = "", val text: String = "",
val images: List<UserImage> = emptyList(), val images: List<UserImage> = emptyList(),
val pastes: List<PasteSpan> = emptyList(),
) : ClawEvent ) : ClawEvent
@Serializable @Serializable
@@ -252,6 +261,7 @@ data class CommandResult(val ok: Boolean, val detail: String? = null)
@Serializable @Serializable
data class AgentIdentity( data class AgentIdentity(
val name: String? = null, val name: String? = null,
val email: String? = null,
val mark: String? = null, val mark: String? = null,
val initials: String? = null, val initials: String? = null,
val tagline: String? = null, val tagline: String? = null,
@@ -82,6 +82,7 @@ import rs.rhema.phone.chat.MAX_STAGED_IMAGES
import rs.rhema.phone.data.AgentIdentityCache import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.di.AppContainer import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PasteSpan
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -438,6 +439,7 @@ private sealed interface TurnGroup {
val id: Long, val id: Long,
val text: String, val text: String,
val images: List<ChatController.SentImage>, val images: List<ChatController.SentImage>,
val pastes: List<PasteSpan> = emptyList(),
) : TurnGroup { ) : TurnGroup {
override val key: String = "u$id" override val key: String = "u$id"
} }
@@ -451,7 +453,7 @@ private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
val groups = mutableListOf<TurnGroup>() val groups = mutableListOf<TurnGroup>()
for (item in items) { for (item in items) {
when (item) { 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 -> { else -> {
val last = groups.lastOrNull() val last = groups.lastOrNull()
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item)) 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 // Chips render as chips, not payloads; the text
// text around them stays verbatim. // 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 var chip = 0
pasteParts(group.text).forEach { part -> messageParts(group.text, group.pastes).forEach { part ->
when (part) { when (part) {
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge) is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
is PastePart.Paste -> { is PastePart.Paste -> {
@@ -740,20 +745,67 @@ private fun PasteChip(label: String) {
) )
} }
// --- embedded pastes -------------------------------------------------- // --- paste chips ------------------------------------------------------
// The wire form a long paste travels in: MARK, payload, MARK — one // A long paste rides as a chip the render stands in for its payload.
// logical unit inside otherwise plain text (rhema-core's paste module // The record is the span list a user_message carries (the session
// is the definition; these are its client-side shape). A mark with no // annotation's own shape); the marks in the text are the record's
// partner is literal text. // 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' 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 { private sealed interface PastePart {
data class Text(val text: String) : PastePart data class Text(val text: String) : PastePart
data class Paste(val payload: 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 /** Splits embedded-form text into its parts, left to right. A mark with
* no partner is literal text; malformed input never throws. */ * no partner is literal text; malformed input never throws. */
private fun pasteParts(text: String): List<PastePart> { private fun pasteParts(text: String): List<PastePart> {
+29 -16
View File
@@ -26,29 +26,40 @@ mock = ["rhema-core/mock"]
[dependencies] [dependencies]
# The shared toolkit: the resident agent assembles its agent from the # The shared toolkit: the resident agent assembles its agent from the
# shell, the approval seam, paste expansion, and revive-on-resume # shell, the approval seam, and revive-on-resume (rhema-bash), the
rhema-agent-tools = { path = "../rhema-agent-tools" } # system-prompt renderer (rhema-prompt), and the driver that turns a
rhema-autonomous-agent = { path = "../rhema-autonomous-agent" } # provider into a host-operating agent (rhema-host-agent)
rhema-coding-agent = { path = "../rhema-coding-agent" } rhema-bash = "0.4.2"
rhema-config = { path = "../rhema-config" } rhema-prompt = "0.4.2"
rhema-core = { path = "../rhema-core" } rhema-host-agent = "0.4.2"
rhema-autonomous-agent = "0.4.2"
rhema-config = "0.4.2"
rhema-core = "0.4.2"
# The bounded request view over the claw sessions, on by default here # The bounded request view over the claw sessions, on by default here
rhema-transcript = { path = "../rhema-transcript" } rhema-transcript = "0.4.2"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" } rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" } rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll # The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat # with, and the identity tools manage them over chat
rhema-identity = { path = "../rhema-identity" } rhema-identity = "0.4.2"
rhema-rsd = { path = "../rhema-rsd" } rhema-rsd = "0.4.2"
# The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box.
# The choice carries an ssh private key as text, so a store-held
# credential has no file to stage; that is the seam the 0.4.2 line adds,
# and the family moves to it together.
rhema-sandbox = "0.4.2"
rhema-sandbox-http = "0.4.2"
rhema-sandbox-ssh = "0.4.2"
# The tool contract: the agent-token allowlist and version the auth # The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw -> # middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse. # contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" } rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain # The resident tier's durable memory: its tools join the resolver chain
rhema-memory = { path = "../rhema-memory" } rhema-memory = "0.4.2"
# The shared ModelCard the backend registry's listings return # The shared ModelCard the backend registry's listings return
rhema-provider = { path = "../rhema-provider" } rhema-provider = "0.4.2"
rhema-provider-registry = { path = "../rhema-provider-registry", version = "0.2.3" } rhema-provider-registry = "0.4.2"
# Args for the two-flag binary surface # Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true } serde = { workspace = true }
@@ -59,6 +70,8 @@ thiserror = { workspace = true }
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's # A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
# concurrent handler runs share it. `net` is the HTTP listener. # concurrent handler runs share it. `net` is the HTTP listener.
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] } 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 # The chat surface: native routes plus SSE, and the OpenAI shim
axum = { workspace = true } axum = { workspace = true }
# Broadcast receivers as SSE bodies # Broadcast receivers as SSE bodies
@@ -70,20 +83,20 @@ rusqlite = { version = "0.40", features = ["bundled"] }
time = { version = "0.3", default-features = false, features = ["parsing"] } time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the # Inbound chat images ride base64; the dispatch decodes them into the
# attachment store # attachment store
base64 = "0.22" base64 = "0.23"
rhema-mcp = { version = "0.2.3", path = "../rhema-mcp" } rhema-mcp = "0.4.2"
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
# In-process HTTP mocks for the offline e2e: zero network # In-process HTTP mocks for the offline e2e: zero network
wiremock = "0.6" wiremock = "0.6"
# The HTTP client for the surface tests, SSE bodies included # The HTTP client for the surface tests, SSE bodies included
reqwest = { version = "0.12", features = ["json", "stream"] } reqwest = { version = "0.13", features = ["json", "stream"] }
# Naming the SSE chunks' type in the surface tests # Naming the SSE chunks' type in the surface tests
bytes = "1" bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock # The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer # feature without a feature of our own — tests are the only consumer
rhema-core = { path = "../rhema-core", features = ["mock"] } rhema-core = { version = "0.4.2", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints] [lints]
+2 -1
View File
@@ -8,7 +8,8 @@ questions, spread across turns.
Write SOUL.md (your name, tone, purpose) and USER.md (who the user Write SOUL.md (your name, tone, purpose) and USER.md (who the user
is) with the bootstrap_save tool as facts arrive; incrementally is is) with the bootstrap_save tool as facts arrive; incrementally is
fine. Set what you learn about your own presentation with the fine. Set what you learn about your own presentation with the
identity_set tool as well — your name, a mark or initials, a tagline. identity_set tool as well — your name, a mark or initials, a tagline, an
email to commit as.
An avatar only if the user hands you an image file; they can also An avatar only if the user hands you an image file; they can also
upload one in the web interface's settings, and saying so beats upload one in the web interface's settings, and saying so beats
hunting one down. Never invent facts the user did not give. hunting one down. Never invent facts the user did not give.
+81 -21
View File
@@ -69,6 +69,12 @@ listen: 127.0.0.1:7799
token: change-me # optional; when set, /v1/* requires it token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools) 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 tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: ssh # local (default), http, or ssh
host: me@box.example # the ssh destination: an alias or user@host
workspace: /srv/claw # ssh only: the workspace base, default /root
# http instead speaks the sandbox protocol (rhema-sandboxd):
# kind: http, url: https://box.example:7600, token: sandbox-secret
poll_interval_secs: 120 poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty watches: # a seed: imported while the table is empty
@@ -96,6 +102,19 @@ 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 a work timer — a turn that hits it ends with a failed outcome and the
conversation intact; a follow-up message keeps going. 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`. `kind: ssh` runs commands on a login the local `ssh`
config resolves (`host`, any alias or `user@host`), nothing installed
on the far end; `workspace` names the remote directory the claw's
workspaces live under, `/root` by default, one directory per claw
workspace under it. 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 root. Later edits stay there; the claw does not copy them
back.
The surface refuses to start on a non-loopback `listen` with no The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer `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 token is what stands between it and the agent's tools. Set a token, or
@@ -123,10 +142,13 @@ The native surface:
``` ```
GET /healthz GET /v1/sessions GET /healthz GET /v1/sessions
POST /v1/sessions {"name"} — create an empty interactive session 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}/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> 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 DELETE /v1/sessions/{key} drop a session and its turn history
POST /v1/sessions/{key}/pause hold the key's dispatch; queued work waits
POST /v1/sessions/{key}/resume lift the hold
POST /v1/sessions/{key}/abort cut the live turn, or drop the queued work
GET /v1/watches POST /v1/watches DELETE /v1/watches/{forge}/{repo} GET /v1/watches POST /v1/watches DELETE /v1/watches/{forge}/{repo}
GET /v1/bootstrap {"soul": bool, "user": bool} GET /v1/bootstrap {"soul": bool, "user": bool}
POST /v1/ingest {"source","key","payload"} -> 202 POST /v1/ingest {"source","key","payload"} -> 202
@@ -137,6 +159,8 @@ DELETE /v1/consents/{id} deny a pending ask
GET /v1/attachments/{id} an attached file's bytes GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report 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"?,"host"?,"workspace"?}, switch and persist
GET /v1/providers the backend instances + the active pair GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted PUT /v1/providers/{id}/credentials add or replace an instance, persisted
@@ -169,7 +193,10 @@ lets a UI badge setup state.
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`, SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`, `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 reload and a daemon restart rebuild the transcript, and a session that
runs for weeks keeps all of it. runs for weeks keeps all of it.
@@ -177,14 +204,26 @@ The seq is the record's dense per-key number for the event, and it is
the client's cursor. A subscription opens with a replay cut atomically the client's cursor. A subscription opens with a replay cut atomically
against the live feed, and the frames of both carry their seqs, so a against the live feed, and the frames of both carry their seqs, so a
client that reconnects sends `?since=<last seq it saw>` and receives client that reconnects sends `?since=<last seq it saw>` and receives
exactly the gap. With no cursor the replay is the tail — the newest 400 exactly the gap. With no cursor the replay is the tail: the newest 400
events, cut back to the first turn boundary in them — so a weeks-old events, cut back to the first turn boundary in them. The window widens
session paints its latest turn at once instead of replaying everything; by doubling while it sits inside one turn, because a long agent turn
the turns above it come from the history route, one whole turn per streams hundreds of deltas and a reload that opened mid-reply would
page, each ending exactly where the previous page began. A cursor the drop what the turn began with. A weeks-old session thus paints its
latest turn at once instead of replaying everything, and the turns
above it come from the history route, one whole turn per page, each
ending exactly where the previous page began. A cursor the
record can no longer serve (a wiped table) answers with a `reset;` record can no longer serve (a wiped table) answers with a `reset;`
comment and the tail, and the client rebuilds rather than splice. comment and the tail, and the client rebuilds rather than splice.
The history route answers for every key in the inventory, not only the
resident prefixes. A key outside them — a forge thread, a finished
coding job — has no turn record to subscribe to, but the engine
checkpoints its session after every step. The route reads that stash
back as the same event shapes, cut into the same pages, and marks the
response `read_only: true`: the transcript a client can render, with no
stream to follow and no message the daemon would take. A key with no
stash yet answers an empty page.
A chat UI subscribes once, POSTs messages, and resets its mirror A chat UI subscribes once, POSTs messages, and resets its mirror
whenever the stream (re)opens, letting the replay rebuild it; the daemon whenever the stream (re)opens, letting the replay rebuild it; the daemon
owns the conversation, so the client mirrors the stream rather than owns the conversation, so the client mirrors the stream rather than
@@ -244,7 +283,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 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 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 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 — command in the session workspace with the secret injected —
`ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/ `ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/
`GITLAB_TOKEN`, and a git credential helper — so `git clone` and API `GITLAB_TOKEN`, and a git credential helper — so `git clone` and API
@@ -305,19 +358,26 @@ same host serves both: the browser gets the web UI on `/`, the daemon
answers `/v1` and `/healthz`; one address for the browser and the answers `/v1` and `/healthz`; one address for the browser and the
phone app, no CORS anywhere. phone app, no CORS anywhere.
The image is the daemon plus `bash` and `git` (the agent's shell is The image is the daemon plus what the agent's shell needs: `bash` and
load-bearing); the chart runs exactly one replica, the claw is `git` (the shell is load-bearing, the agent clones in its workspaces),
single-node by design: one SQLite store, one dispatcher. Single-node `curl` for a turn that fetches a URL, and `gob` for a command that
is what makes restarts instant: at boot the daemon releases every outlives the turn. The agent starts a build or a dev server with `gob
lease the previous process left — outright, not at the dead lease's add` and reads its logs and ports on a later one. The chart runs
TTL — so a turn an update cut mid-flight answers its next message exactly one replica, the claw is single-node by design: one SQLite
instead of stalling behind a ghost (the committed tool call revives store, one dispatcher. Single-node is what makes restarts instant: at
at the top of that next dispatch). The boot the daemon releases every lease the previous process left —
store and workspaces live on a PVC, `claw.yaml` in a ConfigMap (db and outright, not at the dead lease's TTL — so a turn an update cut
workspace paths are pinned to the mounted volume), credentials in a mid-flight answers its next message instead of stalling behind a ghost
Secret, and the bearer token is the `token` value, required since the (the committed tool call revives at the top of that next dispatch). The
daemon binds all interfaces in-cluster. `persistence.enabled=false` cut turn is released as superseded on the way, so a thread it never
trades restart survival for disposability. finished reads as aborted instead of wearing the outcome of the turn
before it. Nothing re-runs it: the mention was drained before the turn
ran, and the thread waits for the next activity.
The store and workspaces live on a PVC, `claw.yaml` in a ConfigMap (db
and workspace paths are pinned to the mounted volume), credentials in
a Secret, and the bearer token is the `token` value, required since
the daemon binds all interfaces in-cluster.
`persistence.enabled=false` trades restart survival for disposability.
The UI in `web/claw` is one client of the same surface: `npm run dev` The UI in `web/claw` is one client of the same surface: `npm run dev`
proxies to a local claw, `npm run build` emits the static bundle an proxies to a local claw, `npm run build` emits the static bundle an
+32 -3
View File
@@ -1,8 +1,15 @@
You are the resident agent on this machine. This session's key is {{ session }}. You are the resident agent on this machine. This session's key is {{ session }}.
You answer chat here. Your shell runs in the workspace at {{ workspace }}. Your shell runs in the workspace at {{ workspace }}.
Keep replies concrete. Do the work with tools instead of narrating it. Keep replies concrete. Do the work with tools instead of narrating it.
Your final message, the one you end the turn on with no tool calls after {% if surface == 'forge' %}
it, is the reply the user sees. You answer forge threads — review requests, assignments, and mentions on
the repositories you watch. Your final message, the one you end the turn
on with no tool calls after it, is the comment posted to the thread
verbatim.
{% else %}
You answer chat here. Your final message, the one you end the turn on
with no tool calls after it, is the reply the user sees.
{% endif %}
## Soul ## Soul
@@ -36,6 +43,27 @@ what it is for. The arguments are the JSON schema a call must satisfy.
{{ vision }} {{ vision }}
{% endif %} {% endif %}
{% if mcp %}
## MCP servers
Available MCP servers:
{% for server in mcp %}- {{ server.name }} (server: {{ server.server }}): {{ server.description }}
{% endfor %}
MCP servers are reachable through bash commands (**not** direct tool calls).
Usage:
{{ mcp[0].name }} --help # a server's tools
{{ mcp[0].name }} <tool> --help # one tool's arguments
{{ mcp[0].name }} <tool> --schema # one tool's exact input JSON
{{ mcp[0].name }} --flag value # a call; --prop_json for nested values
{{ mcp[0].name }} --json - <<'EOF' ... EOF # nested payloads: heredoc, no quoting
mcp servers | mcp tools <server> | mcp call <server> <tool> <json>
{% endif %}
{% if memory %}
## Memory ## Memory
You keep persistent memory across sessions. memory_save stores what is You keep persistent memory across sessions. memory_save stores what is
@@ -43,6 +71,7 @@ worth remembering: decisions, conventions, corrections, pointers.
memory_search recalls it; search before asking the user for something memory_search recalls it; search before asking the user for something
they have likely said before. memory_forget removes a record on they have likely said before. memory_forget removes a record on
request. Never save secrets into memory. request. Never save secrets into memory.
{% endif %}
{% if onboarding %} {% if onboarding %}
{{ onboarding }} {{ onboarding }}
+175
View File
@@ -0,0 +1,175 @@
//! The abort registry: a running turn the operator cut — the kill that
//! pairs with the pause gate ([`crate::pause`]).
//!
//! Pause holds what has not started; abort stops what has. A live turn
//! is minutes of tool rounds deep in a dispatch nobody watches, and the
//! only thing that can end it early is the dispatch itself: the turn's
//! own future, dropped at its current await — a streaming request, or a
//! running shell command, whose child dies with the drop. So each
//! handler holds a listener for its key across the dispatch (the lease
//! guarantees at most one dispatch per key, so entries never collide),
//! and the abort route signals through this registry; the handler
//! repairs the dangling calls, stashes what the turn committed, and
//! releases the lease as superseded.
//!
//! The mechanics are [`crate::steer`]'s — the same per-key channel, the
//! same signal-after-ingest ordering logic — with a different contract
//! on the far side: a steer signal loops the dispatch onto its next
//! round, an abort signal ends it. Signalling a key with no live
//! dispatch is a no-op (`false`), which makes the route's call
//! unconditional: the route's own idle path drains whatever is queued,
//! and the signal covers only the turn that runs.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use tokio::sync::mpsc;
/// The per-key abort registry. The daemon builds one and shares it with
/// the HTTP surface; every handler listens on it.
#[derive(Default)]
pub struct AbortRegistry {
/// One sender per key with a dispatch in flight; the guard's `Drop`
/// removes its own.
live: Mutex<HashMap<String, mpsc::Sender<()>>>,
}
impl AbortRegistry {
/// An empty registry.
pub fn new() -> Self {
Self::default()
}
/// Aborts the live dispatch on `key`, if there is one. `true` when a
/// listener took the signal; `false` when no dispatch runs (or its
/// channel is already full — one pending abort is enough; the turn
/// ends either way).
pub fn signal(&self, key: &str) -> bool {
let listener = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(key)
.cloned();
match listener {
Some(sender) => sender.try_send(()).is_ok(),
None => false,
}
}
/// Arms a listener for `key`. The guard is the dispatch's side: hold
/// it across the whole dispatch chain, drop it to unregister.
pub fn listen(self: &Arc<Self>, key: &str) -> AbortGuard {
let (sender, receiver) = mpsc::channel(1);
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned(), sender.clone());
AbortGuard {
registry: Arc::clone(self),
key: key.to_owned(),
sender,
receiver: Some(receiver),
}
}
}
/// One dispatch's listener: the receiver the select waits on, plus
/// enough identity to unregister only its own entry. The receiver sits
/// in an `Option` because `recv` consumes it; the borrow hands it back
/// after every await, so the guard stays the one object the dispatch
/// carries from round to round.
pub struct AbortGuard {
registry: Arc<AbortRegistry>,
key: String,
/// The guard's own sender, kept only so `Drop` can tell its entry
/// from a later dispatch's.
sender: mpsc::Sender<()>,
receiver: Option<mpsc::Receiver<()>>,
}
impl AbortGuard {
/// Whether an abort is pending. The dispatch checks this between
/// rounds: an abort carries no inbox message of its own, so unlike
/// steer's stale-signal clear, a pending abort here is honored, not
/// dropped.
pub fn take(&mut self) -> bool {
match self.receiver.as_mut() {
Some(receiver) => receiver.try_recv().is_ok(),
None => false,
}
}
/// Resolves once an abort arrives. A closed channel — impossible
/// while this guard lives, since its own sender sits in the
/// registry — parks forever rather than resolving empty, so the
/// select's abort arm goes silent instead of spinning.
pub async fn wait(&mut self) {
loop {
let received = match self.receiver.as_mut() {
Some(receiver) => receiver.recv().await,
None => std::future::pending::<Option<()>>().await,
};
if received.is_some() {
return;
}
}
}
}
impl Drop for AbortGuard {
fn drop(&mut self) {
// Only remove the entry this guard inserted: a same-key entry
// from a later dispatch must survive (it cannot coexist with a
// live one — the lease forbids it — but a defensive check keeps
// the registry honest regardless of caller discipline).
let mut live = self
.registry
.live
.lock()
.unwrap_or_else(PoisonError::into_inner);
if live
.get(&self.key)
.is_some_and(|entry| entry.same_channel(&self.sender))
{
live.remove(&self.key);
}
self.receiver = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_signal_with_no_listener_is_a_no_op() {
let registry = Arc::new(AbortRegistry::new());
assert!(!registry.signal("job:rhema#7"));
}
#[tokio::test]
async fn a_listener_takes_the_signal_and_unregisters_on_drop() {
let registry = Arc::new(AbortRegistry::new());
let mut guard = registry.listen("job:rhema#7");
assert!(registry.signal("job:rhema#7"));
guard.wait().await;
// A second signal fills the capacity-one channel and reports as
// not taken — one pending abort is enough.
assert!(registry.signal("job:rhema#7"));
assert!(!registry.signal("job:rhema#7"));
assert!(guard.take());
drop(guard);
assert!(!registry.signal("job:rhema#7"), "the entry is gone");
}
#[test]
fn keys_abort_independently() {
let registry = Arc::new(AbortRegistry::new());
let _guard = registry.listen("job:rhema#7");
assert!(!registry.signal("job:rhema#8"));
assert!(registry.signal("job:rhema#7"));
}
}
+8 -10
View File
@@ -29,7 +29,8 @@ use std::process::Stdio;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_core::{ToolCall, ToolContext, ToolResolver, ToolResult, ToolSpec}; use rhema_core::{ToolCall, ToolContext, ToolResolver, ToolResult, ToolSpec};
use rhema_identity::{Account, AccountDraft, IdentityStore, Secret, SecretKind}; use rhema_identity::{Account, AccountDraft, IdentityStore, Secret, SecretKind};
use serde::Deserialize; use serde::Deserialize;
@@ -283,8 +284,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// The identity tool set over the account store and the watch table — /// The identity tool set over the account store and the watch table —
/// specs from the embedded manifests, operations compiled here. /// specs from the embedded manifests, operations compiled here.
pub fn registry(accounts: Arc<dyn IdentityStore>, watches: Arc<ClawStore>) -> ToolRegistry { pub fn registry(accounts: Arc<dyn IdentityStore>, watches: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(accounts, watches));
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the identity tool manifests must all load: {skipped:?}" "the identity tool manifests must all load: {skipped:?}"
@@ -582,7 +582,7 @@ impl ToolResolver for IdentityExec {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rhema_autonomous_agent::ToolOp; use crate::toolkit::ToolOp;
fn parts() -> (Arc<dyn IdentityStore>, Arc<ClawStore>) { fn parts() -> (Arc<dyn IdentityStore>, Arc<ClawStore>) {
( (
@@ -598,15 +598,13 @@ mod tests {
#[test] #[test]
fn every_manifest_loads_against_its_builtin_and_serves_the_registry() { fn every_manifest_loads_against_its_builtin_and_serves_the_registry() {
let (accounts, watches) = parts(); let (accounts, watches) = parts();
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools( let (tools, skipped) =
MANIFESTS, crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
&builtins(accounts, watches),
);
assert!(skipped.is_empty(), "{skipped:?}"); assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 3); assert_eq!(tools.len(), 3);
let (accounts, watches) = parts(); let (accounts, watches) = parts();
let resolver = registry(accounts, watches) let resolver =
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive()); registry(accounts, watches).resolver_for(&crate::toolkit::Allowlist::permissive());
assert_eq!( assert_eq!(
resolver.replay_safety("identity_list"), resolver.replay_safety("identity_list"),
rhema_core::ReplaySafety::Safe rhema_core::ReplaySafety::Safe
+5 -6
View File
@@ -17,7 +17,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -309,10 +310,8 @@ pub fn registry(
hub: Arc<EventHub>, hub: Arc<EventHub>,
key: ResourceKey, key: ResourceKey,
) -> ToolRegistry { ) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools( let (tools, skipped) =
MANIFESTS, crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into(), hub, key));
&builtins(store, workspace.into(), hub, key),
);
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the attach_file tool manifest must load: {skipped:?}" "the attach_file tool manifest must load: {skipped:?}"
@@ -327,7 +326,7 @@ pub fn registry(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rhema_autonomous_agent::Allowlist; use crate::toolkit::Allowlist;
#[test] #[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() { fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+149 -11
View File
@@ -26,9 +26,10 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use rhema_agent_tools::render_template; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use async_trait::async_trait;
use rhema_core::ToolSpec; use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json}; use serde_json::{Value, json};
/// The built-in system prompt, kept as data next to the code and read /// The built-in system prompt, kept as data next to the code and read
@@ -197,15 +198,32 @@ fn section(header: &str, content: Option<&str>, stub: &str) -> String {
format!("{header}\n\n{}", content.unwrap_or(stub)) format!("{header}\n\n{}", content.unwrap_or(stub))
} }
/// Which surface a dispatch answers on: the template's opening and
/// reply contract differ — a chat reply goes to the user, a forge
/// reply goes to the thread — and onboarding is a chat offer only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Surface {
/// The chat surfaces: interactive sessions, tasks, phone, reminders.
Chat,
/// A forge thread dispatch: a watch event answered on the forge.
Forge,
}
/// Renders the system prompt for one dispatch through the agent /// Renders the system prompt for one dispatch through the agent
/// toolkit's Jinja renderer: `{{ workspace }}` and the three file /// toolkit's Jinja renderer: `{{ workspace }}` and the three file
/// sections from the live store, `tools` from the dispatch's own /// sections from the live store, `tools` from the dispatch's own
/// resolver specs, `{{ session }}` — the dispatching key, the address /// resolver specs, `{{ session }}` — the dispatching key, the address
/// the model schedules its own wakes to — and `onboarding`, the offer /// the model schedules its own wakes to — and `onboarding`, the offer
/// the template's `{% if %}` shows only while a file is unwritten. /// the template's `{% if %}` shows only while a file is unwritten, and
/// Fallible on purpose — a store that cannot be read surfaces loudly /// only on a chat surface: a forge dispatch is nobody's first
/// instead of rendering a prompt without it, and a template that /// conversation. `mcp` renders the wired servers' section, empty on a
/// cannot render fails the dispatch before any model call. /// surface with none; the memory section renders only when the roster
/// actually carries the memory tools, so a forge prompt never
/// documents tools it does not have. Fallible on purpose — a store
/// that cannot be read surfaces loudly instead of rendering a prompt
/// without it, and a template that cannot render fails the dispatch
/// before any model call.
#[expect(clippy::too_many_arguments, reason = "eight parts, each load-bearing")]
pub fn render_system( pub fn render_system(
template: &str, template: &str,
session: &str, session: &str,
@@ -213,15 +231,18 @@ pub fn render_system(
bootstrap: &Bootstrap, bootstrap: &Bootstrap,
tools: &[ToolSpec], tools: &[ToolSpec],
vision: Option<&str>, vision: Option<&str>,
mcp: &[rhema_config::mcp::McpServerLine],
surface: Surface,
) -> Result<String, BootstrapError> { ) -> Result<String, BootstrapError> {
let soul = bootstrap.load(BootstrapKind::Soul)?; let soul = bootstrap.load(BootstrapKind::Soul)?;
let user = bootstrap.load(BootstrapKind::User)?; let user = bootstrap.load(BootstrapKind::User)?;
let environment = bootstrap.load(BootstrapKind::Environment)?; let environment = bootstrap.load(BootstrapKind::Environment)?;
let onboarding = if soul.is_none() || user.is_none() { let onboarding = if surface == Surface::Chat && (soul.is_none() || user.is_none()) {
ONBOARDING_MD ONBOARDING_MD
} else { } else {
"" ""
}; };
let memory = tools.iter().any(|spec| spec.name == "memory_save");
let context = json!({ let context = json!({
"session": session, "session": session,
"workspace": workspace.display().to_string(), "workspace": workspace.display().to_string(),
@@ -231,6 +252,12 @@ pub fn render_system(
"onboarding": onboarding, "onboarding": onboarding,
"tools": tools, "tools": tools,
"vision": vision, "vision": vision,
"mcp": mcp,
"memory": memory,
"surface": match surface {
Surface::Chat => "chat",
Surface::Forge => "forge",
},
}); });
render_template(template, &context).map_err(|err| { render_template(template, &context).map_err(|err| {
let line = err let line = err
@@ -286,8 +313,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// interactive resolver chain composes — its spec from the embedded /// interactive resolver chain composes — its spec from the embedded
/// manifest, the operation compiled here. /// manifest, the operation compiled here.
pub fn registry(bootstrap: Arc<Bootstrap>) -> ToolRegistry { pub fn registry(bootstrap: Arc<Bootstrap>) -> ToolRegistry {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(bootstrap));
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the bootstrap tool manifest must load: {skipped:?}" "the bootstrap tool manifest must load: {skipped:?}"
@@ -418,7 +444,7 @@ mod tests {
let tools = registry(Arc::new(Bootstrap { let tools = registry(Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(), root: bootstrap.root().to_path_buf(),
})) }))
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive()) .resolver_for(&crate::toolkit::Allowlist::permissive())
.specs(); .specs();
let prompt = render_system( let prompt = render_system(
DEFAULT_SYSTEM_MD, DEFAULT_SYSTEM_MD,
@@ -427,6 +453,8 @@ mod tests {
&bootstrap, &bootstrap,
&tools, &tools,
None, None,
&[],
Surface::Chat,
) )
.expect("renders"); .expect("renders");
assert!(prompt.contains("## SOUL"), "{prompt}"); assert!(prompt.contains("## SOUL"), "{prompt}");
@@ -439,6 +467,110 @@ mod tests {
assert!(prompt.contains("bootstrap_save"), "{prompt}"); assert!(prompt.contains("bootstrap_save"), "{prompt}");
} }
#[test]
fn a_fresh_house_on_the_forge_surface_never_carries_the_onboarding() {
let (_dir, bootstrap) = store();
let prompt = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
Path::new("/ws"),
&bootstrap,
&[],
None,
&[],
Surface::Forge,
)
.expect("renders");
assert!(
!prompt.contains("## Onboarding"),
"a forge thread is nobody's first conversation: {prompt}"
);
assert!(
prompt.contains("the comment posted to the thread"),
"the forge branch of the reply contract: {prompt}"
);
assert!(
!prompt.contains("You answer chat here"),
"not the chat branch: {prompt}"
);
assert_eq!(prompt.matches(PENDING).count(), 2, "{prompt}");
}
#[test]
fn the_memory_section_renders_only_when_the_roster_carries_the_tools() {
let (_dir, bootstrap) = store();
let memory = [ToolSpec::new(
"memory_save",
"stores a record",
json!({"type": "object"}),
)];
let with = render_system(
DEFAULT_SYSTEM_MD,
"interactive:web",
Path::new("/ws"),
&bootstrap,
&memory,
None,
&[],
Surface::Chat,
)
.expect("renders");
let without = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
Path::new("/ws"),
&bootstrap,
&[],
None,
&[],
Surface::Forge,
)
.expect("renders");
assert!(with.contains("## Memory"), "{with}");
assert!(
!without.contains("## Memory"),
"no memory tools, no memory section: {without}"
);
}
#[test]
fn the_wired_mcp_servers_render_their_section() {
let (_dir, bootstrap) = store();
let mcp = [rhema_config::mcp::McpServerLine {
name: "acme-mcp".to_owned(),
server: "acme".to_owned(),
description: "the acme tools".to_owned(),
}];
let prompt = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
Path::new("/ws"),
&bootstrap,
&[],
None,
&mcp,
Surface::Forge,
)
.expect("renders");
assert!(prompt.contains("## MCP servers"), "{prompt}");
assert!(
prompt.contains("- acme-mcp (server: acme): the acme tools"),
"{prompt}"
);
let bare = render_system(
DEFAULT_SYSTEM_MD,
"interactive:web",
Path::new("/ws"),
&bootstrap,
&[],
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(!bare.contains("## MCP servers"), "{bare}");
}
#[test] #[test]
fn the_full_house_renders_each_file_and_drops_the_onboarding_section() { fn the_full_house_renders_each_file_and_drops_the_onboarding_section() {
let (_dir, bootstrap) = store(); let (_dir, bootstrap) = store();
@@ -456,6 +588,8 @@ mod tests {
&bootstrap, &bootstrap,
&[], &[],
None, None,
&[],
Surface::Chat,
) )
.expect("renders"); .expect("renders");
assert!( assert!(
@@ -484,6 +618,8 @@ mod tests {
&bootstrap, &bootstrap,
&[], &[],
None, None,
&[],
Surface::Chat,
) )
.expect("renders"); .expect("renders");
assert!(prompt.contains(content), "{prompt}"); assert!(prompt.contains(content), "{prompt}");
@@ -516,6 +652,8 @@ mod tests {
&bootstrap, &bootstrap,
&tools, &tools,
None, None,
&[],
Surface::Chat,
) )
.expect("renders"); .expect("renders");
assert!(prompt.contains("- my_tool | {"), "{prompt}"); assert!(prompt.contains("- my_tool | {"), "{prompt}");
@@ -528,7 +666,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn the_tool_writes_through_the_store_and_answers_one_line() { async fn the_tool_writes_through_the_store_and_answers_one_line() {
use rhema_autonomous_agent::Allowlist; use crate::toolkit::Allowlist;
use rhema_core::{ToolCall, ToolContext}; use rhema_core::{ToolCall, ToolContext};
let (_dir, bootstrap) = store(); let (_dir, bootstrap) = store();
+145 -6
View File
@@ -13,6 +13,7 @@
//! binary's startup, not here — the daemon library takes the built //! binary's startup, not here — the daemon library takes the built
//! provider, so tests can inject a mock. //! provider, so tests can inject a mock.
use std::num::NonZeroU32;
use std::path::PathBuf; use std::path::PathBuf;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -22,10 +23,13 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60; pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60;
/// How many tool rounds one chat turn may run, when /// How many tool rounds one chat turn may run, when
/// [`ClawConfig::max_turn_steps`] is unset — the coding driver's own /// [`ClawConfig::max_turn_steps`] is unset — the host agent driver's
/// budget shape and its default: deep enough that a cap is a runaway /// own budget shape and its default: deep enough that a cap is a
/// guard for an agent meant to work unattended, not a work timer. /// runaway guard for an agent meant to work unattended, not a work
pub const DEFAULT_MAX_TURN_STEPS: u32 = 2048; /// 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: /// Where the HTTP surface listens when [`ClawConfig::listen`] is unset:
/// loopback only — the surface is for the machine's resident user. /// 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" "agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
)] )]
SameAgentToken, 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 ingest credential is the same value as the human token or
/// the agent token: boot refuses, because the ingest credential's /// the agent token: boot refuses, because the ingest credential's
/// safety is that it is write-only and the event door only — a /// 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 /// How many tool rounds one chat turn may run before it is cut off
/// with a failed outcome, the conversation intact. A follow-up /// with a failed outcome, the conversation intact. A follow-up
/// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset. /// 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`, /// The handler's model backend: `google`, `llama-cpp`, `openrouter`,
/// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve /// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve
/// through the stored rhema config's default profile, env vars /// through the stored rhema config's default profile, env vars
@@ -171,6 +178,33 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still /// Unset closes the door to credentials; the human token can still
/// ingest. /// ingest.
pub ingest_token: Option<String>, pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, a
/// `rhema-sandboxd` over HTTP, or an ssh login on a far box (`kind:
/// ssh`, a `host` destination, and optionally the `private_key`
/// text itself, not a path, the credential stays in this file or
/// the store that holds it). The settings store owns the live
/// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>,
/// The git identity the daemon writes into its user's global git
/// config at boot, so workspace commits carry the agent as author.
/// A field set here wins over the agent's identity (what
/// onboarding and the settings page write); both win over
/// defaults. See [`crate::git_identity`].
pub git: Option<GitIdentity>,
}
/// One git identity as the config states it: both fields optional, a
/// set field winning over the identity store, an unset one falling
/// through.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct GitIdentity {
/// The commit author name.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The commit author address.
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
} }
impl ClawConfig { impl ClawConfig {
@@ -198,6 +232,8 @@ impl Default for ClawConfig {
tools_bin: None, tools_bin: None,
ingest_token: None, ingest_token: None,
transcript: None, transcript: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
@@ -326,6 +362,12 @@ impl ClawConfig {
{ {
return Err(ConfigError::IngestTokenCollision); return Err(ConfigError::IngestTokenCollision);
} }
if let Some(sandbox) = &self.sandbox {
sandbox
.clone()
.normalized()
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
}
Ok(()) Ok(())
} }
} }
@@ -422,10 +464,17 @@ model: claude-sonnet-4-5
listen: 192.168.1.10:7800 listen: 192.168.1.10:7800
token: sekrit token: sekrit
ingest_token: door-key ingest_token: door-key
sandbox:
kind: http
url: https://box.example:7600
token: sandbox-secret
git:
name: Bot
email: bot@example.net
"; ";
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses"); let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
assert_eq!(config.poll_interval_secs, 30); 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.provider.as_deref(), Some("anthropic"));
assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5")); assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5"));
assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800")); assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800"));
@@ -438,6 +487,96 @@ ingest_token: door-key
config.bootstrap_root.as_deref(), config.bootstrap_root.as_deref(),
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap")) 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"));
let git = config.git.expect("the git identity parses");
assert_eq!(git.name.as_deref(), Some("Bot"));
assert_eq!(git.email.as_deref(), Some("bot@example.net"));
let config: ClawConfig = serde_yaml::from_str(
"sandbox:\n kind: ssh\n host: me@box.example\n workspace: /srv/claw\n",
)
.expect("the ssh sandbox parses");
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Ssh);
assert_eq!(sandbox.host.as_deref(), Some("me@box.example"));
assert_eq!(sandbox.workspace.as_deref(), Some("/srv/claw"));
}
#[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,
..crate::sandbox::SandboxChoice::default()
}),
..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()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
fn an_ssh_sandbox_needs_a_host_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"an ssh sandbox without a host is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
host: Some("me@box.example".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a bare login is all ssh needs");
}
#[test]
fn the_git_section_rejects_a_typo_and_carries_partial_identity() {
let err = serde_yaml::from_str::<ClawConfig>(
"git:
nmae: Bot
",
)
.expect_err("a typo inside the section must not read as its default");
assert!(
err.to_string().contains("nmae"),
"the error names the key: {err}"
);
// One field alone is legal: the other falls through to the
// identity store, then defaults.
let config: ClawConfig = serde_yaml::from_str(
"git:
email: bot@example.net
",
)
.expect("parses");
let git = config.git.expect("the section parses");
assert_eq!(git.email.as_deref(), Some("bot@example.net"));
assert_eq!(git.name, None);
} }
#[test] #[test]
+5 -6
View File
@@ -21,7 +21,8 @@ use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration; use std::time::Duration;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rusqlite::params; use rusqlite::params;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -509,10 +510,8 @@ pub fn registry(
hub: Arc<EventHub>, hub: Arc<EventHub>,
key: ResourceKey, key: ResourceKey,
) -> ToolRegistry { ) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools( let (tools, skipped) =
MANIFESTS, crate::toolkit::builtin_tools(MANIFESTS, &builtins(consents, bridge, hub, key));
&builtins(consents, bridge, hub, key),
);
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the ask_secret tool manifest must load: {skipped:?}" "the ask_secret tool manifest must load: {skipped:?}"
@@ -527,7 +526,7 @@ pub fn registry(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rhema_autonomous_agent::Allowlist; use crate::toolkit::Allowlist;
#[test] #[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() { fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+346 -36
View File
@@ -22,6 +22,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration; use std::time::Duration;
use rhema_autonomous_agent::{Driver, Source, SourceError}; use rhema_autonomous_agent::{Driver, Source, SourceError};
@@ -62,6 +63,9 @@ pub enum ClawError {
/// The runtime settings table could not be opened or read. /// The runtime settings table could not be opened or read.
#[error(transparent)] #[error(transparent)]
Settings(#[from] crate::settings::SettingsError), 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. /// The notification table could not be opened or read.
#[error(transparent)] #[error(transparent)]
Notifications(#[from] crate::notifications::NotificationStoreError), Notifications(#[from] crate::notifications::NotificationStoreError),
@@ -123,6 +127,83 @@ 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()
}
}
/// Hands one driver pass to its own task, so a turn does not stop the
/// clock.
///
/// [`Driver::run_once`] awaits every run it admits, which is exactly right
/// for a cron pass and wrong for a resident: a forge turn clones a repo
/// and may build a slicer, a coding job runs a session — tens of minutes
/// either way — and everything else the loop does (detecting, and so
/// polling the forges, recording watch health, firing due tasks, reading
/// the calendar, delivering to the phone) waits behind it. With a 60s
/// tick and a ten-minute turn, the daemon polls once per turn.
///
/// One pass per lane at a time. `busy` is held for the pass's whole
/// duration, and a tick that finds it held leaves its events where they
/// are: the dispatcher's inbox is the queue, so nothing is dropped — the
/// next tick admits them. Starting a second pass anyway would only lose
/// lease acquisitions to the first and log the loss.
fn spawn_pass(driver: Arc<Driver>, label: &'static str, busy: Arc<AtomicBool>) {
if busy.swap(true, Ordering::AcqRel) {
return;
}
let held = BusyFlag(busy);
tokio::spawn(async move {
// Dropped however this task ends, a panic included: a lane whose
// flag never cleared would never run again.
let _held = held;
match driver.run_once().await {
Ok(outcomes) => {
let handled = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Handled))
.count();
let failed = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Failed(_)))
.count();
if handled + failed > 0 {
eprintln!("[claw] {label} pass: {handled} handled, {failed} failed");
}
}
Err(err) => eprintln!("[claw] warning: {label} pass failed: {err}"),
}
});
}
/// Clears a lane's in-flight flag when its spawned pass ends.
struct BusyFlag(Arc<AtomicBool>);
impl Drop for BusyFlag {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
/// The resident daemon: the extension set's sources (the forge watches, /// The resident daemon: the extension set's sources (the forge watches,
/// the task scheduler, the coding jobs, the calendar reminders), the /// the task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface. /// three drivers, and the HTTP surface.
@@ -139,6 +220,10 @@ pub struct Daemon {
forge_driver: Arc<Driver>, forge_driver: Arc<Driver>,
interactive_driver: Arc<Driver>, interactive_driver: Arc<Driver>,
jobs_driver: Arc<Driver>, jobs_driver: Arc<Driver>,
/// Whether a forge pass is running off the tick (see [`spawn_pass`]).
forge_pass_busy: Arc<AtomicBool>,
/// Whether a jobs pass is running off the tick.
jobs_pass_busy: Arc<AtomicBool>,
poll_interval: Duration, poll_interval: Duration,
listen: String, listen: String,
http: ClawState, http: ClawState,
@@ -151,8 +236,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one /// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive /// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is /// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — the resident loop uses the /// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// defaults, `--once` zeroes the debounce. /// with `--once` zeroing the debounce.
pub fn build( pub fn build(
config: &ClawConfig, config: &ClawConfig,
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
@@ -225,6 +310,10 @@ impl Daemon {
// The forge handler resolves its watches through the table at // The forge handler resolves its watches through the table at
// dispatch time, so a watch added mid-run is answerable without a // dispatch time, so a watch added mid-run is answerable without a
// restart. // 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 // The client tools' connection, handed to the agent's shell as
// environment: the URL the surface answers on, the scoped // environment: the URL the surface answers on, the scoped
// agent token (the middleware keeps it to the contract's data // agent token (the middleware keeps it to the contract's data
@@ -252,25 +341,64 @@ impl Daemon {
format!("{}:{inherited}", tools_bin.display()), 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(),
);
// The bootstrap store, before both handlers: the chat renders
// its files per dispatch, and so does the forge one now — the
// persona is shared, the workspaces are not. The environment
// report lands in the store's directory at boot, below.
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
// The pause gate: the keys the drivers hold, loaded from the
// settings table, shared with the HTTP surface's pause route.
let pause = Arc::new(crate::pause::PauseSet::load(settings.clone())?);
// The abort registry: the per-key cut the handlers listen on,
// shared with the HTTP surface's abort route.
let abort = Arc::new(crate::abort::AbortRegistry::new());
let forge_handler = ClawHandler::new( let forge_handler = ClawHandler::new(
backends.clone(), backends.clone(),
workspace_root, workspace_root,
watches.clone(), watches.clone(),
accounts.clone(), accounts.clone(),
bootstrap.clone(),
config.transcript_enabled(), config.transcript_enabled(),
tool_env.clone(), tool_env.clone(),
); )
.with_sandbox(sandbox.clone())
.with_abort(abort.clone());
// Three drivers over one store admit from the same table, so // Three drivers over one store admit from the same table, so
// each owns its slice of the key space: a forge pass must never // 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 // pick up a resident or job event (it would fail it, and
// consume it), and the others likewise. // consume it), and the others likewise. Paused keys belong to
// no driver: every predicate declines them, pass after pass,
// until resume lifts the hold.
let forge_driver = Arc::new( let forge_driver = Arc::new(
Driver::new(forge_dispatcher.clone(), Arc::new(forge_handler)) Driver::new(forge_dispatcher.clone(), Arc::new(forge_handler))
.with_holder("rhema-claw") .with_holder("rhema-claw")
.owning(Arc::new(|key: &ResourceKey| { .owning({
!crate::interactive::is_resident_key(key.as_str()) let pause = pause.clone();
&& !crate::jobs::is_job_key(key.as_str()) Arc::new(move |key: &ResourceKey| {
})), !crate::interactive::is_resident_key(key.as_str())
&& !crate::jobs::is_job_key(key.as_str())
&& !pause.is_paused(key.as_str())
})
}),
); );
// The consent table and its wake bridge: the `ask_secret` tool // The consent table and its wake bridge: the `ask_secret` tool
@@ -291,8 +419,6 @@ impl Daemon {
// `phone` tool queues behind a consent. // `phone` tool queues behind a consent.
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?); let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?); 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 // The identity store shares the settings table and keeps its
// images beside the database. // images beside the database.
let identity = Arc::new(crate::identity::IdentityStore::new( let identity = Arc::new(crate::identity::IdentityStore::new(
@@ -361,16 +487,22 @@ impl Daemon {
extensions.clone(), extensions.clone(),
config.transcript_enabled(), config.transcript_enabled(),
) )
.with_steer(steer.clone()); .with_steer(steer.clone())
.with_abort(abort.clone())
.with_sandbox(sandbox.clone());
let interactive_driver = Arc::new( let interactive_driver = Arc::new(
Driver::new( Driver::new(
interactive_dispatcher.clone(), interactive_dispatcher.clone(),
Arc::new(interactive_handler), Arc::new(interactive_handler),
) )
.with_holder("rhema-claw-interactive") .with_holder("rhema-claw-interactive")
.owning(Arc::new(|key: &ResourceKey| { .owning({
crate::interactive::is_resident_key(key.as_str()) let pause = pause.clone();
})), Arc::new(move |key: &ResourceKey| {
crate::interactive::is_resident_key(key.as_str())
&& !pause.is_paused(key.as_str())
})
}),
); );
// The coding jobs: one handler, one driver, one source. The // The coding jobs: one handler, one driver, one source. The
// final text of a job's turn notifies the user's device, so the // final text of a job's turn notifies the user's device, so the
@@ -381,13 +513,18 @@ impl Daemon {
notifications.clone(), notifications.clone(),
config.max_turn_steps, config.max_turn_steps,
config.transcript_enabled(), config.transcript_enabled(),
); )
.with_sandbox(sandbox.clone())
.with_abort(abort.clone());
let jobs_driver = Arc::new( let jobs_driver = Arc::new(
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler)) Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
.with_holder("rhema-claw-jobs") .with_holder("rhema-claw-jobs")
.owning(Arc::new(|key: &ResourceKey| { .owning({
crate::jobs::is_job_key(key.as_str()) let pause = pause.clone();
})), Arc::new(move |key: &ResourceKey| {
crate::jobs::is_job_key(key.as_str()) && !pause.is_paused(key.as_str())
})
}),
); );
crate::interactive::register_user(&interactive_dispatcher); crate::interactive::register_user(&interactive_dispatcher);
@@ -402,6 +539,9 @@ impl Daemon {
bootstrap, bootstrap,
hub, hub,
steer, steer,
pause,
abort,
jobs,
backends.clone(), backends.clone(),
settings.clone(), settings.clone(),
identity, identity,
@@ -410,6 +550,7 @@ impl Daemon {
bridge, bridge,
attachments, attachments,
phone, phone,
sandbox,
config.token.clone(), config.token.clone(),
config.agent_token.clone(), config.agent_token.clone(),
config.ingest_token.clone(), config.ingest_token.clone(),
@@ -424,6 +565,8 @@ impl Daemon {
forge_driver, forge_driver,
interactive_driver, interactive_driver,
jobs_driver, jobs_driver,
forge_pass_busy: Arc::new(AtomicBool::new(false)),
jobs_pass_busy: Arc::new(AtomicBool::new(false)),
// A zero poll interval would spin detect passes against the // A zero poll interval would spin detect passes against the
// forge API; one second is the floor. // forge API; one second is the floor.
poll_interval: Duration::from_secs(config.poll_interval_secs.max(1)), poll_interval: Duration::from_secs(config.poll_interval_secs.max(1)),
@@ -463,25 +606,52 @@ impl Daemon {
// is failed interrupted before anything re-runs, and a // is failed interrupted before anything re-runs, and a
// still-queued row is re-armed with a fresh dedup id. // still-queued row is re-armed with a fresh dedup id.
self.extensions.boot()?; self.extensions.boot()?;
// The leases still in the store name the turns this restart cut.
// The three dispatchers share one store, so one read sees them
// all. Read before the sweep forgets, recover, then release each
// one as superseded: a record keeps the outcome of its last
// release, so a cut turn would otherwise wear the previous
// turn's word, and the read-only transcript would print
// "handled" beside text the turn never finished.
let cut: Vec<ResourceKey> = self
.forge_dispatcher
.list_active()?
.into_iter()
// An empty inbox is the turn that had already drained its
// news, which is the one a restart strands. A key with items
// waiting re-acquires on its own and records its own outcome.
.filter(|status| status.inbox_depth == 0)
.map(|status| status.key)
.collect();
self.forge_dispatcher.recover_all()?; self.forge_dispatcher.recover_all()?;
self.jobs_dispatcher.recover_all()?; self.jobs_dispatcher.recover_all()?;
self.interactive_dispatcher.recover_all()?; self.interactive_dispatcher.recover_all()?;
for key in cut {
let acquired = self.forge_dispatcher.acquire(key.clone(), "claw-boot");
let lease = match acquired {
Ok((lease, _)) => lease,
Err(err) => {
eprintln!("[claw] warning: {key}: cut turn not marked aborted: {err}");
continue;
}
};
if let Err(err) = self.forge_dispatcher.release(&lease, Outcome::Superseded) {
eprintln!("[claw] warning: {key}: cut turn not marked aborted: {err}");
}
}
Ok(()) Ok(())
} }
/// One pass: every source detects (due tasks first — a reminder is /// One pass, awaited to the end: every source detects (due tasks
/// the user-facing clock), the forge driver runs every key the /// first — a reminder is the user-facing clock), the forge driver
/// debounce released, and the interactive driver drains as a /// runs every key the debounce released, and the interactive driver
/// backstop — a message delivered live into a running turn waits at /// drains as a backstop. The shape a `--once` run and the tests
/// the key for a pass like this one. /// drive, where "the pass is over" has to mean the work is over.
///
/// The resident loop uses [`Daemon::resident_tick`] instead: same
/// detection, but the long lanes are not awaited.
pub async fn tick(&self) -> Result<TickReport, ClawError> { pub async fn tick(&self) -> Result<TickReport, ClawError> {
// The tick only detects — every timer here drives let detected = self.detect().await?;
// deterministic detection, and the set's order is the contract:
// due tasks before the calendar reminders that fire for them.
let mut detected = 0usize;
for source in &self.sources {
detected += source.detect().await?;
}
// A queued coding job starts before the forge pass: it is the // A queued coding job starts before the forge pass: it is the
// thing someone just asked for. // thing someone just asked for.
if let Err(err) = self.jobs_driver.run_once().await { if let Err(err) = self.jobs_driver.run_once().await {
@@ -501,6 +671,50 @@ impl Daemon {
"[claw] pass: {detected} event(s) detected, {handled} handled, {failed} failed" "[claw] pass: {detected} event(s) detected, {handled} handled, {failed} failed"
); );
} }
self.drain_interactive().await;
Ok(TickReport { detected, outcomes })
}
/// The resident loop's pass: the same detection, with the two lanes
/// whose runs last minutes or hours handed to their own tasks.
///
/// Detection is the part that must keep its cadence — the forge polls
/// and the health rows they write, the due tasks, the calendar
/// reminders, the phone delivery all ride it — and detection alone is
/// quick. Awaiting a turn inside it means every one of those timers
/// stops for as long as the turn runs. See [`spawn_pass`].
pub async fn resident_tick(&self) -> Result<(), ClawError> {
self.detect().await?;
// A queued coding job starts before the forge pass: it is the
// thing someone just asked for.
spawn_pass(
self.jobs_driver.clone(),
"jobs",
self.jobs_pass_busy.clone(),
);
spawn_pass(
self.forge_driver.clone(),
"forge",
self.forge_pass_busy.clone(),
);
self.drain_interactive().await;
Ok(())
}
/// Detection only: every source, in set order. The tick's order is
/// the contract — due tasks before the calendar reminders that fire
/// for them — and the sources carry it.
async fn detect(&self) -> Result<usize, ClawError> {
let mut detected = 0usize;
for source in &self.sources {
detected += source.detect().await?;
}
Ok(detected)
}
/// The interactive driver, drained as a backstop: a message delivered
/// live into a running turn waits at the key for a pass like this one.
async fn drain_interactive(&self) {
match self.interactive_driver.run_once().await { match self.interactive_driver.run_once().await {
Ok(runs) if !runs.is_empty() => { Ok(runs) if !runs.is_empty() => {
eprintln!("[claw] interactive: {} queued run(s) drained", runs.len()); eprintln!("[claw] interactive: {} queued run(s) drained", runs.len());
@@ -508,13 +722,13 @@ impl Daemon {
Ok(_) => {} Ok(_) => {}
Err(err) => eprintln!("[claw] warning: interactive pass failed: {err}"), Err(err) => eprintln!("[claw] warning: interactive pass failed: {err}"),
} }
Ok(TickReport { detected, outcomes })
} }
/// The resident loop: the HTTP surface comes up first (a resident is /// The resident loop: the HTTP surface comes up first (a resident is
/// talked to), then detect, run, sleep, until ctrl-c. A failed pass /// talked to), then detect, hand the long lanes to their own tasks,
/// is logged, not fatal — a forge outage or a dead backend must not /// sleep, until ctrl-c. A failed pass is logged, not fatal — a forge
/// end a daemon whose next pass may simply succeed. /// outage or a dead backend must not end a daemon whose next pass may
/// simply succeed.
pub async fn run(&self) -> Result<(), ClawError> { pub async fn run(&self) -> Result<(), ClawError> {
self.bootstrap().await?; self.bootstrap().await?;
let listener = tokio::net::TcpListener::bind(&self.listen).await?; let listener = tokio::net::TcpListener::bind(&self.listen).await?;
@@ -527,7 +741,7 @@ impl Daemon {
}); });
eprintln!("[claw] http listening on {addr}"); eprintln!("[claw] http listening on {addr}");
loop { loop {
if let Err(err) = self.tick().await { if let Err(err) = self.resident_tick().await {
eprintln!("[claw] warning: pass failed: {err}"); eprintln!("[claw] warning: pass failed: {err}");
} }
tokio::select! { tokio::select! {
@@ -551,7 +765,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> { ) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig { let dispatch = DispatcherConfig {
debounce_window_millis: 0, debounce_window_millis: 0,
..DispatcherConfig::default() ..forge_dispatch()
}; };
let daemon = Daemon::build(config, backends, dispatch)?; let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?; daemon.bootstrap().await?;
@@ -562,6 +776,102 @@ pub async fn run_once(
mod tests { mod tests {
use super::*; use super::*;
/// A handler that holds its key until the test lets it go, and counts
/// the runs it served.
struct GatedHandler {
runs: std::sync::atomic::AtomicUsize,
started: tokio::sync::Semaphore,
release: tokio::sync::Semaphore,
}
#[rhema_autonomous_agent::async_trait]
impl rhema_autonomous_agent::Handler for GatedHandler {
async fn handle(&self, _ctx: &mut rhema_autonomous_agent::SessionContext) -> Outcome {
self.runs.fetch_add(1, Ordering::SeqCst);
self.started.add_permits(1);
let _ = self.release.acquire().await;
Outcome::Handled
}
}
/// A pass handed to its own task keeps the tick free, holds its lane
/// while it runs, and does not stack: a tick that fires mid-pass
/// leaves its events in the dispatcher's inbox for the next one.
#[tokio::test]
async fn a_spawned_pass_holds_its_lane_instead_of_stacking() {
let dispatcher = Arc::new(Dispatcher::new(
DispatcherConfig {
debounce_window_millis: 0,
..DispatcherConfig::default()
},
Arc::new(SystemClock),
Arc::new(rhema_rsd::VolatileStore::new()),
));
let handler = Arc::new(GatedHandler {
runs: std::sync::atomic::AtomicUsize::new(0),
started: tokio::sync::Semaphore::new(0),
release: tokio::sync::Semaphore::new(0),
});
// The dispatcher resolves an event's key through its source's key
// function; nothing ingests before its source is registered.
dispatcher.register_source(
"test",
Arc::new(|event: &rhema_rsd::Event| {
rhema_rsd::ResourceKey::from(format!("test:{}", event.id))
}),
);
let driver = Arc::new(Driver::new(dispatcher.clone(), handler.clone()));
dispatcher
.ingest(rhema_rsd::Event {
id: "e1".to_owned(),
source: "test".to_owned(),
payload: serde_json::json!({}),
received_at: 0,
})
.expect("event lands");
let busy = Arc::new(AtomicBool::new(false));
spawn_pass(driver.clone(), "test", busy.clone());
// The pass runs on its own task: the caller is already back, and
// the lane reads as held while the turn is under way.
tokio::time::timeout(Duration::from_secs(5), handler.started.acquire())
.await
.expect("the pass starts within five seconds")
.expect("the pass starts")
.forget();
assert!(
busy.load(Ordering::SeqCst),
"the lane is held for the whole pass"
);
spawn_pass(driver.clone(), "test", busy.clone());
handler.release.add_permits(1);
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while busy.load(Ordering::SeqCst) {
assert!(
tokio::time::Instant::now() < deadline,
"the flag clears when the pass ends"
);
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert_eq!(handler.runs.load(Ordering::SeqCst), 1, "one pass, not two");
}
#[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] #[test]
fn the_interactive_dispatcher_dispatches_now_and_leases_long() { fn the_interactive_dispatcher_dispatches_now_and_leases_long() {
let dispatch = interactive_dispatch(); let dispatch = interactive_dispatch();
+1 -1
View File
@@ -213,7 +213,7 @@ fn bound(raw: &str) -> String {
/// The hostname: `/etc/hostname`'s first line, else the `hostname` /// The hostname: `/etc/hostname`'s first line, else the `hostname`
/// command, else a stand-in — the file is not portable and the command /// command, else a stand-in — the file is not portable and the command
/// is not guaranteed, so absence is a report line. /// is not guaranteed, so absence is a report line.
fn hostname() -> String { pub(crate) fn hostname() -> String {
if let Ok(raw) = std::fs::read_to_string("/etc/hostname") { if let Ok(raw) = std::fs::read_to_string("/etc/hostname") {
let name = bound(&raw); let name = bound(&raw);
if !name.is_empty() { if !name.is_empty() {
+5 -4
View File
@@ -32,17 +32,18 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{Allowlist, Source, ToolRegistry}; use rhema_autonomous_agent::Source;
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_core::ToolResolver; use rhema_core::ToolResolver;
use rhema_forge_integration::ForgeKind;
use rhema_rsd::{Dispatcher, ResourceKey, SystemClock}; use rhema_rsd::{Dispatcher, ResourceKey, SystemClock};
use crate::consents::WaitBridge; use crate::consents::WaitBridge;
use crate::daemon::ClawError; use crate::daemon::ClawError;
use crate::forge::ForgeSource; use crate::forge::ForgeSource;
use crate::hub::EventHub; use crate::hub::EventHub;
use rhema_calendar_integration::CalendarSource; use crate::toolkit::{Allowlist, ToolRegistry};
use rhema_calendar_integration::CalendarStore;
use rhema_forge_integration::ForgeKind;
/// The store handles the standard set is assembled over. One struct, /// The store handles the standard set is assembled over. One struct,
/// so a new extension is a field plus a constructor line, not another /// so a new extension is a field plus a constructor line, not another
+376 -17
View File
@@ -24,9 +24,10 @@ use std::sync::{Arc, Mutex, PoisonError};
use rhema_autonomous_agent::{Source, SourceError, async_trait}; use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_forge_integration::forge_key_fn; 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::{ 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_identity::{IdentityStore, SecretKind};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock}; use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
@@ -218,8 +219,6 @@ pub struct ForgeSource {
/// The device-notification queue a [`Triage::Surface`] lands in. /// The device-notification queue a [`Triage::Surface`] lands in.
notifications: Arc<crate::notifications::NotificationStore>, notifications: Arc<crate::notifications::NotificationStore>,
clients: Mutex<HashMap<ClientKey, Arc<dyn Forge>>>, clients: Mutex<HashMap<ClientKey, Arc<dyn Forge>>>,
/// One notifications cursor per account id.
account_cursors: Mutex<HashMap<String, rhema_forge_integration::Timestamp>>,
} }
impl ForgeSource { impl ForgeSource {
@@ -244,7 +243,6 @@ impl ForgeSource {
accounts, accounts,
notifications, notifications,
clients: Mutex::new(HashMap::new()), clients: Mutex::new(HashMap::new()),
account_cursors: Mutex::new(HashMap::new()),
} }
} }
@@ -315,7 +313,14 @@ impl Source for ForgeSource {
} }
}; };
let client = self.client_for(&record); 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 // Health first, whatever the outcome: a watch that has been
// failing since it was created must be able to say so. // failing since it was created must be able to say so.
self.record_poll( self.record_poll(
@@ -366,6 +371,44 @@ impl Source for ForgeSource {
} }
impl 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 /// Records one poll's outcome, and says something the first time a
/// streak begins: a watch refused on every tick looks exactly like a /// streak begins: a watch refused on every tick looks exactly like a
/// quiet repository from the outside, and only the failing tick knows /// quiet repository from the outside, and only the failing tick knows
@@ -455,12 +498,18 @@ impl ForgeSource {
}; };
let client = record_client(kind, watch.host.as_deref(), &credential); let client = record_client(kind, watch.host.as_deref(), &credential);
let since = self // The cursor this poll asks from: the durable one when the watch
.account_cursors // has one, absent on its first pass — an unread feed is news. An
.lock() // unreadable row reads as absent, like a repo watch's: a
.unwrap_or_else(PoisonError::into_inner) // corrupted cursor must not fire a backlog. The map that used to
.get(&watch.account_id) // hold it was per-process, so every restart asked from nothing
.cloned(); // and re-decided the whole unread feed; the row is what a
// restart resumes from.
let stored = self
.store
.cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id)
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
let since = stored.as_deref().and_then(Timestamp::parse);
let page = client let page = client
.notifications(since.as_ref()) .notifications(since.as_ref())
.await .await
@@ -468,7 +517,7 @@ impl ForgeSource {
let now = SystemClock.now_millis(); let now = SystemClock.now_millis();
let mut fed = 0; let mut fed = 0;
for notification in &page.notifications { for notification in &page.notifications {
match triage::classify(notification) { match claw_triage(notification) {
Triage::Ignore => {} Triage::Ignore => {}
Triage::Surface => { Triage::Surface => {
if let Err(err) = self.notifications.push( if let Err(err) = self.notifications.push(
@@ -519,17 +568,55 @@ impl ForgeSource {
fed += 1; fed += 1;
} }
} }
// The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning
// it, and the durable cursor is what stops the poll asking
// for it again. Deciding without consuming is a loop: a row
// the forge still considers unread comes back every pass —
// re-decided and re-dispatched as a fresh turn for a thread
// that already has one — until the cursor passes it.
//
// Best-effort: an unread row costs a repeat, never a lost
// event, so a failed call is logged and the poll carries on.
if let Err(err) = client.mark_read(notification).await {
eprintln!(
"[claw] warning: mark-read of {} failed: {err}",
notification.id
);
}
} }
// Advance the durable cursor to wherever this poll got to. The
// in-memory map this replaces was per-process: a restart that
// lost it replayed the whole unread feed. A failed write is one
// pass's replay — dedup ids absorb it — so it reads as a poll
// failure, like the repo watch's cursor does.
if let Some(cursor) = page.cursor { if let Some(cursor) = page.cursor {
self.account_cursors self.store
.lock() .set_cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id, cursor.raw())
.unwrap_or_else(PoisonError::into_inner) .map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
.insert(watch.account_id.clone(), cursor);
} }
Ok(fed) Ok(fed)
} }
} }
/// [`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 /// The device-notification text a [`Triage::Surface`] lands: the reason
/// and the thread title, so the human can judge without opening the /// and the thread title, so the human can judge without opening the
/// forge. /// forge.
@@ -547,6 +634,227 @@ fn surface_body(notification: &Notification) -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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 account poll consumes what it decides. The feed is
/// at-least-once — the cursor never passes a row the forge still
/// considers unread, so a row that is triaged but not marked read
/// comes back with the same dedup id on the next pass, and every
/// pass dispatches a fresh turn for a thread that already has one.
#[tokio::test]
async fn a_triaged_account_notification_is_marked_read() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"id": 42188,
"unread": true,
"reason": "mention",
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": "https://api.github.com/repos/acme/widgets/pulls/142",
"type": "PullRequest"
},
"repository": { "full_name": "acme/widgets" }
}
])))
.mount(&server)
.await;
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let (dispatcher, accounts, notifications) = test_parts(store.clone());
// The store mints the id; the watch row is what names it.
let account = accounts
.put(rhema_identity::AccountDraft::new(
"forge bot",
"github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
))
.expect("account lands");
store
.add_account_watch("github", Some(&server.uri()), &account.id)
.expect("account watch lands");
let source = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
assert_eq!(
source.detect().await.expect("the pass runs"),
1,
"a mention dispatches a turn"
);
// The read route keys on the notification, not the thread.
let requests = server.received_requests().await.expect("recording is on");
let reads: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(reads.len(), 1, "one mark-read per triaged row");
assert_eq!(reads[0].url.path(), "/notifications/threads/42188");
}
/// The account cursor is durable. The pass that decides rows leaves
/// where it got to in the store, and a source built fresh over the
/// same store — the shape every restart takes — asks from that row
/// rather than from nothing: the in-memory map this replaces died
/// with the process, and every restart re-decided the whole unread
/// feed.
#[tokio::test]
async fn an_account_cursor_survives_a_restart() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"id": 42188,
"unread": true,
"reason": "mention",
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": "https://api.github.com/repos/acme/widgets/pulls/142",
"type": "PullRequest"
},
"repository": { "full_name": "acme/widgets" }
}
])))
.mount(&server)
.await;
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let (dispatcher, accounts, notifications) = test_parts(store.clone());
let account = accounts
.put(rhema_identity::AccountDraft::new(
"forge bot",
"github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
))
.expect("account lands");
store
.add_account_watch("github", Some(&server.uri()), &account.id)
.expect("account watch lands");
let source = ForgeSource::new(
&dispatcher,
"github",
store.clone(),
accounts.clone(),
notifications.clone(),
);
source.detect().await.expect("the pass runs");
// Where the poll got to is in the store, spelled like the feed's
// own instants.
let cursor = store
.cursor(SCOPE_ACCOUNT, "github", &account.id)
.expect("cursor reads")
.expect("the pass persisted a cursor");
assert_eq!(
cursor, "2026-10-05T12:00:00Z",
"the cursor is the newest instant the poll saw"
);
// The restart: a fresh source over the same store polls from the
// row, not from nothing.
let reborn = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
reborn.detect().await.expect("the restarted pass runs");
let requests = server.received_requests().await.expect("recording is on");
let polls: Vec<_> = requests
.iter()
.filter(|request| {
request.method.as_str() == "GET" && request.url.path() == "/notifications"
})
.collect();
assert_eq!(polls.len(), 2, "one poll per pass");
let since = polls[1].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()),
"the restart asks from the durable cursor"
);
}
/// The parts a test source polls through, all in memory. /// The parts a test source polls through, all in memory.
fn test_parts( fn test_parts(
@@ -831,6 +1139,7 @@ mod tests {
title: Some("Add the flange".to_owned()), title: Some("Add the flange".to_owned()),
url: None, url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"), timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}), raw: serde_json::json!({}),
}; };
let payload = |notification: &Notification| { let payload = |notification: &Notification| {
@@ -862,4 +1171,54 @@ mod tests {
}); });
assert_eq!(key.as_str(), "github:issue:acme/widgets#142"); 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"),
read_key: Some("1".to_owned()),
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()
);
}
}
} }
+472
View File
@@ -0,0 +1,472 @@
//! The workspace git identity: `user.name` and `user.email` in the
//! daemon user's global git config, written at boot so every commit a
//! workspace makes carries the agent as its author — before any
//! conversation happened, on a machine nobody onboarded.
//!
//! Like the environment report this is deterministic boot code, and
//! like every boot probe its failure is one log line, never a failed
//! boot. Each field resolves from three sources, first set wins: the
//! config file's `git` section (the operator's choice), the agent's
//! own presentation identity (`identity.name`, `identity.email` —
//! what onboarding and the settings page write), then defaults. The
//! values land in the git config the daemon user's `git` reads, so
//! thread workspaces, chat scratch repos, and anything the agent
//! inits itself all inherit them.
//!
//! The write is guarded. The settings store remembers the last pair
//! the daemon wrote; boot rewrites a field only when git's global
//! scope still holds that pair, or nothing at all. A value anyone
//! else set wins outright — the daemon is a tenant of its user's
//! machine, not the owner of its git config. The scope is git's own:
//! reads and writes run through `git config --global`, so whatever
//! file the user's git actually reads — `.gitconfig`, the XDG
//! `~/.config/git/config`, or the `GIT_CONFIG_GLOBAL` override — is
//! what the guard sees, not a guessed path that shadows it. An ssh
//! sandbox runs git on another host, so it stays out of scope here:
//! those workspaces remain unprovisioned until a later story pushes
//! the values remotely.
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::config::{ClawConfig, GitIdentity};
use crate::identity::{AgentIdentity, IdentityStore};
use crate::settings::SettingsStore;
/// The fallback author name, when the config and the identity are
/// both silent. Lowercase on purpose: a stand-in, not a persona.
pub const DEFAULT_NAME: &str = "claw";
/// The settings keys recording the last pair the daemon wrote. The
/// guard reads them back on every boot; a mismatch means the field
/// was hand-edited and is left alone.
const WRITTEN_NAME: &str = "git_identity_written_name";
const WRITTEN_EMAIL: &str = "git_identity_written_email";
/// The per-call budget: a local `git config` is a file operation; the
/// budget only bounds a wedged `git`, like any other boot probe.
const GIT_BUDGET: Duration = Duration::from_secs(2);
/// One resolved field: the value and where it came from, for the boot
/// log line.
pub struct ResolvedField {
/// The resolved value, ready for the config file.
pub value: String,
/// Where it came from: `config`, `identity`, or `default`, for
/// the boot log line.
pub source: &'static str,
}
/// Resolves both fields: config, then identity, then defaults. The
/// fields resolve independently — a config name beside an identity
/// email is a legal pair.
pub fn resolve(
git: Option<&GitIdentity>,
identity: &AgentIdentity,
hostname: &str,
) -> (ResolvedField, ResolvedField) {
let field = |configured: Option<String>, presented: Option<String>, default: String| {
if let Some(value) = configured {
ResolvedField {
source: "config",
value,
}
} else if let Some(value) = presented {
ResolvedField {
source: "identity",
value,
}
} else {
ResolvedField {
source: "default",
value: default,
}
}
};
let name = field(
git.and_then(|git| git.name.clone()),
identity.name.clone(),
DEFAULT_NAME.to_owned(),
);
let email = field(
git.and_then(|git| git.email.clone()),
identity.email.clone(),
format!("{}@{}", DEFAULT_NAME, hostname),
);
(name, email)
}
/// The boot entry point: opens the stores the daemon built, resolves,
/// provisions, and returns the log line. Nothing here is fatal — every
/// failure becomes the line the caller prints.
pub fn boot(config: &ClawConfig) -> String {
let outcome = (|| -> Result<String, String> {
// The scope rides the environment override when the caller set
// one — the tests' isolation — and is otherwise git's own
// global scope, resolved by git, not guessed here.
let scope = std::env::var("GIT_CONFIG_GLOBAL")
.ok()
.filter(|path| !path.trim().is_empty())
.map(PathBuf::from);
let db = config.db_path().map_err(|err| err.to_string())?;
let settings = Arc::new(SettingsStore::open(&db).map_err(|err| err.to_string())?);
let dir = db
.parent()
.ok_or("the database has no parent directory")?
.join("identity");
let who = IdentityStore::new(settings.clone(), dir)
.get()
.map_err(|err| err.to_string())?;
Ok(provision(
scope.as_deref(),
config.git.as_ref(),
&who,
&settings,
))
})();
outcome.unwrap_or_else(|reason| format!("git identity not provisioned: {reason}"))
}
/// Provisions both fields into the git global scope — `scope`, when
/// given, pins `GIT_CONFIG_GLOBAL` for the child `git` calls (the
/// tests' isolation); otherwise git resolves its own. Returns the log
/// line. The guard is per field: a hand-edited name beside an email
/// the daemon wrote is updated on the email side and left alone on
/// the name side.
pub fn provision(
scope: Option<&Path>,
git: Option<&GitIdentity>,
identity: &AgentIdentity,
settings: &SettingsStore,
) -> String {
let (name, email) = resolve(git, identity, &crate::environment::hostname());
let mut parts = Vec::new();
field(
scope,
"user.name",
WRITTEN_NAME,
&name,
settings,
&mut parts,
);
field(
scope,
"user.email",
WRITTEN_EMAIL,
&email,
settings,
&mut parts,
);
format!("git identity: {}", parts.join(", "))
}
/// One field's guard, write, and log phrase:
/// - the config file holds someone else's value → kept, untouched;
/// - it already holds the resolved value → aligned (the marker too,
/// so a later resolution can still update it — a hand edit that
/// matches what the daemon resolved counts as the daemon's);
/// - it is unset, or it is exactly what the daemon wrote last time →
/// written, and the marker follows.
fn field(
scope: Option<&Path>,
key: &str,
setting_key: &str,
want: &ResolvedField,
settings: &SettingsStore,
parts: &mut Vec<String>,
) {
let mut summary = |action: String| {
parts.push(format!(
"{} {:?} from {}: {}",
key.rsplit_once('.').map(|(_, n)| n).unwrap_or(key),
want.value,
want.source,
action
))
};
let written = settings.get(setting_key).ok().flatten();
match read(scope, key) {
Err(reason) => summary(format!("unreadable ({reason}), left alone")),
Ok(Some(current))
if Some(current.as_str()) != written.as_deref() && current != want.value =>
{
summary("kept a hand-edited value".to_owned())
}
Ok(Some(current)) if current == want.value => {
if written.as_deref() != Some(current.as_str()) {
record(settings, setting_key, &current);
}
summary("already current".to_owned())
}
Ok(_) => match write(scope, key, &want.value) {
Ok(()) => {
record(settings, setting_key, &want.value);
summary("wrote".to_owned())
}
Err(reason) => summary(format!("not written ({reason})")),
},
}
}
/// Records the pair the daemon wrote, so the next boot can tell its
/// own values from a hand edit. A store failure leaves the guard
/// conservative: the field reads as foreign next boot and is kept.
fn record(settings: &SettingsStore, key: &str, value: &str) {
let _ = settings.set(key, value);
}
/// One `git` invocation: fixed argv, no shell, stdin null, a short
/// budget. The exit code travels — a read's `1` means the key is
/// unset, which is an answer, not an error.
enum GitRun {
Completed { code: i32, stdout: String },
NotFound,
TimedOut,
}
fn git_scoped(scope: Option<&Path>, args: &[&str]) -> GitRun {
let mut command = Command::new("git");
command.args(args);
if let Some(path) = scope {
// The child only: the caller's environment stays untouched,
// and parallel scopes in tests cannot see each other.
command.env("GIT_CONFIG_GLOBAL", path);
}
let mut child = match command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return GitRun::NotFound,
Err(_) => return GitRun::NotFound,
};
let deadline = Instant::now() + GIT_BUDGET;
let code = loop {
match child.try_wait() {
Ok(Some(status)) => break status.code(),
Ok(None) if Instant::now() >= deadline => break None,
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => break None,
}
};
let Some(code) = code else {
let _ = child.kill();
let _ = child.wait();
return GitRun::TimedOut;
};
let stdout = child
.stdout
.take()
.map(|mut pipe| {
let mut buf = Vec::new();
use std::io::Read;
let _ = pipe.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
})
.unwrap_or_default();
GitRun::Completed { code, stdout }
}
/// Reads one key from the git global scope: `Some` when set, `None`
/// when unset (git exits 1 for that), an error when the read cannot be
/// trusted (a missing git, a multi-valued key) — and an untrusted read
/// is never written over. Git resolves the scope itself, so the value
/// seen is the value a commit would carry, from whichever file holds
/// it.
fn read(scope: Option<&Path>, key: &str) -> Result<Option<String>, String> {
match git_scoped(scope, &["config", "--global", "--get", key]) {
GitRun::Completed { code: 0, stdout } => {
Ok(Some(stdout.trim().to_owned()).filter(|value| !value.is_empty()))
}
GitRun::Completed { code: 1, .. } => Ok(None),
GitRun::Completed { code, .. } => Err(format!("exit {code}")),
GitRun::NotFound => Err("git not found".to_owned()),
GitRun::TimedOut => Err("no exit in time".to_owned()),
}
}
/// Writes one key into the git global scope, replacing every value
/// the key carries (`--replace-all` keeps the field single-valued even
/// over a strange starting file). Git picks the file — its own write
/// rule, the XDG config when that is the established one, `.gitconfig`
/// otherwise, the `GIT_CONFIG_GLOBAL` the scope pins.
fn write(scope: Option<&Path>, key: &str, value: &str) -> Result<(), String> {
match git_scoped(scope, &["config", "--global", "--replace-all", key, value]) {
GitRun::Completed { code: 0, .. } => Ok(()),
GitRun::Completed { code, .. } => Err(format!("exit {code}")),
GitRun::NotFound => Err("git not found".to_owned()),
GitRun::TimedOut => Err("no exit in time".to_owned()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GitIdentity;
use crate::identity::IdentityTexts;
/// The fixture: a temp file standing in as the git global scope
/// (`GIT_CONFIG_GLOBAL` for the child `git` calls), an in-memory
/// settings store, and a fresh store handle per test.
struct Fixture {
file: PathBuf,
settings: SettingsStore,
#[allow(dead_code)]
dir: tempfile::TempDir,
}
fn fixture() -> Fixture {
let dir = tempfile::tempdir().expect("tempdir");
let file = dir.path().join("gitconfig");
Fixture {
file,
settings: SettingsStore::in_memory().expect("the store opens"),
dir,
}
}
/// Provisions inside the fixture's scope.
fn run(fix: &Fixture, git: Option<&GitIdentity>, who: &AgentIdentity) -> String {
provision(Some(&fix.file), git, who, &fix.settings)
}
fn identity(name: Option<&str>, email: Option<&str>) -> AgentIdentity {
let store_settings = crate::settings::SettingsStore::in_memory().expect("the store opens");
let images = tempfile::tempdir().expect("tempdir");
let store = IdentityStore::new(Arc::new(store_settings), images.path().join("identity"));
store
.set_texts(&IdentityTexts {
name: name.map(str::to_owned),
mark: None,
initials: None,
tagline: None,
signoff: None,
email: email.map(str::to_owned),
})
.expect("the identity saves")
}
fn config_git(name: Option<&str>, email: Option<&str>) -> Option<GitIdentity> {
Some(GitIdentity {
name: name.map(str::to_owned),
email: email.map(str::to_owned),
})
}
fn value_of(file: &Path, key: &str) -> Option<String> {
read(Some(file), key).expect("the key reads")
}
#[test]
fn defaults_land_when_nothing_is_set() {
let fix = fixture();
let who = identity(None, None);
let line = run(&fix, None, &who);
assert_eq!(value_of(&fix.file, "user.name").as_deref(), Some("claw"));
assert_eq!(
value_of(&fix.file, "user.email").as_deref(),
Some(format!("claw@{}", crate::environment::hostname()).as_str()),
);
assert!(line.contains("from default"), "{line}");
assert!(line.contains("wrote"), "{line}");
}
#[test]
fn config_beats_identity_beats_default() {
let fix = fixture();
let who = identity(Some("Kosmos"), Some("kosmos@example.net"));
run(&fix, config_git(Some("Bot"), None).as_ref(), &who);
assert_eq!(value_of(&fix.file, "user.name").as_deref(), Some("Bot"));
assert_eq!(
value_of(&fix.file, "user.email").as_deref(),
Some("kosmos@example.net"),
"the fields resolve independently"
);
let other = fixture();
run(&other, None, &who);
assert_eq!(
value_of(&other.file, "user.name").as_deref(),
Some("Kosmos")
);
}
#[test]
fn a_hand_edited_value_wins_and_is_recorded_as_foreign() {
let fix = fixture();
write(Some(&fix.file), "user.name", "The Operator").expect("the seed writes");
let who = identity(Some("Kosmos"), None);
let line = run(&fix, None, &who);
assert_eq!(
value_of(&fix.file, "user.name").as_deref(),
Some("The Operator")
);
assert!(line.contains("kept"), "{line}");
// The daemon did not write it, so no marker was recorded.
assert_eq!(fix.settings.get(WRITTEN_NAME).unwrap(), None);
// The unset email beside it still provisions: the guard is per field.
assert!(value_of(&fix.file, "user.email").is_some());
}
#[test]
fn reruns_update_what_the_daemon_wrote() {
let fix = fixture();
let first = identity(Some("Kosmos"), None);
run(&fix, None, &first);
let second = identity(Some("Kosmos Prime"), None);
let line = run(&fix, None, &second);
assert_eq!(
value_of(&fix.file, "user.name").as_deref(),
Some("Kosmos Prime"),
"the daemon rewrites its own values"
);
assert!(line.contains("wrote"), "{line}");
// And a rerun over an already-current pair is a no-op.
let before = std::fs::read_to_string(&fix.file).expect("the file reads");
let line = run(&fix, None, &second);
let after = std::fs::read_to_string(&fix.file).expect("the file reads");
assert_eq!(before, after, "nothing to do, nothing written");
assert!(line.contains("already current"), "{line}");
}
#[test]
fn a_config_change_flows_through_on_the_next_boot() {
let fix = fixture();
let who = identity(None, None);
run(
&fix,
config_git(Some("Bot"), Some("bot@example.net")).as_ref(),
&who,
);
run(
&fix,
config_git(Some("Renamed"), Some("moved@example.net")).as_ref(),
&who,
);
assert_eq!(value_of(&fix.file, "user.name").as_deref(), Some("Renamed"));
assert_eq!(
value_of(&fix.file, "user.email").as_deref(),
Some("moved@example.net"),
);
}
#[test]
fn a_hand_edit_that_matches_the_resolution_counts_as_the_daemons() {
let fix = fixture();
let who = identity(Some("Kosmos"), None);
write(Some(&fix.file), "user.name", "Kosmos").expect("the seed writes");
run(&fix, None, &who);
// The marker was aligned, so a later resolution updates the field.
let renamed = identity(Some("Kosmos II"), None);
run(&fix, None, &renamed);
assert_eq!(
value_of(&fix.file, "user.name").as_deref(),
Some("Kosmos II")
);
}
}
+517 -50
View File
@@ -10,7 +10,7 @@
//! //!
//! Session continuity rides the dispatcher, not the filesystem: the //! Session continuity rides the dispatcher, not the filesystem: the
//! agent's session JSON is stashed into `ctx.session.core.driver_state` //! 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 //! 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 //! 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 //! context's commit hook, so the intent is in the store before the first
@@ -23,11 +23,11 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, PoisonError};
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, Surface};
use crate::forge::{WatchCredential, record_client, resolve_watch_credential}; use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore; use crate::watch_store::ClawStore;
use rhema_agent_tools::AllowAll;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait}; 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_core::{Content, Event as ModelEvent, EventSink, Message, Session};
use rhema_forge_integration::ForgeKind; use rhema_forge_integration::ForgeKind;
use rhema_forge_integration::triage::Role; use rhema_forge_integration::triage::Role;
@@ -35,10 +35,13 @@ use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode, EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode,
parse_key, parse_key,
}; };
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_identity::IdentityStore; use rhema_identity::IdentityStore;
use rhema_rsd::{InboxItem, Outcome, ResourceKey}; use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell;
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
use crate::sandbox::SandboxState;
/// The handler's tool permissions, resolved deterministically before the /// The handler's tool permissions, resolved deterministically before the
/// agent's first step (spec §8) — never by the model, never mid-run. V1 /// agent's first step (spec §8) — never by the model, never mid-run. V1
@@ -47,14 +50,25 @@ use crate::backends::BackendRegistry;
/// [`Role`] is the seam it hangs on, a reviewer dispatch deserving a /// [`Role`] is the seam it hangs on, a reviewer dispatch deserving a
/// narrower policy than an implementer's — and a policy that refuses the /// narrower policy than an implementer's — and a policy that refuses the
/// shell refuses the run (see [`ClawHandler::dispatch`]). /// shell refuses the run (see [`ClawHandler::dispatch`]).
fn allowlist() -> rhema_autonomous_agent::Allowlist { fn allowlist() -> crate::toolkit::Allowlist {
rhema_autonomous_agent::Allowlist::permissive() crate::toolkit::Allowlist::permissive()
} }
/// The coding agent over one watch: a provider, a model, a workspace /// The coding agent over one watch: a provider, a model, a workspace
/// root, and the watch table the dispatch keys resolve through — live, /// root, and the watch table the dispatch keys resolve through — live,
/// so a watch added at runtime is answerable without a restart. /// so a watch added at runtime is answerable without a restart.
///
/// The agent is the resident's: every dispatch renders the same
/// bootstrap prompt the chat surfaces render — SOUL.md, USER.md, the
/// environment report — over the thread's workspace, so the claw that
/// answers a review or a mention is the character the user chats with,
/// not a nameless delegate. The tools stay the coding set (shell,
/// vision, MCP); the chat-only rosters (memory, notifications, the
/// key-scoped asks) do not ride a forge dispatch.
pub struct ClawHandler { pub struct ClawHandler {
/// The bootstrap store the persona renders from, per dispatch, so
/// a SOUL.md the chat wrote is live on the next forge answer.
bootstrap: Arc<Bootstrap>,
/// The deployment's providers and the active pair, read per dispatch. /// The deployment's providers and the active pair, read per dispatch.
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
/// Whether the sessions run the bounded request view (the config's /// Whether the sessions run the bounded request view (the config's
@@ -70,7 +84,17 @@ pub struct ClawHandler {
/// agent shell: the daemon URL, the scoped agent token, the tools' /// agent shell: the daemon URL, the scoped agent token, the tools'
/// bin dir on PATH. Empty when the config issues no agent token. /// bin dir on PATH. Empty when the config issues no agent token.
tool_env: std::collections::BTreeMap<String, String>, 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>>,
/// The abort registry the sessions' abort route signals: a live
/// turn cut at its await stashes what it committed and ends the
/// dispatch as superseded, its comment never posted (see
/// [`crate::abort`]). Private by default — a handler nobody shared
/// a registry with never receives a signal — and shared through
/// [`ClawHandler::with_abort`].
abort: Arc<crate::abort::AbortRegistry>,
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
} }
impl ClawHandler { impl ClawHandler {
@@ -81,6 +105,7 @@ impl ClawHandler {
workspace_root: impl Into<PathBuf>, workspace_root: impl Into<PathBuf>,
watches: Arc<ClawStore>, watches: Arc<ClawStore>,
accounts: Arc<dyn IdentityStore>, accounts: Arc<dyn IdentityStore>,
bootstrap: Arc<Bootstrap>,
transcript: bool, transcript: bool,
tool_env: std::collections::BTreeMap<String, String>, tool_env: std::collections::BTreeMap<String, String>,
) -> Self { ) -> Self {
@@ -90,11 +115,29 @@ impl ClawHandler {
workspace_root: workspace_root.into(), workspace_root: workspace_root.into(),
watches, watches,
accounts, accounts,
bootstrap,
tool_env, tool_env,
sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
clients: Mutex::new(HashMap::new()), 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
}
/// Shares the abort registry with the HTTP surface: the abort route
/// signals it, and every forge dispatch this handler runs listens
/// on it.
pub fn with_abort(mut self, abort: Arc<crate::abort::AbortRegistry>) -> Self {
self.abort = abort;
self
}
/// The forge client a dispatch key answers to: /// The forge client a dispatch key answers to:
/// `"github:issue:acme/widgets#7"` resolves its watch record from the /// `"github:issue:acme/widgets#7"` resolves its watch record from the
/// table at dispatch time — the table is the source of truth, not a /// table at dispatch time — the table is the source of truth, not a
@@ -120,6 +163,18 @@ impl ClawHandler {
key: &ResourceKey, key: &ResourceKey,
as_account: Option<&str>, as_account: Option<&str>,
) -> Result<Arc<dyn Forge>, String> { ) -> 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) let watch = watch_key(key)
.ok_or_else(|| format!("resource key {key} is not a forge thread key"))?; .ok_or_else(|| format!("resource key {key} is not a forge thread key"))?;
let (forge, repo) = watch let (forge, repo) = watch
@@ -192,7 +247,7 @@ impl ClawHandler {
kind: ForgeKind, kind: ForgeKind,
host: Option<&str>, host: Option<&str>,
credential: &WatchCredential, credential: &WatchCredential,
) -> Arc<dyn Forge> { ) -> Arc<WatchClient> {
// Everything that changes the client: the kind, its host, and the // Everything that changes the client: the kind, its host, and the
// credential — the login included, since one value sent two ways // credential — the login included, since one value sent two ways
// is two credentials. // is two credentials.
@@ -206,7 +261,10 @@ impl ClawHandler {
let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner); let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner);
clients clients
.entry(cache_key) .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() .clone()
} }
@@ -224,7 +282,22 @@ impl ClawHandler {
// that account — a thread the account's feed delivered may have no // that account — a thread the account's feed delivered may have no
// repo watch row at all. // repo watch row at all.
let news = self.drain_news(ctx, &key).await?; 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 let snapshot = forge
.snapshot(&repo, thread_kind, number) .snapshot(&repo, thread_kind, number)
@@ -251,10 +324,28 @@ impl ClawHandler {
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role); let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
let mut sink = TurnSink; let mut sink = TurnSink;
let output = agent // The abort listener rides the turn: a signal drops the future
.turn(prompt, &mut sink, Arc::new(AllowAll)) // at its current await — a streaming request, or a running
.await // shell command, whose child dies with the drop. What the turn
.map_err(|err| format!("turn for {key} failed: {err}"))?; // committed so far is already the session (the commit hook),
// so the stash below hands it to the next dispatch.
let mut abort = self.abort.listen(&key);
let turned = tokio::select! {
output = agent.turn(prompt, &mut sink) => {
Some(output.map_err(|err| format!("turn for {key} failed: {err}")))
}
_ = abort.wait() => None,
};
let output = match turned {
Some(output) => output?,
None => {
// Cut, not failed: the thread gets no half-answer, and
// the session keeps whatever the turn committed.
ctx.session.core.driver_state = serde_json::to_value(agent.session())
.map_err(|err| format!("session for {key} does not serialize: {err}"))?;
return Ok(Outcome::Superseded);
}
};
// Stash before posting: the turn's work survives a failed comment. // Stash before posting: the turn's work survives a failed comment.
ctx.session.core.driver_state = serde_json::to_value(agent.session()) ctx.session.core.driver_state = serde_json::to_value(agent.session())
@@ -299,36 +390,87 @@ impl ClawHandler {
ctx: &SessionContext, ctx: &SessionContext,
workspace: &Path, workspace: &Path,
key: &str, key: &str,
) -> Result<CodingAgent, String> { ) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current(); let (provider, model) = self.backends.current();
let config = self.agent_config(&model, workspace); let config = self.agent_config(provider, &model, workspace, key)?;
let agent = match &ctx.session.core.driver_state { let agent = match &ctx.session.core.driver_state {
// A never-dispatched key carries no stash: start clean. // 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 => { stashed => {
let session: Session = serde_json::from_value(stashed.clone()) let session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?; .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}")) agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
} }
/// The config one dispatch's agent runs on: the default coding /// The config one dispatch's agent runs on: the resident's own
/// agent's, with the bounded request view when the config has it on. /// prompt — the bootstrap template rendered per dispatch over the
/// A forge thread answers for as long as the thread lives; without /// thread's workspace, SOUL.md and USER.md live — with the bounded
/// the view its history would ride whole on every step. /// request view when the config has it on and a remote shell when
fn agent_config(&self, model: &str, workspace: &Path) -> CodingAgentConfig { /// the sandbox choice says so. A forge thread answers for as long
let mut config = CodingAgentConfig::new(model, workspace); /// as the thread lives; without the view its history would ride
/// whole on every step.
fn agent_config(
&self,
provider: Arc<dyn rhema_core::ModelProvider>,
model: &str,
workspace: &Path,
key: &str,
) -> Result<HostAgentConfig, String> {
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 // Write the resolved value, not an override: the coding agent's
// own default is on now, and the config's `false` must win. // own default is on now, and the config's `false` must win.
config.transcript = self config.transcript = self
.transcript .transcript
.then(rhema_transcript::TranscriptSettings::default); .then(rhema_transcript::TranscriptSettings::default);
config.shell_env = self.tool_env.clone(); config.shell_env = self.tool_env.clone();
crate::vision::apply(&mut config); // The prompt names the workspace the model sees and documents
crate::mcp::apply(&mut config); // exactly what the request advertises: the shell built-ins plus
config // the transcript's zoom when the view is on — the same assembly
// the host agent does for its own default prompt. A verbatim
// prompt ignores the config's template sections, so the vision
// and MCP documentation render here from the same wired values;
// a remote sandbox wires neither.
let mut vision = None;
let mut mcp = Vec::new();
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display.clone(),
sandbox.executor(workspace.to_path_buf()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
vision = config.vision.clone();
mcp = config.mcp_servers.clone();
}
}
let mut specs = ShellTools::builtin_specs();
if config.transcript.is_some() {
specs.push(rhema_transcript::Zoom::spec());
}
config.system = Some(
crate::bootstrap::render_system(
DEFAULT_SYSTEM_MD,
key,
&display,
&self.bootstrap,
&specs,
vision.as_deref(),
&mcp,
Surface::Forge,
)
.map_err(|err| format!("cannot render the forge system prompt for {key}: {err}"))?,
);
Ok(config)
} }
/// The per-thread workspace: one directory under the root, created on /// The per-thread workspace: one directory under the root, created on
@@ -343,6 +485,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] #[async_trait]
impl Handler for ClawHandler { impl Handler for ClawHandler {
async fn handle(&self, ctx: &mut SessionContext) -> Outcome { async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
@@ -440,6 +621,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: /// The batch's dominant role, for the prompt's persona framing:
/// implementing subsumes reviewing — a batch that asks for both is a /// implementing subsumes reviewing — a batch that asks for both is a
/// dispatch where the work is the point. Plain events imply no persona: /// dispatch where the work is the point. Plain events imply no persona:
@@ -470,30 +705,31 @@ fn dominant_role(news: &[InboxNews]) -> Option<Role> {
} }
} }
/// The persona framing a dispatched role opens the prompt with. The key /// The task framing a dispatched role opens the prompt with. Who is
/// stays the thread, so a role change across dispatches is the session's /// answering lives in the system prompt — SOUL.md, the same file every
/// chat dispatch renders; this is only what the job is. The key stays
/// the thread, so a role change across dispatches is the session's
/// continuity, not a new conversation. /// continuity, not a new conversation.
fn persona_text(role: Role) -> &'static str { fn task_text(role: Role) -> &'static str {
match role { match role {
Role::Reviewer => { Role::Reviewer => {
"You are acting as this pull request's reviewer. Check the change \ "This dispatch is a review request. Check the change out in the \
out in the workspace when you can, read the diff, and judge it: correctness, \ workspace when you can, read the diff, and judge it: correctness, tests, \
tests, edge cases, fit with the surrounding code. Your final reply is the \ edge cases, fit with the surrounding code. Make the reply the review — \
review — findings first, ordered by severity, concrete and actionable; if \ findings first, ordered by severity, concrete and actionable; if there is \
there is nothing to fix, say so plainly and say what you checked." nothing to fix, say so plainly and say what you checked."
} }
Role::Implementer => { Role::Implementer => {
"You are acting as this thread's implementer. Do the work the new \ "This dispatch asks for work. Address the review feedback or the \
activity asks for: address the review feedback or the assigned issue by \ assigned issue by changing the code in the workspace — build and test what \
changing the code in the workspace — build and test what you change. Your \ you change. Make the reply a short report of what you changed and why, or, \
final reply is a short report of what you changed and why, or, when the \ when the whole change does not fit one turn, what landed now and the \
whole change does not fit one turn, what landed now and the concrete plan \ concrete plan for the rest."
for the rest."
} }
} }
} }
/// The agent's prompt for one dispatch: the persona framing (when the /// The agent's prompt for one dispatch: the task framing (when the
/// triage dispatched a role), the thread's standing state, the new news, /// triage dispatched a role), the thread's standing state, the new news,
/// and the posting contract. The final assistant message is the comment /// and the posting contract. The final assistant message is the comment
/// — everything else is orientation for the investigation. /// — everything else is orientation for the investigation.
@@ -506,7 +742,7 @@ fn build_prompt(
) -> String { ) -> String {
let mut prompt = String::new(); let mut prompt = String::new();
if let Some(role) = role { if let Some(role) = role {
prompt.push_str(persona_text(role)); prompt.push_str(task_text(role));
prompt.push_str("\n\n"); prompt.push_str("\n\n");
} }
prompt.push_str(&format!( prompt.push_str(&format!(
@@ -712,6 +948,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] #[test]
fn thread_level_events_carry_no_body_and_the_prompt_says_so() { fn thread_level_events_carry_no_body_and_the_prompt_says_so() {
let prompt = build_prompt( let prompt = build_prompt(
@@ -738,6 +1057,7 @@ mod tests {
"title": "Add the widget flange", "title": "Add the widget flange",
"url": null, "url": null,
"timestamp": "2026-10-03T09:00:00Z", "timestamp": "2026-10-03T09:00:00Z",
"read_key": "42188",
"raw": {}, "raw": {},
})) }))
.expect("notification fixture parses") .expect("notification fixture parses")
@@ -844,8 +1164,12 @@ mod tests {
Some(Role::Reviewer), Some(Role::Reviewer),
); );
assert!( assert!(
prompt.contains("acting as this pull request's reviewer"), prompt.contains("This dispatch is a review request"),
"persona: {prompt}" "task: {prompt}"
);
assert!(
!prompt.contains("You are acting as"),
"who answers is the system prompt's to say, not the task text's: {prompt}"
); );
assert!( assert!(
prompt.contains("notification (review_requested) on pull request #142"), prompt.contains("notification (review_requested) on pull request #142"),
@@ -861,6 +1185,7 @@ mod tests {
Content::Text("on it".into()), Content::Text("on it".into()),
Content::Text(" — closing.".into()), Content::Text(" — closing.".into()),
], ],
annotations: Default::default(),
}; };
assert_eq!(final_text(&message).as_deref(), Some("on it — closing.")); assert_eq!(final_text(&message).as_deref(), Some("on it — closing."));
let tool_only = Message { let tool_only = Message {
@@ -871,10 +1196,19 @@ mod tests {
args: serde_json::json!({}), args: serde_json::json!({}),
provider_data: serde_json::Value::Null, provider_data: serde_json::Value::Null,
})], })],
annotations: Default::default(),
}; };
assert_eq!(final_text(&tool_only), None, "no text, no reply"); assert_eq!(final_text(&tool_only), None, "no text, no reply");
} }
/// A throwaway bootstrap store: the persona renders from it, the
/// shape the daemon assembles over the configured directory.
fn bootstrap() -> (tempfile::TempDir, Arc<Bootstrap>) {
let dir = tempfile::tempdir().expect("tempdir");
let store = Bootstrap::new(dir.path().join("bootstrap")).expect("store opens");
(dir, Arc::new(store))
}
#[test] #[test]
fn a_key_resolves_to_its_watch_entry_live_from_the_table() { fn a_key_resolves_to_its_watch_entry_live_from_the_table() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens")); let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
@@ -891,11 +1225,13 @@ mod tests {
) )
.expect("constructs"), .expect("constructs"),
); );
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new( let handler = ClawHandler::new(
registry, registry,
"/tmp/w", "/tmp/w",
watches, watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()), Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
true, true,
std::collections::BTreeMap::new(), std::collections::BTreeMap::new(),
); );
@@ -956,11 +1292,13 @@ mod tests {
) )
.expect("constructs"), .expect("constructs"),
); );
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new( let handler = ClawHandler::new(
registry, registry,
"/tmp/w", "/tmp/w",
watches, watches,
accounts, accounts,
bootstrap,
true, true,
std::collections::BTreeMap::new(), std::collections::BTreeMap::new(),
); );
@@ -1014,11 +1352,14 @@ mod tests {
.expect("constructs"), .expect("constructs"),
); );
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new()); let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0;
let (_dir, bootstrap) = bootstrap();
let on = ClawHandler::new( let on = ClawHandler::new(
registry.clone(), registry.clone(),
"/tmp/w", "/tmp/w",
watches.clone(), watches.clone(),
accounts.clone(), accounts.clone(),
bootstrap.clone(),
true, true,
std::collections::BTreeMap::new(), std::collections::BTreeMap::new(),
); );
@@ -1027,18 +1368,144 @@ mod tests {
"/tmp/w", "/tmp/w",
watches, watches,
accounts, accounts,
bootstrap,
false, false,
std::collections::BTreeMap::new(), std::collections::BTreeMap::new(),
); );
assert!( assert!(
on.agent_config("m", Path::new("/tmp/w")) on.agent_config(
.transcript provider.clone(),
.is_some() "m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7"
)
.expect("renders")
.transcript
.is_some()
); );
assert!( assert!(
off.agent_config("m", Path::new("/tmp/w")) off.agent_config(
.transcript provider,
.is_none() "m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7"
)
.expect("renders")
.transcript
.is_none()
);
}
#[test]
fn the_forge_dispatch_renders_the_residents_own_prompt() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
let registry = Arc::new(
crate::backends::BackendRegistry::new(
vec![crate::backends::Backend::headless(
"mock",
Arc::new(NoopProvider),
)],
None,
)
.expect("constructs"),
);
let (_dir, bootstrap) = bootstrap();
bootstrap
.save(
crate::bootstrap::BootstrapKind::Soul,
"I am claw: terse, warm, relentless.",
)
.expect("saves");
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
true,
std::collections::BTreeMap::new(),
);
let provider = handler.backends.current().0;
let config = handler
.agent_config(
provider,
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7",
)
.expect("renders");
let prompt = config.system.expect("the forge prompt is verbatim");
assert!(
prompt.contains("I am claw: terse, warm, relentless."),
"the soul rides the forge prompt: {prompt}"
);
assert!(
prompt.contains("the comment posted to the thread"),
"the forge branch of the reply contract: {prompt}"
);
assert!(
!prompt.contains("You answer chat here"),
"not the chat branch: {prompt}"
);
assert!(
prompt.contains("github:issue:acme/widgets#7"),
"the session key: {prompt}"
);
assert!(
prompt.contains("- bash |"),
"the shell tool is documented: {prompt}"
);
assert!(
prompt.contains("zoom"),
"the transcript view's tool is documented when the view is on: {prompt}"
);
assert!(
!prompt.contains("## Memory"),
"no memory tools, no memory section: {prompt}"
);
}
#[test]
fn a_fresh_house_never_sends_a_forge_dispatch_onboarding() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
let registry = Arc::new(
crate::backends::BackendRegistry::new(
vec![crate::backends::Backend::headless(
"mock",
Arc::new(NoopProvider),
)],
None,
)
.expect("constructs"),
);
// No SOUL.md, no USER.md — the state where chat onboards.
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
false,
std::collections::BTreeMap::new(),
);
let provider = handler.backends.current().0;
let config = handler
.agent_config(
provider,
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7",
)
.expect("renders");
let prompt = config.system.expect("the forge prompt is verbatim");
assert!(
!prompt.contains("## Onboarding"),
"a forge thread is nobody's first conversation: {prompt}"
);
assert!(
prompt.contains("(pending onboarding)"),
"the stub says so honestly: {prompt}"
); );
} }
+407 -41
View File
@@ -47,7 +47,7 @@ use rhema_claw_tools_contract::CONTRACT_HEADER;
use rhema_claw_tools_contract::CONTRACT_VERSION; use rhema_claw_tools_contract::CONTRACT_VERSION;
use rhema_core::ImageMediaType; use rhema_core::ImageMediaType;
use rhema_rsd::{ use rhema_rsd::{
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, ResourceKey, Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, Outcome, ResourceKey,
SqliteStore, Store, SqliteStore, Store,
}; };
use serde::{Deserialize, Deserializer}; use serde::{Deserialize, Deserializer};
@@ -55,11 +55,13 @@ use serde_json::{Value, json};
use tokio::sync::broadcast::error::RecvError; use tokio::sync::broadcast::error::RecvError;
use tokio_stream::wrappers::ReceiverStream; use tokio_stream::wrappers::ReceiverStream;
use crate::abort::AbortRegistry;
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
use crate::bootstrap::Bootstrap; use crate::bootstrap::Bootstrap;
use crate::hub::{EventHub, TurnEvent}; use crate::hub::{EventHub, TurnEvent};
use crate::interactive::WireImage; use crate::interactive::WireImage;
use crate::notifications::NotificationStore; use crate::notifications::NotificationStore;
use crate::pause::PauseSet;
use crate::steer::SteerRegistry; use crate::steer::SteerRegistry;
use crate::task_store::TaskStore; use crate::task_store::TaskStore;
use crate::watch_store::{ClawStore, validate_watch}; use crate::watch_store::{ClawStore, validate_watch};
@@ -106,6 +108,17 @@ pub struct ClawState {
/// a chat message into a key whose turn is live cuts that turn /// a chat message into a key whose turn is live cuts that turn
/// short (see [`crate::steer`]). /// short (see [`crate::steer`]).
steer: Arc<SteerRegistry>, steer: Arc<SteerRegistry>,
/// The pause gate the pause/resume routes write and every driver's
/// ownership predicate reads: the keys whose dispatch is held (see
/// [`crate::pause`]).
pause: Arc<PauseSet>,
/// The abort registry the abort route signals: the live turn it
/// cuts ends as superseded (see [`crate::abort`]).
abort: Arc<AbortRegistry>,
/// The coding-job table the abort route reads when an idle
/// `job:` key's queue is dropped: the row is the jobs' truth, so
/// the row moves with the abort.
jobs: Arc<crate::job_store::CodingJobStore>,
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
settings: Arc<crate::settings::SettingsStore>, settings: Arc<crate::settings::SettingsStore>,
identity: Arc<crate::identity::IdentityStore>, identity: Arc<crate::identity::IdentityStore>,
@@ -123,6 +136,9 @@ pub struct ClawState {
/// The phone tables: the command queue the device polls and the /// The phone tables: the command queue the device polls and the
/// reported state the ingest door feeds. /// reported state the ingest door feeds.
phone: Arc<crate::phone::PhoneStore>, 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>, token: Option<String>,
/// The scoped agent token the client tools hold: a second bearer /// The scoped agent token the client tools hold: a second bearer
/// answering only the contract's data routes (see /// answering only the contract's data routes (see
@@ -146,7 +162,7 @@ impl ClawState {
/// `agent_token`. /// `agent_token`.
#[expect( #[expect(
clippy::too_many_arguments, clippy::too_many_arguments,
reason = "eighteen parts, each load-bearing" reason = "twenty-one parts, each load-bearing"
)] )]
pub fn new( pub fn new(
dispatcher: Arc<Dispatcher>, dispatcher: Arc<Dispatcher>,
@@ -159,6 +175,9 @@ impl ClawState {
bootstrap: Arc<Bootstrap>, bootstrap: Arc<Bootstrap>,
hub: Arc<EventHub>, hub: Arc<EventHub>,
steer: Arc<SteerRegistry>, steer: Arc<SteerRegistry>,
pause: Arc<PauseSet>,
abort: Arc<AbortRegistry>,
jobs: Arc<crate::job_store::CodingJobStore>,
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
settings: Arc<crate::settings::SettingsStore>, settings: Arc<crate::settings::SettingsStore>,
identity: Arc<crate::identity::IdentityStore>, identity: Arc<crate::identity::IdentityStore>,
@@ -167,6 +186,7 @@ impl ClawState {
bridge: Arc<crate::consents::WaitBridge>, bridge: Arc<crate::consents::WaitBridge>,
attachments: Arc<crate::attachments::AttachmentStore>, attachments: Arc<crate::attachments::AttachmentStore>,
phone: Arc<crate::phone::PhoneStore>, phone: Arc<crate::phone::PhoneStore>,
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>, token: Option<String>,
agent_token: Option<String>, agent_token: Option<String>,
ingest_token: Option<String>, ingest_token: Option<String>,
@@ -182,6 +202,9 @@ impl ClawState {
bootstrap, bootstrap,
hub, hub,
steer, steer,
pause,
abort,
jobs,
backends, backends,
settings, settings,
identity, identity,
@@ -190,6 +213,7 @@ impl ClawState {
bridge, bridge,
attachments, attachments,
phone, phone,
sandbox,
token, token,
agent_token, agent_token,
ingest_token, ingest_token,
@@ -198,7 +222,8 @@ impl ClawState {
} }
/// Every dispatch key with a record — interactive and forge alike, /// Every dispatch key with a record — interactive and forge alike,
/// both dispatchers share one store — with its status. /// both dispatchers share one store — with its status and whether
/// the pause gate holds it.
pub fn sessions(&self) -> Result<Vec<Value>, DispatchError> { pub fn sessions(&self) -> Result<Vec<Value>, DispatchError> {
let mut sessions = Vec::new(); let mut sessions = Vec::new();
for key in self.store.keys()? { for key in self.store.keys()? {
@@ -209,6 +234,7 @@ impl ClawState {
"revision": status.revision, "revision": status.revision,
"inbox_depth": status.inbox_depth, "inbox_depth": status.inbox_depth,
"last_outcome": status.last_outcome, "last_outcome": status.last_outcome,
"paused": self.pause.is_paused(status.key.as_str()),
})); }));
} }
Ok(sessions) Ok(sessions)
@@ -229,6 +255,12 @@ impl ClawState {
// leaves the transcript alone: the purge below is the one step this // leaves the transcript alone: the purge below is the one step this
// side cannot undo, and it must never run for a session the 409 kept. // side cannot undo, and it must never run for a session the 409 kept.
let existed = self.dispatcher.forget(key)?; let existed = self.dispatcher.forget(key)?;
// The pause hold goes with the record: a key re-created under
// the same name starts unpaused. Best-effort — the record and
// the transcript are already gone, so a settings-row failure
// here must not pretend the delete failed; a leftover row only
// holds a session that does not exist.
let _ = self.pause.resume(key.as_str());
// Then the history, unconditionally — including the `Ok(false)` path, // Then the history, unconditionally — including the `Ok(false)` path,
// where a record already gone left the transcript behind. Deleting // where a record already gone left the transcript behind. Deleting
// that transcript is the repair: a retried DELETE finishes a half-done // that transcript is the repair: a retried DELETE finishes a half-done
@@ -258,6 +290,17 @@ impl ClawState {
&self.steer &self.steer
} }
/// The pause gate: the pause/resume routes write it, the sessions
/// listing reads it.
pub fn pause(&self) -> &PauseSet {
&self.pause
}
/// The abort registry: the abort route signals it.
pub fn aborts(&self) -> &AbortRegistry {
&self.abort
}
/// The configured model — the shim's echo default. /// The configured model — the shim's echo default.
/// The backend registry: the provider list and the active pair. /// The backend registry: the provider list and the active pair.
pub fn backends(&self) -> &BackendRegistry { pub fn backends(&self) -> &BackendRegistry {
@@ -289,6 +332,11 @@ impl ClawState {
pub fn watches(&self) -> &ClawStore { pub fn watches(&self) -> &ClawStore {
&self.watches &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 /// The app router: `/healthz` open, `/v1` behind the bearer check when
@@ -297,6 +345,9 @@ pub fn router(state: ClawState) -> Router {
let v1 = Router::new() let v1 = Router::new()
.route("/sessions", get(sessions).post(sessions_create)) .route("/sessions", get(sessions).post(sessions_create))
.route("/sessions/{key}", delete(session_delete)) .route("/sessions/{key}", delete(session_delete))
.route("/sessions/{key}/pause", post(session_pause))
.route("/sessions/{key}/resume", post(session_resume))
.route("/sessions/{key}/abort", post(session_abort))
.route( .route(
"/sessions/{key}/messages", "/sessions/{key}/messages",
post(messages).layer(axum::extract::DefaultBodyLimit::max(MAX_MESSAGE_BODY_BYTES)), post(messages).layer(axum::extract::DefaultBodyLimit::max(MAX_MESSAGE_BODY_BYTES)),
@@ -343,6 +394,7 @@ pub fn router(state: ClawState) -> Router {
) )
.route("/providers/{id}", delete(providers_remove)) .route("/providers/{id}", delete(providers_remove))
.route("/providers/{id}/models", get(providers_models)) .route("/providers/{id}/models", get(providers_models))
.route("/sandbox", get(sandbox_get).put(sandbox_put))
.route( .route(
"/chat/completions", "/chat/completions",
post(crate::openai::chat_completions) post(crate::openai::chat_completions)
@@ -622,6 +674,201 @@ async fn session_delete(State(state): State<ClawState>, Path(key): Path<String>)
} }
} }
/// The shared shape of the pause/resume routes' answer.
fn pause_answer(key: &ResourceKey, paused: bool) -> Response {
(
StatusCode::OK,
Json(json!({ "key": key.as_str(), "paused": paused })),
)
.into_response()
}
/// `POST /v1/sessions/{key}/pause`: hold the key's dispatch. Queued
/// work stays in the inbox, new work ingests as always, and every
/// driver passes the key by until resume lifts the hold — a live turn
/// is not cut by this (the lease predates the hold); the abort route
/// is what cuts one. 404 when the inventory has no such key.
async fn session_pause(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
// The key path's shape: one segment is the whole key, trimmed — a
// key carrying `/` arrives only percent-encoded, which is what
// every client of this surface sends. Empty after the trim is the
// 400 the delete route answers too.
let key = key.trim();
if key.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key is required"})),
)
.into_response();
}
let key = ResourceKey::from(key);
match state.store.load(&key) {
Ok(Some(_)) => {}
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": format!("no session {:?}", key.as_str())})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
}
match state.pause.pause(key.as_str()) {
Ok(_) => pause_answer(&key, true),
Err(err) => internal_error(err).into_response(),
}
}
/// `POST /v1/sessions/{key}/resume`: lift the hold. The key's pending
/// work dispatches on the first driver pass after this — the debounce
/// window it may still owe runs first, as it always did. Idempotent:
/// resuming an unheld key answers `{"paused": false}`, and 404s only
/// when the inventory has no such key at all.
async fn session_resume(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
// The key path's shape: one segment is the whole key, trimmed — a
// key carrying `/` arrives only percent-encoded, which is what
// every client of this surface sends. Empty after the trim is the
// 400 the delete route answers too.
let key = key.trim();
if key.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key is required"})),
)
.into_response();
}
let key = ResourceKey::from(key);
match state.store.load(&key) {
Ok(Some(_)) => {}
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": format!("no session {:?}", key.as_str())})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
}
match state.pause.resume(key.as_str()) {
Ok(_) => pause_answer(&key, false),
Err(err) => internal_error(err).into_response(),
}
}
/// `POST /v1/sessions/{key}/abort`: stop the key's work now. Two shapes,
/// one route:
///
/// - a live lease: the dispatch is signalled through the abort registry
/// and its turn is dropped at its current await — the handler repairs
/// the dangling calls, stashes what it committed, and releases the
/// lease as superseded. Work that sat behind the turn in the inbox
/// stays there, still queued.
/// - an idle key with a queue: the queue is drained and dropped under
/// a throwaway lease, so nothing dispatches; a `job:` key's row moves
/// to failed/`aborted` with it, the row being the jobs' truth.
///
/// The answer carries what happened: `{"key", "cut", "dropped"}`. A
/// `cut` of `false` with a zero `dropped` is the idempotent no-op —
/// nothing was running and nothing was queued. The whole route is
/// race-tolerant by construction: a key that leaves the leased state
/// between the read and the signal drains through the idle path, and a
/// key that enters it lands in the dispatcher's own conflicts below.
async fn session_abort(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
// The key path's shape: one segment is the whole key, trimmed — a
// key carrying `/` arrives only percent-encoded, which is what
// every client of this surface sends. Empty after the trim is the
// 400 the delete route answers too.
let key = key.trim();
if key.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key is required"})),
)
.into_response();
}
let key = ResourceKey::from(key);
let record = match state.store.load(&key) {
Ok(Some(record)) => record,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": format!("no session {:?}", key.as_str())})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
};
let leased = record.lease.is_some();
if leased && state.aborts().signal(key.as_str()) {
// A job row moves with its cut: the handler's own abort path
// lands it, so nothing to do here but the answer.
return (
StatusCode::OK,
Json(json!({ "key": key.as_str(), "cut": true, "dropped": 0 })),
)
.into_response();
}
// Idle, or leased-but-unsignalable (the turn released between the
// read and the signal, or the lease lapsed unswept — `acquire`
// sweeps both). Whatever is queued drains and drops; nothing runs.
if record.inbox.is_empty() {
return (
StatusCode::OK,
Json(json!({ "key": key.as_str(), "cut": false, "dropped": 0 })),
)
.into_response();
}
let (lease, _session) = match state.dispatcher.acquire(key.clone(), "claw-abort") {
Ok(acquired) => acquired,
// The key went busy between the read and the acquire: a turn
// holds it now, and that turn is what a retry aborts.
Err(DispatchError::Conflict(_)) | Err(DispatchError::AtCapacity { .. }) => {
return (
StatusCode::CONFLICT,
Json(json!({"error": format!(
"session {:?} took a lease mid-abort; retry to cut it",
key.as_str()
)})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
};
let dropped = match state.dispatcher.poll_inbox(&lease) {
Ok(items) => items.len(),
Err(err) => return internal_error(err).into_response(),
};
if let Err(err) = state.dispatcher.release(&lease, Outcome::Superseded) {
return internal_error(err).into_response();
}
// The jobs' truth moves with the queue it lost: a row whose
// delivery was just dropped is failed, not queued, or it would sit
// live forever with nothing to run it. Quietly — the operator who
// aborted it is the one being told.
if let Some((instance, job_id)) = crate::jobs::parse_job_key(&key)
&& let Ok(Some(job)) = state.jobs.job(job_id)
&& job.status.is_live()
&& let Err(err) = state.jobs.fail(job_id, "aborted")
{
eprintln!("[claw] abort: job {job_id} on {instance:?} could not be failed: {err}");
}
// The transcript shows the cut: the dropped questions are already
// recorded, and without this marker they read as questions the
// daemon ignored.
state.hub.emit(
&key,
TurnEvent::TurnDone {
reply: None,
outcome: "aborted".to_owned(),
},
);
(
StatusCode::OK,
Json(json!({ "key": key.as_str(), "cut": false, "dropped": dropped })),
)
.into_response()
}
/// The setup badge: which of SOUL.md and USER.md exist, read live — a /// The setup badge: which of SOUL.md and USER.md exist, read live — a
/// UI badges first-run setup from it while the onboarding offer is /// UI badges first-run setup from it while the onboarding offer is
/// still open. /// still open.
@@ -652,12 +899,20 @@ pub const MAX_INBOUND_IMAGES: usize = 8;
pub const MAX_MESSAGE_BODY_BYTES: usize = pub const MAX_MESSAGE_BODY_BYTES: usize =
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024; MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
/// `{"text": "..."}` — one chat message, plus the images it carries. /// `{"text": "..."}` — one chat message, plus the images and the chip
/// A body without `images` is the old shape, unchanged. /// payloads it carries. A body without `images` or `pastes` is the old
/// shape, unchanged.
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct MessageBody { 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, 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 /// The message's inline images, each the full MIME type plus bare
/// base64. The route checks the budget, then the dispatch copies /// base64. The route checks the budget, then the dispatch copies
/// the bytes into the attachment store — the stream carries ids, /// the bytes into the attachment store — the stream carries ids,
@@ -729,6 +984,7 @@ async fn messages(
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event( if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
key.as_str(), key.as_str(),
&body.text, &body.text,
&body.pastes,
&body.images, &body.images,
)) { )) {
return ( return (
@@ -839,19 +1095,14 @@ async fn events(
let key = ResourceKey::from(key); let key = ResourceKey::from(key);
let (replay, mut receiver) = match query.since { let (replay, mut receiver) = match query.since {
Some(cursor) => state.hub.replay_after(&key, cursor, TAIL_WINDOW), Some(cursor) => state.hub.replay_after(&key, cursor, TAIL_WINDOW),
None => state.hub.replay_tail(&key, TAIL_WINDOW), // A tail window can open mid-turn, and a transcript that opens
// on a reply with no question above it reads as a bug. The hub
// widens the window back to the turn's first event. A cursor
// replay is exact by construction and is never cut.
None => state.hub.replay_tail_turn(&key, TAIL_WINDOW),
}; };
let stale = replay.stale; let stale = replay.stale;
// A tail window can open mid-turn (the oldest events in it belong let history = replay.events;
// to a turn that started before the window), and a transcript that
// opens on a reply with no question above it reads as a bug. Cut
// back to the window's first question. A cursor replay is exact by
// construction and is never cut.
let history = if query.since.is_none() {
snap_to_turn(replay.events)
} else {
replay.events
};
// The pump decouples the broadcast channel from the SSE body: the // The pump decouples the broadcast channel from the SSE body: the
// client's disconnect closes the body, which fails the send, which // client's disconnect closes the body, which fails the send, which
// ends the pump. The stream never ends on its own — a chat UI // ends the pump. The stream never ends on its own — a chat UI
@@ -999,21 +1250,6 @@ fn sse_event(seq: i64, turn: TurnEvent) -> SseEvent {
} }
} }
/// A replay window cut back to its first question: the events before
/// it belong to a turn whose start the window did not reach, and half a
/// turn reads as a bug. A window with no question in it (one turn
/// longer than the window) is returned whole — showing it beats showing
/// nothing, and the walk back through history continues above it.
fn snap_to_turn(mut events: Vec<crate::hub::SeqEvent>) -> Vec<crate::hub::SeqEvent> {
match events
.iter()
.position(|(_, event)| matches!(event, TurnEvent::UserMessage { .. }))
{
Some(index) if index > 0 => events.split_off(index),
_ => events,
}
}
/// The history route's query: the page ends at `before` (the seq of the /// The history route's query: the page ends at `before` (the seq of the
/// oldest event the client holds; absent reads from the newest), and /// oldest event the client holds; absent reads from the newest), and
/// `limit` is the most events it may hold before the page is widened /// `limit` is the most events it may hold before the page is widened
@@ -1031,24 +1267,30 @@ struct HistoryQuery {
/// through a session's history. The page starts on a turn boundary and /// through a session's history. The page starts on a turn boundary and
/// ends exactly at `before`, so pages stack without gaps or overlaps. /// ends exactly at `before`, so pages stack without gaps or overlaps.
/// The response's `more` says whether anything precedes it: `false` /// The response's `more` says whether anything precedes it: `false`
/// means the client has reached the session's first event. /// means the client has reached the session's first event, and
/// `read_only` says the page is a snapshot rather than a record a
/// message could extend.
///
/// A key outside the resident context has no hub record: its handler
/// never streams. The daemon still holds the session the engine
/// checkpointed, so the route serves that history instead, through
/// [`crate::thread`] — the same page shape, cut the same way, so a chat
/// surface renders a finished forge thread with the renderer it already
/// has. Those keys take no message ([`messages`] refuses them), which
/// is what `read_only` tells the client.
async fn session_history( async fn session_history(
State(state): State<ClawState>, State(state): State<ClawState>,
Path(key): Path<String>, Path(key): Path<String>,
Query(query): Query<HistoryQuery>, Query(query): Query<HistoryQuery>,
) -> Response { ) -> Response {
if !crate::interactive::is_resident_key(&key) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key must start with interactive:, task:, or phone:"})),
)
.into_response();
}
let key = ResourceKey::from(key); let key = ResourceKey::from(key);
let limit = query let limit = query
.limit .limit
.unwrap_or(HISTORY_PAGE) .unwrap_or(HISTORY_PAGE)
.clamp(1, HISTORY_PAGE_MAX); .clamp(1, HISTORY_PAGE_MAX);
if !crate::interactive::is_resident_key(key.as_str()) {
return stashed_history(&state, &key, query.before, limit);
}
let page = state.hub.replay_turn_before(&key, query.before, limit); let page = state.hub.replay_turn_before(&key, query.before, limit);
// Whether anything sits below the page: a lookup, not a read. // Whether anything sits below the page: a lookup, not a read.
let more = match page.first().map(|(seq, _)| *seq) { let more = match page.first().map(|(seq, _)| *seq) {
@@ -1059,7 +1301,48 @@ async fn session_history(
.into_iter() .into_iter()
.map(|(seq, event)| json!({"seq": seq, "event": event})) .map(|(seq, event)| json!({"seq": seq, "event": event}))
.collect(); .collect();
Json(json!({"events": events, "more": more})).into_response() Json(json!({"events": events, "more": more, "read_only": false})).into_response()
}
/// The snapshot page for a key the resident context does not own: the
/// record's session stash, turned back into turn events. A key with no
/// record, or a record the engine never checkpointed, has nothing to
/// show and answers an empty page rather than a 404 — the inventory
/// lists the key, and an empty thread is the truth about it.
fn stashed_history(
state: &ClawState,
key: &ResourceKey,
before: Option<i64>,
limit: usize,
) -> Response {
let record = match state.store.load(key) {
Ok(record) => record,
Err(err) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": format!("session lookup for {key} failed: {err}")})),
)
.into_response();
}
};
let (page, more) = match record.as_ref().and_then(|record| record.session.as_ref()) {
Some(session) => {
let outcome = record
.as_ref()
.and_then(|record| record.last_outcome.as_ref());
let leased = record
.as_ref()
.is_some_and(|record| record.state == rhema_rsd::KeyState::Leased);
let events = crate::thread::events(&session.core, outcome, leased);
crate::thread::page(&events, before, limit)
}
None => (Vec::new(), false),
};
let events: Vec<Value> = page
.into_iter()
.map(|(seq, event)| json!({"seq": seq, "event": event}))
.collect();
Json(json!({"events": events, "more": more, "read_only": true})).into_response()
} }
async fn watches_list(State(state): State<ClawState>) -> Result<Json<Value>, (StatusCode, String)> { async fn watches_list(State(state): State<ClawState>) -> Result<Json<Value>, (StatusCode, String)> {
@@ -1982,6 +2265,88 @@ 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()),
"private_key_set": choice
.private_key
.as_deref()
.is_some_and(|key| !key.is_empty()),
"host": choice.host,
"ssh_workspace": choice.workspace,
"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` and `private_key` are write-only;
/// `clear_token` and `clear_private_key` drop the stored ones. 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 clear_private_key = body["clear_private_key"].as_bool().unwrap_or(false);
let private_key = if clear_private_key {
None
} else {
body["private_key"]
.as_str()
.map(str::to_owned)
.or_else(|| current.private_key.clone())
};
let choice = crate::sandbox::SandboxChoice {
kind,
url: body["url"]
.as_str()
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
host: body["host"]
.as_str()
.map(str::to_owned)
.or_else(|| current.host.clone()),
workspace: body["workspace"]
.as_str()
.map(str::to_owned)
.or_else(|| current.workspace.clone()),
private_key,
};
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. /// `GET /v1/providers`: every constructible backend and the active pair.
/// The active pair is runtime state — the config file seeded it, the /// The active pair is runtime state — the config file seeded it, the
/// settings store owns it now. Each provider is one instance, named by /// settings store owns it now. Each provider is one instance, named by
@@ -2220,6 +2585,7 @@ async fn agent_put(
}; };
let texts = crate::identity::IdentityTexts { let texts = crate::identity::IdentityTexts {
name: field(body["name"].as_str(), &current.name), name: field(body["name"].as_str(), &current.name),
email: field(body["email"].as_str(), &current.email),
mark: field(body["mark"].as_str(), &current.mark), mark: field(body["mark"].as_str(), &current.mark),
initials: field(body["initials"].as_str(), &current.initials), initials: field(body["initials"].as_str(), &current.initials),
tagline: field(body["tagline"].as_str(), &current.tagline), tagline: field(body["tagline"].as_str(), &current.tagline),
+147 -5
View File
@@ -32,6 +32,7 @@ use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::sync::broadcast; use tokio::sync::broadcast;
use crate::paste::PasteSpan;
use crate::turn_store::{TurnStore, TurnStoreError}; use crate::turn_store::{TurnStore, TurnStoreError};
/// How many events a subscriber may trail by before the oldest drop. /// How many events a subscriber may trail by before the oldest drop.
@@ -74,13 +75,23 @@ pub enum TurnEvent {
/// shows its own messages as it sends them, and skips the live /// shows its own messages as it sends them, and skips the live
/// echo. /// echo.
UserMessage { 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, text: String,
/// The batch's images, in arrival order, as the attachment /// The batch's images, in arrival order, as the attachment
/// store holds them. `default` because rows recorded before /// store holds them. `default` because rows recorded before
/// images rode the transcript carry no field. /// images rode the transcript carry no field.
#[serde(default)] #[serde(default)]
images: Vec<UserImage>, 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. /// A piece of the model's reasoning trace, in stream order.
ThinkingDelta { ThinkingDelta {
@@ -118,7 +129,8 @@ pub enum TurnEvent {
/// The turn's final assistant text, when it produced one. /// The turn's final assistant text, when it produced one.
reply: Option<String>, reply: Option<String>,
/// `handled` or `failed` — or `steered`, when a chat message /// `handled` or `failed` — or `steered`, when a chat message
/// cut the turn short and a next turn runs instead of it. /// cut the turn short and a next turn runs instead of it — or
/// `aborted`, when the operator cut it and nothing follows.
outcome: String, outcome: String,
}, },
/// The agent asked the human something only they can answer: a /// The agent asked the human something only they can answer: a
@@ -319,6 +331,42 @@ impl EventHub {
) )
} }
/// The newest page, cut with the live receiver, starting on a turn's
/// first event: the window a client with no cache opens with. It
/// widens by doubling while the window falls inside one turn, up to
/// [`HISTORY_SCAN_CAP`], and a record that opens inside a turn comes
/// back whole rather than as a fragment. A long agent turn streams
/// hundreds of deltas past the file it handed over, so a reload that
/// landed mid-reply used to drop what the turn began with, images
/// among it.
pub fn replay_tail_turn(
&self,
key: &ResourceKey,
limit: usize,
) -> (Replay, broadcast::Receiver<TurnEvent>) {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
let entry = Self::entry(&mut entries, key, self.capacity);
let store = self.record_store.as_deref();
let mut want = limit.max(1);
let events = loop {
let window = Self::record_tail(store, entry, key, want);
let opens_on_turn = window
.first()
.is_some_and(|(_, event)| matches!(event, TurnEvent::UserMessage { .. }));
if opens_on_turn || window.len() < want || want >= HISTORY_SCAN_CAP {
break window;
}
want = (want * 2).min(HISTORY_SCAN_CAP);
};
(
Replay {
events,
stale: false,
},
entry.sender.subscribe(),
)
}
/// One page of the record older than `before` (`None` reads from the /// One page of the record older than `before` (`None` reads from the
/// newest), ending exactly at `before` and starting at a turn's /// newest), ending exactly at `before` and starting at a turn's
/// first event — the page a client walking backward asks for, so a /// first event — the page a client walking backward asks for, so a
@@ -565,10 +613,27 @@ mod tests {
serde_json::to_string(&TurnEvent::UserMessage { serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(), text: "hi".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}) })
.unwrap(), .unwrap(),
r#"{"type":"user_message","text":"hi","images":[]}"# 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!( assert_eq!(
serde_json::to_string(&TurnEvent::ToolResult { serde_json::to_string(&TurnEvent::ToolResult {
name: "bash".into(), name: "bash".into(),
@@ -600,7 +665,8 @@ mod tests {
event, event,
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
); );
} }
@@ -614,7 +680,8 @@ mod tests {
assert_eq!( assert_eq!(
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "x".into(), text: "x".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
.kind(), .kind(),
"user_message" "user_message"
@@ -659,6 +726,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
); );
hub.emit(&key, text("hi")); hub.emit(&key, text("hi"));
@@ -669,7 +737,8 @@ mod tests {
vec![ vec![
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
}, },
text("hi"), text("hi"),
], ],
@@ -795,6 +864,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "earlier".into(), text: "earlier".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
); );
let (history, mut receiver) = hub.subscribe_with_history(&key); let (history, mut receiver) = hub.subscribe_with_history(&key);
@@ -882,6 +952,77 @@ mod tests {
assert_eq!(replay.events, vec![(4, text("4")), (5, text("5"))]); assert_eq!(replay.events, vec![(4, text("4")), (5, text("5"))]);
} }
/// The tail a fresh client opens with starts on a question even when
/// the newest turn is longer than the window: a reload must not land
/// on the middle of a reply, where the file the turn handed over (and
/// the question that asked for it) are behind the window.
#[test]
fn a_tail_window_inside_one_turn_widens_to_the_question() {
let hub = EventHub::default();
let key = key("longturn");
hub.emit(
&key,
TurnEvent::UserMessage {
text: "q".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
for n in 0..5 {
hub.emit(&key, text(&n.to_string()));
}
// A window of 2 from the end sits inside the turn; the widened
// one opens on the question and holds the whole turn.
let (replay, _) = hub.replay_tail_turn(&key, 2);
assert!(!replay.stale);
assert_eq!(
replay.events.len(),
6,
"the whole turn: {:?}",
replay.events
);
assert_eq!(replay.events[0].0, 0);
assert!(matches!(replay.events[0].1, TurnEvent::UserMessage { .. }));
}
/// The widening stops at the record's start: a record with no
/// question in it replays whole instead of looping after the cap.
#[test]
fn a_tail_window_with_no_question_replays_the_record_once() {
let hub = EventHub::default();
let key = key("questionless");
for n in 0..6 {
hub.emit(&key, text(&n.to_string()));
}
let (replay, _) = hub.replay_tail_turn(&key, 2);
assert_eq!(replay.events.len(), 6);
assert_eq!(replay.events[0].0, 0, "the record's first event");
}
/// A tail that already opens on a question is left exactly as asked:
/// no widening past the window the store served.
#[test]
fn a_tail_window_on_a_question_is_not_widened() {
let hub = EventHub::default();
let key = key("plain");
for turn in 0..3 {
hub.emit(
&key,
TurnEvent::UserMessage {
text: format!("q{turn}"),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text(&format!("a{turn}")));
hub.emit(&key, done(&format!("a{turn}")));
}
// Seqs 6, 7, 8: the third turn, opening on its question.
let (replay, _) = hub.replay_tail_turn(&key, 3);
assert_eq!(replay.events.len(), 3);
assert_eq!(replay.events[0].0, 6);
}
/// Backward paging: each page ends where the last began and starts /// Backward paging: each page ends where the last began and starts
/// on a turn boundary, so a transcript stacks pages without gaps, /// on a turn boundary, so a transcript stacks pages without gaps,
/// overlaps, or a fragment at its top. /// overlaps, or a fragment at its top.
@@ -896,6 +1037,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: format!("q{turn}"), text: format!("q{turn}"),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
); );
hub.emit(&key, text(&format!("a{turn}"))); hub.emit(&key, text(&format!("a{turn}")));
+24 -7
View File
@@ -14,7 +14,8 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -44,9 +45,13 @@ pub const MAX_IMAGE_BYTES: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentIdentity { pub struct AgentIdentity {
/// The agent's display name: message author, window title, /// The agent's display name: message author, window title,
/// notifications. /// notifications, and the commit author name in workspaces.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>, pub name: Option<String>,
/// The address commits carry in workspaces; also the mail-like
/// identity other surfaces may quote.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
/// The glyph or emoji in the rail, the favicon, the empty states. /// The glyph or emoji in the rail, the favicon, the empty states.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub mark: Option<String>, pub mark: Option<String>,
@@ -69,6 +74,7 @@ pub struct AgentIdentity {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct IdentityTexts { pub struct IdentityTexts {
pub name: Option<String>, pub name: Option<String>,
pub email: Option<String>,
pub mark: Option<String>, pub mark: Option<String>,
pub initials: Option<String>, pub initials: Option<String>,
pub tagline: Option<String>, pub tagline: Option<String>,
@@ -120,6 +126,7 @@ impl IdentityStore {
pub fn get(&self) -> Result<AgentIdentity, IdentityError> { pub fn get(&self) -> Result<AgentIdentity, IdentityError> {
Ok(AgentIdentity { Ok(AgentIdentity {
name: self.text("name")?, name: self.text("name")?,
email: self.text("email")?,
mark: self.text("mark")?, mark: self.text("mark")?,
initials: self.text("initials")?, initials: self.text("initials")?,
tagline: self.text("tagline")?, tagline: self.text("tagline")?,
@@ -135,6 +142,7 @@ impl IdentityStore {
pub fn set_texts(&self, texts: &IdentityTexts) -> Result<AgentIdentity, IdentityError> { pub fn set_texts(&self, texts: &IdentityTexts) -> Result<AgentIdentity, IdentityError> {
let fields = [ let fields = [
("name", &texts.name, 64usize), ("name", &texts.name, 64usize),
("email", &texts.email, 120),
("mark", &texts.mark, 8), ("mark", &texts.mark, 8),
("initials", &texts.initials, 4), ("initials", &texts.initials, 4),
("tagline", &texts.tagline, 120), ("tagline", &texts.tagline, 120),
@@ -263,6 +271,7 @@ impl ToolOp for IdentitySet {
}; };
let texts = IdentityTexts { let texts = IdentityTexts {
name: field(args["name"].as_str(), current.name.as_deref()), name: field(args["name"].as_str(), current.name.as_deref()),
email: field(args["email"].as_str(), current.email.as_deref()),
mark: field(args["mark"].as_str(), current.mark.as_deref()), mark: field(args["mark"].as_str(), current.mark.as_deref()),
initials: field(args["initials"].as_str(), current.initials.as_deref()), initials: field(args["initials"].as_str(), current.initials.as_deref()),
tagline: field(args["tagline"].as_str(), current.tagline.as_deref()), tagline: field(args["tagline"].as_str(), current.tagline.as_deref()),
@@ -345,10 +354,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The identity tool set over `store`: `identity_set` — its spec from /// The identity tool set over `store`: `identity_set` — its spec from
/// the embedded manifest, the operation compiled here. /// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> ToolRegistry { pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools( let (tools, skipped) =
MANIFESTS, crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into()));
&builtins(store, workspace.into()),
);
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the identity_set tool manifest must load: {skipped:?}" "the identity_set tool manifest must load: {skipped:?}"
@@ -363,7 +370,7 @@ pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> Too
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rhema_autonomous_agent::Allowlist; use crate::toolkit::Allowlist;
#[test] #[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() { fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
@@ -393,6 +400,7 @@ mod tests {
let saved = store let saved = store
.set_texts(&IdentityTexts { .set_texts(&IdentityTexts {
name: Some(" Kosmos ".to_owned()), name: Some(" Kosmos ".to_owned()),
email: Some("kosmos@example.net".to_owned()),
mark: Some("✦".to_owned()), mark: Some("✦".to_owned()),
initials: None, initials: None,
tagline: Some("order".to_owned()), tagline: Some("order".to_owned()),
@@ -400,6 +408,7 @@ mod tests {
}) })
.expect("the texts save"); .expect("the texts save");
assert_eq!(saved.name.as_deref(), Some("Kosmos"), "trimmed"); assert_eq!(saved.name.as_deref(), Some("Kosmos"), "trimmed");
assert_eq!(saved.email.as_deref(), Some("kosmos@example.net"));
assert_eq!(saved.mark.as_deref(), Some("✦")); assert_eq!(saved.mark.as_deref(), Some("✦"));
assert_eq!(saved.initials, None); assert_eq!(saved.initials, None);
assert_eq!(saved.signoff, None, "an empty string clears"); assert_eq!(saved.signoff, None, "an empty string clears");
@@ -409,6 +418,7 @@ mod tests {
.set_texts(&IdentityTexts::default()) .set_texts(&IdentityTexts::default())
.expect("the clear saves"); .expect("the clear saves");
assert_eq!(cleared.name, None); assert_eq!(cleared.name, None);
assert_eq!(cleared.email, None);
} }
#[test] #[test]
@@ -485,6 +495,7 @@ mod tests {
let answer = tool let answer = tool
.invoke(json!({ .invoke(json!({
"name": "Kosmos", "name": "Kosmos",
"email": "kosmos@example.net",
"mark": "✦", "mark": "✦",
"avatar": "face.png", "avatar": "face.png",
})) }))
@@ -493,6 +504,7 @@ mod tests {
let answer: Value = serde_json::from_str(&answer).expect("parses"); let answer: Value = serde_json::from_str(&answer).expect("parses");
assert_eq!(answer["saved"], true); assert_eq!(answer["saved"], true);
assert_eq!(answer["identity"]["name"], "Kosmos"); assert_eq!(answer["identity"]["name"], "Kosmos");
assert_eq!(answer["identity"]["email"], "kosmos@example.net");
assert_eq!(answer["identity"]["avatar"], true); assert_eq!(answer["identity"]["avatar"], true);
let (bytes, content_type) = store let (bytes, content_type) = store
.image(ImageKind::Avatar) .image(ImageKind::Avatar)
@@ -506,6 +518,11 @@ mod tests {
.expect("saves"); .expect("saves");
let identity = store.get().expect("reads"); let identity = store.get().expect("reads");
assert_eq!(identity.name.as_deref(), Some("Kosmos"), "kept"); assert_eq!(identity.name.as_deref(), Some("Kosmos"), "kept");
assert_eq!(
identity.email.as_deref(),
Some("kosmos@example.net"),
"kept"
);
assert_eq!(identity.tagline.as_deref(), Some("order"), "added"); assert_eq!(identity.tagline.as_deref(), Some("order"), "added");
assert!(identity.avatar, "untouched by a text-only save"); assert!(identity.avatar, "untouched by a text-only save");
} }
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -17,7 +17,8 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -41,8 +42,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The coding-agent tool set over `store`: one tool, `coding_agent` — /// The coding-agent tool set over `store`: one tool, `coding_agent` —
/// its spec from the embedded manifest, the operation compiled here. /// its spec from the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<CodingJobStore>) -> ToolRegistry { pub fn registry(store: Arc<CodingJobStore>) -> ToolRegistry {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the coding_agent tool manifest must load: {skipped:?}" "the coding_agent tool manifest must load: {skipped:?}"
@@ -227,7 +227,7 @@ fn required<'a>(value: &'a Option<String>, complaint: &str) -> Result<&'a str, S
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rhema_autonomous_agent::Allowlist; use crate::toolkit::Allowlist;
#[test] #[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() { fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+159 -16
View File
@@ -13,7 +13,7 @@
//! instance and job resolve through the store, the workspace is the //! instance and job resolve through the store, the workspace is the
//! instance's path, the session blob (or a fresh agent) is loaded, 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 //! 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 //! the user's notifications; the turn itself streams nowhere, its
//! observability is the stderr tool log. //! observability is the stderr tool log.
//! //!
@@ -22,11 +22,13 @@
//! fails before any model call. The trust boundary is unchanged from //! fails before any model call. The trust boundary is unchanged from
//! the forge path — the bearer-gated surface and the instance list. //! the forge path — the bearer-gated surface and the instance list.
use std::num::NonZeroU32;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait}; 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_core::{Event as ModelEvent, EventSink};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey}; use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
@@ -34,6 +36,7 @@ use crate::handler::final_text;
use crate::interactive::passthrough_key_fn; use crate::interactive::passthrough_key_fn;
use crate::job_store::{CodingJobStore, JobStatus}; use crate::job_store::{CodingJobStore, JobStatus};
use crate::notifications::{DEFAULT_DEVICE, NotificationStore}; use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
use crate::sandbox::SandboxState;
/// The source name the coding jobs ingest under. /// The source name the coding jobs ingest under.
pub const JOBS_SOURCE: &str = "jobs"; pub const JOBS_SOURCE: &str = "jobs";
@@ -137,10 +140,19 @@ pub struct CodingJobHandler {
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>, store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>, notifications: Arc<NotificationStore>,
max_turn_steps: u32, max_turn_steps: NonZeroU32,
/// Whether the jobs run the bounded request view (the config's /// Whether the jobs run the bounded request view (the config's
/// `transcript`, on unless set false). /// `transcript`, on unless set false).
transcript: bool, transcript: bool,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>,
/// The abort registry the sessions' abort route signals: a live job
/// turn cut at its await stashes the conversation and lands the row
/// as failed with `aborted` (see [`crate::abort`]). Private by
/// default — a handler nobody shared a registry with never receives
/// a signal — and shared through [`CodingJobHandler::with_abort`].
abort: Arc<crate::abort::AbortRegistry>,
} }
impl CodingJobHandler { impl CodingJobHandler {
@@ -151,7 +163,7 @@ impl CodingJobHandler {
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>, store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>, notifications: Arc<NotificationStore>,
max_turn_steps: u32, max_turn_steps: NonZeroU32,
transcript: bool, transcript: bool,
) -> Self { ) -> Self {
Self { Self {
@@ -160,13 +172,36 @@ impl CodingJobHandler {
notifications, notifications,
max_turn_steps, max_turn_steps,
transcript, transcript,
sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
} }
} }
/// 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
}
/// Shares the abort registry with the HTTP surface: the abort route
/// signals it, and every job dispatch this handler runs listens on
/// it.
pub fn with_abort(mut self, abort: Arc<crate::abort::AbortRegistry>) -> Self {
self.abort = abort;
self
}
/// One dispatch, failed with a reason on any step; every failure /// One dispatch, failed with a reason on any step; every failure
/// lands in the job row before it lands in the outcome, so the /// lands in the job row before it lands in the outcome, so the
/// model's `status` read and the user's notification agree. /// model's `status` read and the user's notification agree.
async fn dispatch(&self, ctx: &mut SessionContext) -> Result<Outcome, String> { async fn dispatch(&self, ctx: &mut SessionContext) -> Result<Outcome, String> {
// The abort listener arms first, before any of the lookups and
// file work below: the route signals the moment it sees the
// lease, and a listener that arrives after the agent is built
// would let an early abort fall through as a no-op. One listener
// per dispatch is enough — the lease forbids a second one.
let mut abort = self.abort.listen(ctx.key.as_str());
// Poll to live, as every handler does — and here the poll is also // Poll to live, as every handler does — and here the poll is also
// what closes the dispatch. A job key carries exactly one kind of // what closes the dispatch. A job key carries exactly one kind of
// item, the row's own delivery, and those items are drained and // item, the row's own delivery, and those items are drained and
@@ -212,7 +247,11 @@ impl CodingJobHandler {
.map_err(|err| format!("job {job_id} could not start: {err}"))?; .map_err(|err| format!("job {job_id} could not start: {err}"))?;
let (provider, model) = self.backends.current(); 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; config.max_turn_steps = self.max_turn_steps;
// A job's stashed session carries across runs and only ever // A job's stashed session carries across runs and only ever
// grows; the view is what keeps a repeat run's steps cheap. // grows; the view is what keeps a repeat run's steps cheap.
@@ -221,8 +260,18 @@ impl CodingJobHandler {
config.transcript = self config.transcript = self
.transcript .transcript
.then(rhema_transcript::TranscriptSettings::default); .then(rhema_transcript::TranscriptSettings::default);
crate::vision::apply(&mut config); match &self.sandbox {
crate::mcp::apply(&mut config); 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 let stashed = self
.store .store
.session(&instance_name) .session(&instance_name)
@@ -236,9 +285,9 @@ impl CodingJobHandler {
self.fail(job_id, &instance_name, &reason); self.fail(job_id, &instance_name, &reason);
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| { .map_err(|err| {
let reason = format!("cannot start the coding agent for {instance_name:?}: {err}"); let reason = format!("cannot start the coding agent for {instance_name:?}: {err}");
@@ -248,21 +297,42 @@ impl CodingJobHandler {
// Commit-before-execute rides the dispatcher exactly as the // Commit-before-execute rides the dispatcher exactly as the
// forge handler's does: the intent is in the store before the // forge handler's does: the intent is in the store before the
// first tool runs, and a crash-left dangling call revives at // 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). // session).
agent.set_commit_hook(Some(ctx.commit_hook())); agent.set_commit_hook(Some(ctx.commit_hook()));
let mut sink = JobSink; let mut sink = JobSink;
let output = match agent.turn(&job.prompt, &mut sink, Arc::new(AllowAll)).await { // The abort listener rides the turn: a signal drops the future
Ok(output) => output, // at its current await — a streaming request, or a running
Err(err) => { // shell command, whose child dies with the drop. Armed at
let reason = format!("the coding turn for {instance_name:?} failed: {err}"); // dispatch entry, above.
let turned = tokio::select! {
output = agent.turn(&job.prompt, &mut sink) => {
Some(output.map_err(|err| {
format!("the coding turn for {instance_name:?} failed: {err}")
}))
}
_ = abort.wait() => None,
};
let output = match turned {
Some(Ok(output)) => output,
Some(Err(err)) => {
let reason = err;
// The conversation up to the failure is still the // The conversation up to the failure is still the
// instance's: saved, so a follow-up run continues it. // instance's: saved, so a follow-up run continues it.
self.save_session(&instance_name, &agent); self.save_session(&instance_name, &agent);
self.fail(job_id, &instance_name, &reason); self.fail(job_id, &instance_name, &reason);
return Ok(Outcome::Failed(reason)); return Ok(Outcome::Failed(reason));
} }
None => {
// Cut, not failed: the row says `aborted`, the
// conversation keeps whatever the turn committed, and
// the outcome is superseded — the work is no longer
// wanted, exactly the outcome's own words.
self.save_session(&instance_name, &agent);
self.fail(job_id, &instance_name, "aborted");
return Ok(Outcome::Superseded);
}
}; };
self.save_session(&instance_name, &agent); self.save_session(&instance_name, &agent);
let reply = final_text(&output.message).ok_or_else(|| { let reply = final_text(&output.message).ok_or_else(|| {
@@ -280,7 +350,7 @@ impl CodingJobHandler {
Ok(Outcome::Handled) 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()) { match serde_json::to_string(agent.session()) {
Ok(blob) => { Ok(blob) => {
let _ = self.store.save_session(instance, &blob); let _ = self.store.save_session(instance, &blob);
@@ -360,7 +430,80 @@ mod tests {
BackendRegistry::new(vec![Backend::headless("mock", provider)], None) BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"), .expect("a single mock backend always constructs"),
); );
CodingJobHandler::new(backends, store, notifications, 16, true) CodingJobHandler::new(
backends,
store,
notifications,
NonZeroU32::new(16).unwrap(),
true,
)
}
/// A provider whose one generation parks forever — the request an
/// abort interrupts, released only by the drop.
struct ParkingProvider;
#[rhema_autonomous_agent::async_trait]
impl rhema_core::ModelProvider for ParkingProvider {
async fn complete(
&self,
_request: rhema_core::ModelRequest,
_sink: &mut dyn rhema_core::EventSink,
) -> Result<rhema_core::ModelOutput, rhema_core::ProviderError> {
std::future::pending::<()>().await;
unreachable!("the pending future never resolves")
}
}
#[tokio::test]
async fn an_abort_signal_cuts_the_running_job_and_fails_the_row() {
let workspace = tempdir();
let store = Arc::new(CodingJobStore::in_memory().unwrap());
store
.add_instance("rhema", workspace.to_str().unwrap())
.unwrap();
let job = store.enqueue("rhema", "fix the lint").unwrap();
let notifications = Arc::new(NotificationStore::in_memory().unwrap());
let provider: Arc<dyn rhema_core::ModelProvider> = Arc::new(ParkingProvider);
let backends = Arc::new(
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"),
);
let abort = Arc::new(crate::abort::AbortRegistry::new());
let handler = CodingJobHandler::new(
backends,
store.clone(),
notifications.clone(),
NonZeroU32::new(16).unwrap(),
true,
)
.with_abort(abort.clone());
let (source, driver, _dispatcher) = harness(store.clone(), handler);
assert_eq!(source.detect().await.unwrap(), 1);
// The job runs off the test task; the abort lands while the
// generation is parked.
let pass = tokio::spawn(async move { driver.run_once().await });
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
while store.job(job.id).unwrap().unwrap().status != JobStatus::Running {
assert!(
tokio::time::Instant::now() < deadline,
"the job never started"
);
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
assert!(abort.signal(&job_key("rhema", job.id)));
// Superseded, not failed-and-retried: the work is no longer
// wanted, and the row — the jobs' truth — says aborted.
assert_eq!(pass.await.unwrap().unwrap(), vec![Outcome::Superseded]);
let row = store.job(job.id).unwrap().unwrap();
assert_eq!(row.status, JobStatus::Failed);
assert_eq!(row.result.as_deref(), Some("aborted"));
// The user still hears about it.
let pending = notifications.pending(DEFAULT_DEVICE, 0).unwrap();
assert_eq!(pending.len(), 1);
assert!(pending[0].body.contains("aborted"));
} }
fn reply(text: &str) -> ModelOutput { fn reply(text: &str) -> ModelOutput {
+21 -5
View File
@@ -32,9 +32,13 @@
//! - [`turn_store`] — the turn-history table: what each key's stream //! - [`turn_store`] — the turn-history table: what each key's stream
//! streamed, appended per event, replayed whole after a restart //! streamed, appended per event, replayed whole after a restart
//! - [`hub`] — the event hub: per-key record and broadcast of turn events //! - [`hub`] — the event hub: per-key record and broadcast of turn events
//! - [`identity`] — the agent's presentation identity: name, mark, //! - [`identity`] — the agent's presentation identity: name, email,
//! images, served over `/v1/agent` and settable by the agent itself //! mark, images, served over `/v1/agent` and settable by the agent
//! through the `identity_set` tool //! itself through the `identity_set` tool
//! - [`git_identity`] — the boot-time git identity: `user.name` and
//! `user.email` into the daemon user's global git config, resolved
//! from config, then identity, then defaults, guarded against
//! hand-edited values
//! - [`consents`] — the consent table and wake bridge: a running turn //! - [`consents`] — the consent table and wake bridge: a running turn
//! asks the human (a secret to store, permission to act) and waits; //! asks the human (a secret to store, permission to act) and waits;
//! the chat surface answers through the consent routes //! the chat surface answers through the consent routes
@@ -42,6 +46,8 @@
//! workspace files handed to the human as fetchable cards //! workspace files handed to the human as fetchable cards
//! - [`phone`] — the phone state and command queue: reported status to //! - [`phone`] — the phone state and command queue: reported status to
//! read, consent-gated control actions the device executes //! 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 //! - [`watch_tools`] — the agent's watch-management tool set
//! - [`notify_tools`] — the `notify` tool: the queue a device polls //! - [`notify_tools`] — the `notify` tool: the queue a device polls
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task` //! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
@@ -64,6 +70,7 @@
#![forbid(unsafe_code)] #![forbid(unsafe_code)]
pub mod abort;
pub mod accounts_tools; pub mod accounts_tools;
pub mod attachments; pub mod attachments;
pub mod backends; pub mod backends;
@@ -74,6 +81,7 @@ pub mod daemon;
pub mod environment; pub mod environment;
pub mod extension; pub mod extension;
pub mod forge; pub mod forge;
pub mod git_identity;
pub mod handler; pub mod handler;
pub mod http; pub mod http;
pub mod hub; pub mod hub;
@@ -88,12 +96,17 @@ pub mod mock;
pub mod notifications; pub mod notifications;
pub mod notify_tools; pub mod notify_tools;
pub mod openai; pub mod openai;
pub mod paste;
pub mod pause;
pub mod phone; pub mod phone;
pub mod sandbox;
pub mod settings; pub mod settings;
pub mod steer; pub mod steer;
pub mod task_source; pub mod task_source;
pub mod task_store; pub mod task_store;
pub mod task_tools; pub mod task_tools;
pub mod thread;
pub mod toolkit;
pub mod turn_store; pub mod turn_store;
pub(crate) mod vision; pub(crate) mod vision;
pub mod watch_store; pub mod watch_store;
@@ -105,7 +118,7 @@ pub use bootstrap::{
render_system, render_system,
}; };
pub use config::{ClawConfig, ConfigError}; 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 environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes}; pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource; pub use forge::ForgeSource;
@@ -117,8 +130,11 @@ pub use interactive::InteractiveHandler;
pub use mock::MockLoop; pub use mock::MockLoop;
pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError}; pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError};
pub use rhema_forge_integration::{ForgeKind, resolve_token}; pub use rhema_forge_integration::{ForgeKind, resolve_token};
pub use sandbox::{SandboxChoice, SandboxError, SandboxKind, SandboxState};
pub use settings::SettingsStore; pub use settings::SettingsStore;
pub use task_source::{TASKS_SOURCE, TaskScheduler}; pub use task_source::{TASKS_SOURCE, TaskScheduler};
pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError}; pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError};
pub use turn_store::{TurnStore, TurnStoreError}; 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,
};
+10 -5
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use clap::Parser; use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once}; use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::{DispatcherConfig, Outcome}; use rhema_rsd::Outcome;
/// `rhema-claw` — the resident forge-watching agent daemon. /// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@@ -74,9 +74,9 @@ async fn main() {
} }
if let Some(Command::Vision { args: rest }) = &args.command { if let Some(Command::Vision { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1); 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()); 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 { if let Err(err) = run(args).await {
eprintln!("error: {err}"); eprintln!("error: {err}");
@@ -100,6 +100,11 @@ async fn run(args: Args) -> Result<(), ClawError> {
} else { } else {
resolve_backends(&config)? resolve_backends(&config)?
}; };
// The workspace git identity: written in both shapes (a cron pass
// commits too), from deterministic boot code, guarded against
// hand-edited values. Never fatal — provisioning problems are the
// one stderr line this prints.
eprintln!("[claw] {}", rhema_claw::git_identity::boot(&config));
eprintln!( eprintln!(
"[claw] active {}/{}, db {}, http {}", "[claw] active {}/{}, db {}, http {}",
backends.active().0, backends.active().0,
@@ -135,7 +140,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on. // reads it next to the config that turns it on.
config.validate_surface()?; config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts"); 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 daemon.run().await
} }
} }
+8 -3
View File
@@ -9,7 +9,7 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use rhema_coding_agent::CodingAgentConfig; use rhema_host_agent::HostAgentConfig;
/// What one wiring produced, held for the process. /// What one wiring produced, held for the process.
struct Wired { struct Wired {
@@ -61,7 +61,7 @@ fn wired() -> Option<&'static Wired> {
/// init file, the socket, the token), the prompt's `mcp` lines, and /// init file, the socket, the token), the prompt's `mcp` lines, and
/// the persisted off switch. A frontend without wiring changes /// the persisted off switch. A frontend without wiring changes
/// nothing. /// nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) { pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else { let Some(wired) = wired() else {
return; return;
}; };
@@ -82,7 +82,12 @@ mod tests {
/// same map). /// same map).
#[test] #[test]
fn apply_without_any_wiring_leaves_the_config_alone() { 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(); let before = config.shell_env.clone();
apply(&mut config); apply(&mut config);
// The wiring only appears when the machine's global mcp.yaml // The wiring only appears when the machine's global mcp.yaml
+1
View File
@@ -65,6 +65,7 @@ impl ModelProvider for MockLoop {
message: Message { message: Message {
role: Role::Assistant, role: Role::Assistant,
content: vec![Content::Text(text)], content: vec![Content::Text(text)],
annotations: Default::default(),
}, },
stop_reason: StopReason::EndTurn, stop_reason: StopReason::EndTurn,
usage: Usage::default(), usage: Usage::default(),
+6 -8
View File
@@ -12,7 +12,8 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -33,8 +34,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[("notify", include_str!("../tools/notif
/// The notification tool set over `store`: `notify` — its spec from /// The notification tool set over `store`: `notify` — its spec from
/// the embedded manifest, the operation compiled here. /// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<NotificationStore>) -> ToolRegistry { pub fn registry(store: Arc<NotificationStore>) -> ToolRegistry {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the notify tool manifest must load: {skipped:?}" "the notify tool manifest must load: {skipped:?}"
@@ -102,7 +102,7 @@ mod tests {
async fn call(store: &Arc<NotificationStore>, args: Value) -> rhema_core::ToolResult { async fn call(store: &Arc<NotificationStore>, args: Value) -> rhema_core::ToolResult {
let resolver = let resolver =
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive()); registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
resolver resolver
.resolve( .resolve(
rhema_core::ToolCall { rhema_core::ToolCall {
@@ -118,13 +118,11 @@ mod tests {
#[test] #[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_spec() { fn the_manifest_loads_against_its_builtin_and_serves_the_spec() {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}"); assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 1); assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "notify"); assert_eq!(tools[0].spec().name, "notify");
let resolver = let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!( assert_eq!(
resolver.replay_safety("notify"), resolver.replay_safety("notify"),
rhema_core::ReplaySafety::Unsafe, rhema_core::ReplaySafety::Unsafe,
+1
View File
@@ -259,6 +259,7 @@ pub async fn chat_completions(
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event( if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
key.as_str(), key.as_str(),
&input.text, &input.text,
&[],
&input.images, &input.images,
)) { )) {
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()); return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
+215
View File
@@ -0,0 +1,215 @@
//! How a prompt carries a pasted payload: plain text plus a span note.
//!
//! A submitted prompt is plain text with each multi-line paste's payload
//! in place, exactly what the model reads, and the message carries a
//! [`PasteSpan`] list under [`CONSUMER`] saying which byte ranges the
//! chat surface draws as chips. No provider, no summarizer, and no other
//! consumer reads that note.
//!
//! `rhema-core` carried this until 0.4.2 moved display encodings out of
//! the engine. One frontend writes the note and the same frontend reads
//! it, so it belongs beside that frontend. The format is unchanged, so a
//! session stashed by either side loads in the other.
//!
//! [`PasteSpan`] replaced an embedded encoding, [`MARK`], payload,
//! [`MARK`], written into the text. Sessions written that way still
//! load. [`migrate`] rewrites one into plain text plus spans before the
//! first provider call.
use rhema_core::{Content, Message, Role};
use serde::{Deserialize, Serialize};
/// The object-replacement character: opens and closes one embedded
/// paste. Two marks always bracket a payload; a lone mark is literal
/// text.
pub const MARK: char = '\u{FFFC}';
/// The annotation key the chat surface records paste spans under on a
/// user message. No engine reads it.
pub const CONSUMER: &str = "rhema-code";
/// One paste's span in a message's plain text: the byte range its chip
/// stands for, and the payload's line count for the chip's label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasteSpan {
/// Start byte of the payload in the message text.
pub start: usize,
/// End byte of the payload in the message text, exclusive.
pub end: usize,
/// Lines in the payload, the chip's size label.
pub lines: usize,
}
/// The annotation's own shape, `{"pastes": [...]}`.
#[derive(Serialize, Deserialize)]
struct Pastes {
pastes: Vec<PasteSpan>,
}
/// Normalizes text that travels inside an embed or beside marks:
/// carriage returns to newlines, stray marks dropped, the scan must stay
/// unambiguous.
pub fn normalize(text: &str) -> String {
text.replace("\r\n", "\n")
.replace('\r', "\n")
.replace(MARK, "")
}
/// Records `spans` on `message` under [`CONSUMER`], replacing whatever
/// the same consumer left before; an empty list clears the note.
pub fn annotate(message: &mut Message, spans: &[PasteSpan]) {
if spans.is_empty() {
message.annotations.remove(CONSUMER);
return;
}
let value = serde_json::to_value(Pastes {
pastes: spans.to_vec(),
})
.expect("paste spans serialize");
message.annotate(CONSUMER, value);
}
/// The paste spans `message` carries, empty when it has none or when the
/// note is not this consumer's shape.
pub fn spans(message: &Message) -> Vec<PasteSpan> {
message
.annotation(CONSUMER)
.and_then(|value| serde_json::from_value::<Pastes>(value.clone()).ok())
.map(|pastes| pastes.pastes)
.unwrap_or_default()
}
/// Splits legacy embedded text into the plain form and its spans.
fn split_legacy(text: &str) -> (String, Vec<PasteSpan>) {
let mut plain = String::with_capacity(text.len());
let mut spans = Vec::new();
let mut rest = text;
while let Some(start) = rest.find(MARK) {
plain.push_str(&rest[..start]);
let after = &rest[start + MARK.len_utf8()..];
match after.find(MARK) {
Some(end) => {
let payload = &after[..end];
let begin = plain.len();
plain.push_str(payload);
spans.push(PasteSpan {
start: begin,
end: plain.len(),
lines: payload.lines().count(),
});
rest = &after[end + MARK.len_utf8()..];
}
// An unpaired mark is literal text.
None => {
plain.push(MARK);
rest = after;
}
}
}
plain.push_str(rest);
(plain, spans)
}
/// Rewrites the legacy embedded form in `history` into plain text plus
/// [`PasteSpan`] annotations, returning how many messages changed.
/// Sessions written before the annotation existed carry `MARK payload
/// MARK` inside the prompt; a resumed session must not send those marks
/// to a provider. Chips only ever lived in one user text block, so only
/// user messages are considered.
pub fn migrate(history: &mut [Message]) -> usize {
let mut changed = 0;
for message in history.iter_mut() {
if message.role != Role::User {
continue;
}
let mut spans = Vec::new();
let mut touched = false;
for content in message.content.iter_mut() {
if let Content::Text(text) = content
&& text.contains(MARK)
{
let (plain, found) = split_legacy(text);
*text = plain;
spans.extend(found);
touched = true;
}
}
if touched {
annotate(message, &spans);
changed += 1;
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spans_round_trip_through_the_annotation() {
let mut message = Message::text(Role::User, "look at l1\nl2 this");
assert!(spans(&message).is_empty());
let span = PasteSpan {
start: 8,
end: 13,
lines: 2,
};
annotate(&mut message, &[span]);
assert_eq!(spans(&message), vec![span]);
let json = serde_json::to_value(&message).unwrap();
assert_eq!(json["annotations"]["rhema-code"]["pastes"][0]["lines"], 2);
// Clearing the last span drops the whole note, so an
// annotation-free message keeps the pre-annotation wire shape.
annotate(&mut message, &[]);
assert!(spans(&message).is_empty());
assert!(
serde_json::to_value(&message)
.unwrap()
.get("annotations")
.is_none()
);
}
#[test]
fn migrate_rewrites_the_legacy_form_into_plain_text_and_spans() {
let payload = "l1\nl2\nl3\nl4";
let mut history = vec![
Message::text(Role::User, format!("look at {MARK}{payload}{MARK} this")),
Message::text(Role::Assistant, "on it"),
];
assert_eq!(migrate(&mut history), 1);
assert_eq!(
history[0].content,
Message::text(Role::User, format!("look at {payload} this")).content
);
assert_eq!(
spans(&history[0]),
vec![PasteSpan {
start: 8,
end: 8 + payload.len(),
lines: 4,
}]
);
// Idempotent: the plain form has no marks left to rewrite.
assert_eq!(migrate(&mut history), 0);
assert_eq!(history[1], Message::text(Role::Assistant, "on it"));
}
#[test]
fn an_unpaired_mark_migrates_as_literal_text() {
let mut history = vec![Message::text(Role::User, format!("a{MARK}b"))];
assert_eq!(migrate(&mut history), 1);
assert_eq!(
history[0].content,
Message::text(Role::User, "a\u{FFFC}b").content
);
assert!(spans(&history[0]).is_empty());
}
#[test]
fn normalize_flattens_carriage_returns_and_drops_marks() {
assert_eq!(normalize("p\r\nq\rs"), "p\nq\ns");
assert_eq!(normalize(&format!("a{MARK}b")), "ab");
}
}
+160
View File
@@ -0,0 +1,160 @@
//! The pause gate: dispatch keys the drivers hold — the inventory's
//! pause/resume, wired through the HTTP surface.
//!
//! Pausing is an operator's hold, not a dispatcher state: rhema-rsd's
//! state machine has idle, leased and re-acquire, and none of them means
//! "keep the events, run nothing". So the hold lives beside the store:
//! a set of keys, persisted in the settings table (`paused:<key>` rows,
//! the same table the active backend pair lives in), checked by every
//! driver's ownership predicate. A paused key ingests as always — its
//! inbox accumulates, its debounce opens, `admit` offers it — and every
//! driver declines it, pass after pass, until resume lifts the hold.
//! Nothing is dropped and nothing runs; the pending work dispatches on
//! the first pass after the resume.
//!
//! The in-memory set is the read side (a predicate call is a lock and a
//! contains); the settings rows are the truth a restart reloads. A live
//! turn is not paused by this — the lease it holds was granted before
//! the hold, and it runs to its end; the abort surface is what cuts a
//! running turn (see [`crate::abort`]).
use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, PoisonError};
use crate::settings::{SettingsError, SettingsStore};
/// The settings-row prefix one paused key lives under: `paused:<key>`,
/// value `1`. The prefix is stripped back off on load.
const SETTINGS_PREFIX: &str = "paused:";
/// The keys whose dispatch is on hold, in memory over the settings
/// table. Shareable: every method takes `&self`, the set serializes on
/// its mutex, and the whole thing rides an `Arc` through the daemon and
/// the HTTP surface.
pub struct PauseSet {
settings: Arc<SettingsStore>,
live: Mutex<BTreeSet<String>>,
}
impl PauseSet {
/// Loads the set over `settings`: every `paused:` row becomes one
/// held key. The daemon calls this once at assembly; a restart
/// resumes holding whatever was held.
pub fn load(settings: Arc<SettingsStore>) -> Result<Self, SettingsError> {
let rows = settings.rows_by_prefix(SETTINGS_PREFIX)?;
let live = rows
.into_iter()
.map(|(key, _)| key[SETTINGS_PREFIX.len()..].to_owned())
.collect::<BTreeSet<_>>();
Ok(Self {
settings,
live: Mutex::new(live),
})
}
/// Holds `key`'s dispatch. `Ok(true)` when the hold is new, `Ok(false)`
/// when the key was already held — the route can answer idempotent.
pub fn pause(&self, key: &str) -> Result<bool, SettingsError> {
let fresh = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned());
if fresh && let Err(err) = self.settings.set(&format!("{SETTINGS_PREFIX}{key}"), "1") {
// The hold is one fact in two places: a row that cannot be
// written takes the in-memory half back with it, so a
// restart cannot disagree with what the caller was told.
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(key);
return Err(err);
}
Ok(fresh)
}
/// Lifts `key`'s hold. `Ok(true)` when a hold was lifted, `Ok(false)`
/// when the key was not held.
pub fn resume(&self, key: &str) -> Result<bool, SettingsError> {
let lifted = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(key);
if lifted && let Err(err) = self.settings.delete(&format!("{SETTINGS_PREFIX}{key}")) {
// Same agreement as `pause`: a row that cannot be deleted
// puts the hold back, where it was.
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned());
return Err(err);
}
Ok(lifted)
}
/// Whether `key` is held — the drivers' predicate check, one lock
/// and a contains.
pub fn is_paused(&self, key: &str) -> bool {
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.contains(key)
}
/// Every held key, ascending — the ops view.
pub fn keys(&self) -> Vec<String> {
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn store() -> Arc<SettingsStore> {
Arc::new(SettingsStore::in_memory().expect("in-memory settings"))
}
#[test]
fn a_pause_persists_and_reloads() {
let settings = store();
let pause = PauseSet::load(settings.clone()).unwrap();
assert!(pause.pause("job:rhema#7").unwrap());
assert!(pause.is_paused("job:rhema#7"));
assert!(!pause.is_paused("interactive:web"));
// A fresh set over the same table starts where the last left off.
let reloaded = PauseSet::load(settings).unwrap();
assert!(reloaded.is_paused("job:rhema#7"));
assert_eq!(reloaded.keys(), vec!["job:rhema#7".to_owned()]);
}
#[test]
fn resume_lifts_the_hold_and_clears_the_row() {
let settings = store();
let pause = PauseSet::load(settings.clone()).unwrap();
pause.pause("interactive:web").unwrap();
assert!(pause.resume("interactive:web").unwrap());
assert!(!pause.is_paused("interactive:web"));
assert!(!pause.resume("interactive:web").unwrap(), "already lifted");
assert!(
PauseSet::load(settings).unwrap().keys().is_empty(),
"nothing lingers in the table"
);
}
#[test]
fn pausing_twice_is_one_hold() {
let settings = store();
let pause = PauseSet::load(settings).unwrap();
assert!(pause.pause("gitea:acme/widgets#3").unwrap());
assert!(!pause.pause("gitea:acme/widgets#3").unwrap());
assert_eq!(pause.keys().len(), 1);
}
}
+5 -6
View File
@@ -49,7 +49,8 @@ use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration; use std::time::Duration;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rusqlite::params; use rusqlite::params;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -721,10 +722,8 @@ pub fn registry(
hub: Arc<EventHub>, hub: Arc<EventHub>,
key: ResourceKey, key: ResourceKey,
) -> ToolRegistry { ) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools( let (tools, skipped) =
MANIFESTS, crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, consents, bridge, hub, key));
&builtins(store, consents, bridge, hub, key),
);
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the phone tool manifest must load: {skipped:?}" "the phone tool manifest must load: {skipped:?}"
@@ -739,7 +738,7 @@ pub fn registry(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use rhema_autonomous_agent::Allowlist; use crate::toolkit::Allowlist;
#[test] #[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() { fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+824
View File
@@ -0,0 +1,824 @@
//! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP, or an ssh login on a far
//! box.
//!
//! 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`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end; its private key rides the
//! choice as key text, the settings table is the store, so a
//! credential held in config or a store has no file to stage. 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 the workspace root and, when it is
//! empty, sends the host workspace as a tarball through the 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::{RunOutcome, ShellError, ShellExecutor, default_executor_with};
use rhema_core::{OutputOnly, ToolProgress};
use rhema_sandbox::{RunRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
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 the http sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The ssh sandbox's default workspace base: the remote login's own
/// home, the ssh backend's documented default. One directory per claw
/// workspace lands under it, named by the session hash.
pub const SSH_WORKSPACE_ROOT: &str = "/root";
/// 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,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
}
impl SandboxKind {
/// The stored spelling.
pub fn as_str(self) -> &'static str {
match self {
Self::Local => "local",
Self::Http => "http",
Self::Ssh => "ssh",
}
}
/// 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),
"ssh" => Some(Self::Ssh),
_ => 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>,
/// The `ssh` sandbox's destination: any alias or `user@host` the
/// local ssh config resolves, the built-in client's resolution.
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
/// The `ssh` sandbox's workspace base, where the per-workspace
/// directories land. Defaults to [`SSH_WORKSPACE_ROOT`].
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
/// The `ssh` sandbox's private key, the key text itself (OpenSSH
/// or PEM format), not a path: the choice lives in a config file
/// or a store that has no file to stage. Unset, the sandbox
/// hunts like the `ssh` binary would, the agent first, then the
/// default key files. `GET /v1/sandbox` never returns the key,
/// only that one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub private_key: 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());
self.host = self
.host
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty());
self.workspace = self
.workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty());
self.private_key = self
.private_key
.map(|key| key.trim().to_owned())
.filter(|key| !key.is_empty());
if self.kind == SandboxKind::Ssh {
let host = self
.host
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the ssh sandbox needs a host".to_owned()))?;
if host.contains(char::is_whitespace) {
return Err(SandboxError::Invalid(
"the ssh sandbox host is one destination, no spaces".to_owned(),
));
}
if let Some(workspace) = self.workspace.as_deref()
&& !workspace.starts_with('/')
{
return Err(SandboxError::Invalid(
"the ssh sandbox workspace must be an absolute path".to_owned(),
));
}
}
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::Local
}
/// The remote directory one workspace's commands run in: the
/// protocol root for `http`, a directory per host workspace under
/// the configured base for `ssh`.
pub fn remote_root(&self, host: &Path) -> PathBuf {
match self.kind {
SandboxKind::Http => PathBuf::from(REMOTE_WORKSPACE),
SandboxKind::Ssh => PathBuf::from(format!(
"{}/{}",
self.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT),
session_name(host)
)),
SandboxKind::Local => host.to_path_buf(),
}
}
}
/// 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<dyn Sandbox>>>,
}
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, the choice's remote root otherwise.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
self.choice().remote_root(host)
}
/// 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 sandbox for one session. The map is cleared whenever
/// the choice changes, so a new URL, token, host, or base builds a
/// new client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<dyn Sandbox>, ShellError> {
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 sandbox: Arc<dyn Sandbox> =
match choice.kind {
SandboxKind::Http => {
let url = choice.url.as_deref().ok_or_else(|| {
ShellError::Failed("the http sandbox has no url".to_owned())
})?;
let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
}
SandboxKind::Ssh => {
let dest = choice.host.as_deref().ok_or_else(|| {
ShellError::Failed("the ssh sandbox has no host".to_owned())
})?;
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
let mut sandbox = SshSandbox::new(dest.to_owned())
.with_workspace(format!("{base}/{session}"));
if let Some(key) = choice.private_key.as_deref() {
sandbox = sandbox.with_private_key(key);
}
Arc::new(sandbox)
}
SandboxKind::Local => {
return Err(ShellError::Failed(
"the local sandbox needs no remote client".to_owned(),
));
}
};
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 root gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox. The
/// probe makes the root first: the http daemon keeps one, the ssh
/// far end has none until something makes it, and the unpack's
/// `tar -C` would fail on a missing directory.
async fn seed(
&self,
sandbox: &Arc<dyn Sandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = OutputOnly(|_line: &str| {});
let probe = sandbox
.run(
RunRequest {
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone().into(),
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,
request: RunRequest,
cancelled: &AtomicBool,
progress: &mut dyn ToolProgress,
) -> Result<RunOutcome, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self.local.run(request, 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 root = choice.remote_root(&self.host_workspace);
ShellSandbox::new(sandbox)
.run(
RunRequest {
command: request.command,
cwd: root,
timeout: request.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::OutOfMemory => ShellError::OutOfMemory,
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()),
}
}
/// One path quoted for the remote `bash -c`: single quotes, the
/// closing quote spliced, good for every path a workspace root can
/// have.
fn shquote(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
/// 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,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a URL is required");
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn an_ssh_choice_needs_a_host_and_an_absolute_base() {
let missing = SandboxChoice {
kind: SandboxKind::Ssh,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a host is required");
let spaced = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me @box".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(spaced.is_err(), "a destination is one word");
let relative = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("srv/claw".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "the base is an absolute path");
let good = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some(" me@box ".to_owned()),
workspace: Some("/srv/claw/".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(good.host.as_deref(), Some("me@box"));
assert_eq!(good.workspace.as_deref(), Some("/srv/claw"));
assert!(good.is_remote());
assert_eq!(good.kind.as_str(), "ssh");
assert_eq!(
SandboxKind::parse("ssh"),
Some(SandboxKind::Ssh),
"the stored spelling round-trips"
);
}
#[test]
fn the_private_key_trims_and_a_blank_stays_unset() {
let keyed = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" -----BEGIN OPENSSH PRIVATE KEY----- ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(
keyed.private_key.as_deref(),
Some("-----BEGIN OPENSSH PRIVATE KEY-----"),
"the key text is trimmed, not mangled"
);
let blank = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("a blank key is no key, not a rejection");
assert_eq!(blank.private_key, None, "blank keeps the hunt on");
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
..SandboxChoice::default()
});
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 an_ssh_workspace_is_one_directory_per_host_workspace() {
let host = PathBuf::from("/state/claw/workspaces/interactive");
let choice = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
};
let root = choice.remote_root(&host);
let root = root.to_string_lossy().to_string();
assert!(
root.starts_with("/srv/claw/rhema-claw-"),
"the root lives under the configured base: {root}"
);
assert_eq!(root.len(), "/srv/claw/rhema-claw-".len() + 16);
let default_root = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
..SandboxChoice::default()
}
.remote_root(&host);
assert_eq!(
default_root.to_string_lossy(),
format!("/root/{}", session_name(&host)),
"the base defaults to the login's home"
);
}
#[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()),
..SandboxChoice::default()
})
.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"));
}
#[test]
fn an_ssh_choice_persists_with_its_host_and_base() {
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");
state
.set(SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
})
.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::Ssh);
assert_eq!(reloaded.choice().host.as_deref(), Some("me@box"));
assert_eq!(reloaded.choice().workspace.as_deref(), Some("/srv/claw"));
assert_eq!(
reloaded.workspace().to_string_lossy(),
format!("/srv/claw/{}", session_name(Path::new("/tmp/ws"))),
"the settings surface reports the session root"
);
}
#[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()),
..SandboxChoice::default()
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = OutputOnly(|_line: &str| {});
let executed = executor
.run(
RunRequest {
command: "echo hi".to_owned(),
cwd: Path::new(REMOTE_WORKSPACE).to_path_buf(),
timeout: 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));
}
}
+10 -13
View File
@@ -15,7 +15,8 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
use time::OffsetDateTime; use time::OffsetDateTime;
@@ -65,8 +66,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `cancel_task` — specs from the embedded manifests, operations /// `cancel_task` — specs from the embedded manifests, operations
/// compiled here. /// compiled here.
pub fn registry(store: Arc<TaskStore>) -> ToolRegistry { pub fn registry(store: Arc<TaskStore>) -> ToolRegistry {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the task tool manifests must all load: {skipped:?}" "the task tool manifests must all load: {skipped:?}"
@@ -236,7 +236,7 @@ mod tests {
async fn call(store: &Arc<TaskStore>, name: &str, args: Value) -> rhema_core::ToolResult { async fn call(store: &Arc<TaskStore>, name: &str, args: Value) -> rhema_core::ToolResult {
let resolver = let resolver =
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive()); registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
resolver resolver
.resolve( .resolve(
rhema_core::ToolCall { rhema_core::ToolCall {
@@ -252,8 +252,7 @@ mod tests {
#[test] #[test]
fn every_manifest_loads_against_its_builtin() { fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}"); assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect(); let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!( assert_eq!(
@@ -271,7 +270,7 @@ mod tests {
let mut covered = Vec::new(); let mut covered = Vec::new();
for (source, raw) in MANIFESTS { for (source, raw) in MANIFESTS {
covered.push( covered.push(
rhema_autonomous_agent::manifest::parse(raw) crate::toolkit::parse_manifest(raw)
.unwrap_or_else(|err| panic!("{source}: {err}")) .unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin, .builtin,
); );
@@ -286,12 +285,11 @@ mod tests {
#[test] #[test]
fn the_registry_serves_the_manifest_specs() { fn the_registry_serves_the_manifest_specs() {
let resolver = let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let specs = resolver.specs(); let specs = resolver.specs();
for (name, raw) in MANIFESTS { for (name, raw) in MANIFESTS {
let manifest = rhema_autonomous_agent::manifest::parse(raw) let manifest =
.unwrap_or_else(|err| panic!("{name}: {err}")); crate::toolkit::parse_manifest(raw).unwrap_or_else(|err| panic!("{name}: {err}"));
let spec = specs let spec = specs
.iter() .iter()
.find(|spec| spec.name == *name) .find(|spec| spec.name == *name)
@@ -310,8 +308,7 @@ mod tests {
#[test] #[test]
fn replay_safety_comes_from_the_manifest() { fn replay_safety_comes_from_the_manifest() {
let resolver = let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!( assert_eq!(
resolver.replay_safety("list_tasks"), resolver.replay_safety("list_tasks"),
rhema_core::ReplaySafety::Safe rhema_core::ReplaySafety::Safe
+413
View File
@@ -0,0 +1,413 @@
//! Read-only transcripts for the keys the chat surface cannot message.
//!
//! A forge thread, a finished coding job: their dispatches run through
//! handlers that never touch the hub, so the daemon holds no turn
//! record for them. What it does hold is the session stash the
//! step engine checkpoints after every step, with the engine's own
//! history in it. This module turns that history back into the hub's
//! event shapes, so the chat surface renders a finished thread with the
//! renderer it already has, and [`page`] cuts it the way the hub cuts
//! its own record.
use std::collections::HashMap;
use rhema_core::{Content, Message, Role, Session as CoreSession, ToolResult};
use rhema_rsd::Outcome;
use crate::hub::{SeqEvent, TurnEvent};
use crate::interactive::{shell_command, snippet};
/// One tool call remembered while its result is still to come: the name
/// the result event carries, and the arguments a shell result's command
/// line is read from.
struct Call {
name: String,
args: String,
}
/// The transcript of a stashed session, as the hub's events: one
/// `user_message`, the turn's deltas and tool rows, one `turn_done` per
/// turn, in history order. `last` is the record's most recent outcome,
/// which the newest turn's end marker carries; the older turns closed
/// the way the handler closes a finished one. `leased` says the record
/// is mid-dispatch right now, and a stash whose newest turn never
/// released is not "handled" — the turn was cut, and its end marker says
/// so instead of borrowing the previous turn's word.
///
/// Images and pastes ride a user message only when the stash recorded
/// them: a forge or job prompt carries none, and a chat key never takes
/// this path.
pub fn events(session: &CoreSession, last: Option<&Outcome>, leased: bool) -> Vec<TurnEvent> {
let mut out: Vec<TurnEvent> = Vec::new();
let mut calls: HashMap<String, Call> = HashMap::new();
let mut open = false;
let mut reply: Option<String> = None;
for message in &session.history {
match message.role {
Role::User => {
close(&mut out, &mut open, reply.take(), "handled");
out.push(TurnEvent::UserMessage {
text: text_of(message),
images: Vec::new(),
pastes: crate::paste::spans(message),
});
open = true;
}
Role::Assistant => {
// A stash cut before its first user message still opens
// a turn: the history is what it is.
open = true;
let mut said: Option<String> = None;
for content in &message.content {
match content {
Content::Text(text) => {
if text.trim().is_empty() {
continue;
}
out.push(TurnEvent::TextDelta { text: text.clone() });
said = Some(text.clone());
}
Content::ToolCall(call) => {
calls.insert(
call.id.clone(),
Call {
name: call.name.clone(),
args: call.args.to_string(),
},
);
out.push(TurnEvent::ToolStart {
name: call.name.clone(),
});
}
Content::ToolResult(result) => push_result(&mut out, &calls, result),
Content::Image(_) => {}
}
}
if said.is_some() {
reply = said;
}
}
Role::Tool | Role::System => {
for content in &message.content {
if let Content::ToolResult(result) = content {
push_result(&mut out, &calls, result);
}
}
}
}
}
let outcome = outcome_label(last, leased);
close(&mut out, &mut open, reply, &outcome);
out
}
/// The text blocks of a message, joined the way the model read them.
fn text_of(message: &Message) -> String {
message
.content
.iter()
.filter_map(|content| match content {
Content::Text(text) => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
/// The end marker, only for a turn that was open.
fn close(out: &mut Vec<TurnEvent>, open: &mut bool, reply: Option<String>, outcome: &str) {
if !*open {
return;
}
out.push(TurnEvent::TurnDone {
reply,
outcome: outcome.to_owned(),
});
*open = false;
}
/// One tool result as the wire's row: the name its call carried, the
/// bounded snippet the summary holds, and for a shell the command line
/// parsed back out of the call's arguments.
fn push_result(out: &mut Vec<TurnEvent>, calls: &HashMap<String, Call>, result: &ToolResult) {
let call = calls.get(&result.id);
let name = call
.map(|call| call.name.clone())
.unwrap_or_else(|| result.id.clone());
let command = matches!(name.as_str(), "bash" | "run_command")
.then(|| shell_command(call.map(|call| call.args.as_str())))
.flatten();
out.push(TurnEvent::ToolResult {
name,
is_error: result.is_error,
summary: snippet(&result.content),
code: result.code,
command,
});
}
/// The outcome label a turn's end marker carries, in the handler's own
/// words: a superseded dispatch was cut, a failed one broke. A record
/// with no outcome has never released, so its newest turn is either the
/// one running now (the lease says so) or one a restart cut — never a
/// handled turn, which always records its release.
fn outcome_label(outcome: Option<&Outcome>, leased: bool) -> String {
match outcome {
Some(Outcome::Failed(_)) => "failed",
Some(Outcome::Superseded) => "aborted",
Some(Outcome::Handled) => "handled",
None if leased => "running",
None => "aborted",
}
.to_owned()
}
/// One page of a stashed transcript, cut the way the hub cuts its own
/// record: at most `limit` events ending at `before`, starting on a
/// turn boundary, with `more` saying whether anything sits below it. A
/// turn longer than `limit` comes back whole rather than split. `seq`
/// numbers the events from 1 in history order — a stable address for as
/// long as the stash does not change.
pub fn page(events: &[TurnEvent], before: Option<i64>, limit: usize) -> (Vec<SeqEvent>, bool) {
let end = match before {
Some(before) => (before - 1).clamp(0, events.len() as i64) as usize,
None => events.len(),
};
let mut want = limit.max(1);
loop {
let from = end.saturating_sub(want);
let window = &events[from..end];
let page_start = match window
.iter()
.position(|event| matches!(event, TurnEvent::UserMessage { .. }))
{
Some(index) => from + index,
None if from == 0 => from,
None => {
// The window sits inside one turn: read further back,
// unless there is nothing further back to read.
want = (want * 2).min(crate::hub::HISTORY_SCAN_CAP);
continue;
}
};
let page = events[page_start..end]
.iter()
.enumerate()
.map(|(offset, event)| ((page_start + offset + 1) as i64, event.clone()))
.collect();
return (page, page_start > 0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use rhema_core::{Image, ToolCall};
use serde_json::json;
fn user(text: &str) -> Message {
Message::text(Role::User, text)
}
fn assistant(content: Vec<Content>) -> Message {
Message {
role: Role::Assistant,
content,
annotations: Default::default(),
}
}
fn result(id: &str, content: &str) -> Message {
Message {
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult {
id: id.to_owned(),
content: content.to_owned(),
is_error: false,
code: Some(0),
images: Vec::new(),
})],
annotations: Default::default(),
}
}
fn session(history: Vec<Message>) -> CoreSession {
CoreSession {
history,
..CoreSession::default()
}
}
#[test]
fn a_turn_becomes_the_events_the_hub_would_have_recorded() {
let core = session(vec![
user("review PR 7"),
assistant(vec![Content::ToolCall(ToolCall {
id: "call-1".to_owned(),
name: "bash".to_owned(),
args: json!({"command": "gh pr diff 7"}),
provider_data: serde_json::Value::Null,
})]),
result("call-1", "diff --git a/x b/x"),
assistant(vec![Content::Text("LGTM.".to_owned())]),
]);
assert_eq!(
events(&core, Some(&Outcome::Handled), false),
vec![
TurnEvent::UserMessage {
text: "review PR 7".to_owned(),
images: Vec::new(),
pastes: Vec::new(),
},
TurnEvent::ToolStart {
name: "bash".to_owned(),
},
TurnEvent::ToolResult {
name: "bash".to_owned(),
is_error: false,
summary: "diff --git a/x b/x".to_owned(),
code: Some(0),
command: Some("gh pr diff 7".to_owned()),
},
TurnEvent::TextDelta {
text: "LGTM.".to_owned(),
},
TurnEvent::TurnDone {
reply: Some("LGTM.".to_owned()),
outcome: "handled".to_owned(),
},
]
);
}
#[test]
fn each_turn_closes_before_the_next_question() {
let core = session(vec![
user("first"),
assistant(vec![Content::Text("one".to_owned())]),
user("second"),
assistant(vec![Content::Text("two".to_owned())]),
]);
let events = events(&core, Some(&Outcome::Failed("boom".to_owned())), false);
let closes: Vec<&TurnEvent> = events
.iter()
.filter(|event| matches!(event, TurnEvent::TurnDone { .. }))
.collect();
assert_eq!(closes.len(), 2);
assert_eq!(
closes[0],
&TurnEvent::TurnDone {
reply: Some("one".to_owned()),
outcome: "handled".to_owned(),
}
);
// The newest turn carries the record's own outcome.
assert_eq!(
closes[1],
&TurnEvent::TurnDone {
reply: Some("two".to_owned()),
outcome: "failed".to_owned(),
}
);
}
#[test]
fn a_stash_that_starts_mid_turn_still_closes() {
let core = session(vec![assistant(vec![Content::Text("orphan".to_owned())])]);
assert_eq!(
events(&core, Some(&Outcome::Handled), false).last(),
Some(&TurnEvent::TurnDone {
reply: Some("orphan".to_owned()),
outcome: "handled".to_owned(),
})
);
}
/// A record with no release is not a handled turn: either the
/// dispatch is running now, or a restart cut it. Both read as what
/// they are instead of borrowing the previous turn's word.
#[test]
fn an_unreleased_turn_is_not_labelled_handled() {
let core = session(vec![
user("cut"),
assistant(vec![Content::Text("I'll start by looking".to_owned())]),
]);
let cut = events(&core, None, false);
assert_eq!(
cut.last(),
Some(&TurnEvent::TurnDone {
reply: Some("I'll start by looking".to_owned()),
outcome: "aborted".to_owned(),
})
);
let running = events(&core, None, true);
assert_eq!(
running.last(),
Some(&TurnEvent::TurnDone {
reply: Some("I'll start by looking".to_owned()),
outcome: "running".to_owned(),
})
);
}
#[test]
fn images_in_the_history_do_not_invent_attachment_ids() {
let mut message = user("look");
message.content.push(Content::Image(Image {
media_type: rhema_core::ImageMediaType::Png,
data: "iVBORw0KGgo=".to_owned(),
}));
let events = events(&session(vec![message]), None, false);
assert_eq!(
events[0],
TurnEvent::UserMessage {
text: "look".to_owned(),
images: Vec::new(),
pastes: Vec::new(),
}
);
}
#[test]
fn a_page_starts_on_a_turn_boundary_and_stacks_backwards() {
let core = session(vec![
user("zero"),
assistant(vec![Content::Text("a".to_owned())]),
user("one"),
assistant(vec![Content::Text("b".to_owned())]),
user("two"),
assistant(vec![Content::Text("c".to_owned())]),
]);
let all = events(&core, None, false);
// The newest page holds the last turn only.
let (newest, more) = page(&all, None, 2);
assert!(more, "two turns sit above it");
assert!(matches!(newest[0].1, TurnEvent::UserMessage { .. }));
assert_eq!(newest.len(), 3, "a turn comes whole: question, delta, done");
assert_eq!(newest[0].0, 7, "seqs are absolute, so pages stack");
// The next page ends exactly where the first begins.
let (older, more) = page(&all, Some(newest[0].0), 2);
assert!(more);
assert_eq!(older[0].0, 4);
let (first, more) = page(&all, Some(older[0].0), 2);
assert!(!more, "the record ends here");
assert_eq!(first[0].0, 1);
}
#[test]
fn a_turn_longer_than_the_page_comes_back_whole() {
let core = session(vec![
user("long"),
assistant(vec![
Content::Text("a".to_owned()),
Content::Text("b".to_owned()),
Content::Text("c".to_owned()),
]),
]);
let all = events(&core, None, false);
let (whole, more) = page(&all, None, 1);
assert_eq!(whole.len(), all.len());
assert!(!more);
}
}
+680
View File
@@ -0,0 +1,680 @@
//! The resident's toolset: named tools, a `TOOL.yaml` per tool, and the
//! per-run [`ToolResolver`] cut from them.
//!
//! `rhema-core` ships the resolver seam and no registry, on purpose. It
//! ships one primitive, not a framework. Until 0.4.2 the registry, the
//! manifest loader, the allowlist, and the resolver chain rode
//! `rhema-autonomous-agent`, which was never the right home for them. The
//! crate is the lease-driven loop, and it compiles no tool of its own.
//! The claw was the only consumer, so the machinery moved here with the
//! tools it serves.
//!
//! The shape is unchanged. A tool is a folder under `tools/` holding a
//! `TOOL.yaml`: the name the model calls, the description it
//! picks the tool by, the argument schema, the replay classification, and
//! a `run` binding. The code half is a [`ToolOp`] registered under that
//! binding's id, so a tool's static data stops living next to it in Rust
//! string literals and one folder names one tool. [`builtin_tools`]
//! joins the two, [`ToolRegistry`] holds the survivors, and
//! [`ToolRegistry::resolver_for`] cuts the allowlisted view the step
//! engine consumes.
//!
//! A manifest that does not parse, or whose `run.builtin` id has no
//! operation, is skipped rather than fatal, the way an unreadable skill
//! folder is; each family pins its shipped set with a test.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use async_trait::async_trait;
use rhema_core::{
ReplaySafety, ToolCall, ToolContext, ToolProgress, ToolResolver, ToolResult, ToolSpec,
};
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
/// Why a tool invocation failed: the message the model reads. The
/// registry turns `Err` into an in-band failure result, a failing tool is
/// a result the model reacts to, never a crashed run, so the message is
/// the error's whole content.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{0}")]
pub struct ToolError(String);
impl ToolError {
/// An error whose message the model reads verbatim.
pub fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
/// The message the model reads.
pub fn message(&self) -> &str {
&self.0
}
}
impl From<String> for ToolError {
fn from(message: String) -> Self {
Self(message)
}
}
impl From<&str> for ToolError {
fn from(message: &str) -> Self {
Self(message.to_owned())
}
}
/// One named tool: the spec the model sees, and the invocation the
/// registry dispatches to.
#[async_trait]
pub trait Tool: Send + Sync {
/// The tool's schema, passed through to the provider's native
/// tool-calling format. The description lives here and nowhere else.
fn spec(&self) -> ToolSpec;
/// Whether a resume may re-execute one of this tool's committed calls
/// that lost its result. [`ReplaySafety::Unsafe`] unless declared
/// otherwise: an unclassified tool is treated as side-effecting.
fn replay_safety(&self) -> ReplaySafety {
ReplaySafety::Unsafe
}
/// Runs the tool. The registry turns `Err` into an in-band failure
/// result carrying the error's message; `Ok` text is the tool's
/// answer.
async fn invoke(&self, args: Value) -> Result<String, ToolError>;
}
/// The static half of a tool, parsed from a `TOOL.yaml`.
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest {
/// Name the model uses to call the tool.
pub name: String,
/// What the tool does; the model picks tools from this.
pub description: String,
/// JSON schema for the call arguments; the empty-object schema when
/// the manifest omits it.
pub parameters: Value,
/// Whether a resume may re-execute a committed call that lost its
/// result; [`ReplaySafety::Unsafe`] when the manifest omits it.
pub replay_safety: ReplaySafety,
/// The `run.builtin` id naming the compiled operation.
pub builtin: String,
}
/// Why a `TOOL.yaml` did not parse into a [`Manifest`].
#[derive(Debug, Error)]
#[error("{0}")]
pub struct ManifestError(String);
/// Parses one `TOOL.yaml`. `parameters` defaults to the empty-object
/// schema and `replay_safety` to [`ReplaySafety::Unsafe`], so a minimal
/// manifest is a name, a description, and a `run` binding.
pub fn parse_manifest(raw: &str) -> Result<Manifest, ManifestError> {
let yaml: ManifestYaml =
serde_yaml::from_str(raw).map_err(|err| ManifestError(err.to_string()))?;
let name = yaml.name.trim().to_owned();
if name.is_empty() {
return Err(ManifestError("no tool name".to_owned()));
}
let description = yaml.description.trim().to_owned();
if description.is_empty() {
return Err(ManifestError(format!("{name}: no description")));
}
let builtin = match yaml.run.kind {
RunKind::Builtin { builtin } => builtin.trim().to_owned(),
};
if builtin.is_empty() {
return Err(ManifestError(format!(
"{name}: run.builtin names no operation"
)));
}
let parameters = match yaml.parameters {
Some(value) => serde_json::to_value(&value)
.map_err(|err| ManifestError(format!("{name}: parameters are not JSON: {err}")))?,
None => serde_json::json!({ "type": "object" }),
};
let replay_safety = yaml
.replay_safety
.map(|replay| match replay {
ReplayYaml::Unsafe => ReplaySafety::Unsafe,
ReplayYaml::Safe => ReplaySafety::Safe,
})
.unwrap_or_default();
Ok(Manifest {
name,
description,
parameters,
replay_safety,
builtin,
})
}
/// The operation half of a manifest-defined tool: run the call. The spec
/// half lives in the tool's `TOOL.yaml`, so an operation carries no
/// schema strings of its own.
#[async_trait]
pub trait ToolOp: Send + Sync {
/// Runs the tool. The registry turns `Err` into an in-band failure
/// result; `Ok` text is the tool's answer.
async fn invoke(&self, args: Value) -> Result<String, ToolError>;
}
/// A [`Tool`] cut from a [`Manifest`] plus its registered operation: the
/// model sees the manifest's spec, and the registry dispatches to the
/// operation.
pub struct ManifestTool {
manifest: Manifest,
op: Arc<dyn ToolOp>,
}
impl ManifestTool {
/// Binds `manifest` to the operation `op`.
pub fn new(manifest: Manifest, op: Arc<dyn ToolOp>) -> Self {
Self { manifest, op }
}
}
#[async_trait]
impl Tool for ManifestTool {
fn spec(&self) -> ToolSpec {
ToolSpec::new(
self.manifest.name.clone(),
self.manifest.description.clone(),
self.manifest.parameters.clone(),
)
}
fn replay_safety(&self) -> ReplaySafety {
self.manifest.replay_safety
}
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
self.op.invoke(args).await
}
}
/// Loads `manifests`: `(source, text)` pairs, `source` naming the
/// manifest in skip reports, against the registered `builtins`. A
/// manifest that does not parse, or whose `run.builtin` id has no
/// operation, is skipped and reported; the survivors are ready to
/// register.
pub fn builtin_tools(
manifests: &[(&str, &str)],
builtins: &BTreeMap<String, Arc<dyn ToolOp>>,
) -> (Vec<Arc<dyn Tool>>, Vec<String>) {
let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
let mut skipped = Vec::new();
for (source, raw) in manifests {
let manifest = match parse_manifest(raw) {
Ok(manifest) => manifest,
Err(err) => {
skipped.push(format!("{source}: {err}"));
continue;
}
};
match builtins.get(&manifest.builtin) {
Some(op) => tools.push(Arc::new(ManifestTool::new(manifest, op.clone()))),
None => skipped.push(format!(
"{source}: no builtin operation for {:?}",
manifest.builtin
)),
}
}
(tools, skipped)
}
/// The tool-permission set one handler run is granted. `None` means
/// permissive, every registered tool, which is the resident tier's
/// standing policy: the HTTP surface is the trust boundary.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Allowlist {
allowed: Option<BTreeSet<String>>,
}
impl Allowlist {
/// Every registered tool is permitted.
pub fn permissive() -> Self {
Self { allowed: None }
}
/// Only the named tools are permitted.
pub fn from_tools(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
allowed: Some(names.into_iter().map(Into::into).collect()),
}
}
/// Whether `tool` may be invoked under this allowlist.
pub fn allows(&self, tool: &str) -> bool {
match &self.allowed {
None => true,
Some(allowed) => allowed.contains(tool),
}
}
}
/// The named tool set, from which per-run [`ToolResolver`]s are cut.
#[derive(Default)]
pub struct ToolRegistry {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
impl ToolRegistry {
/// An empty registry.
pub fn new() -> Self {
Self::default()
}
/// Registers a tool under its spec's name; a re-register replaces.
pub fn register(&mut self, tool: Arc<dyn Tool>) {
self.tools.insert(tool.spec().name, tool);
}
/// How many tools are registered.
pub fn len(&self) -> usize {
self.tools.len()
}
/// Whether nothing is registered.
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
/// A resolver over the tools `allowlist` permits: the model sees only
/// those specs, and a call for a forbidden or unknown tool comes back
/// as an in-band failure result.
pub fn resolver_for(&self, allowlist: &Allowlist) -> Arc<dyn ToolResolver> {
Arc::new(FilteredResolver {
tools: self
.tools
.iter()
.filter(|(name, _)| allowlist.allows(name))
.map(|(name, tool)| (name.clone(), tool.clone()))
.collect(),
})
}
}
/// One run's view of the registry: the allowlisted slice, as the seam the
/// step engine consumes.
struct FilteredResolver {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
#[async_trait]
impl ToolResolver for FilteredResolver {
fn specs(&self) -> Vec<ToolSpec> {
self.tools.values().map(|tool| tool.spec()).collect()
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
self.tools
.get(name)
.map(|tool| tool.replay_safety())
.unwrap_or(ReplaySafety::Unsafe)
}
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
let Some(tool) = self.tools.get(&call.name) else {
return ToolResult::failure(&call.id, format!("unknown tool: {}", call.name));
};
match tool.invoke(call.args.clone()).await {
Ok(text) => ToolResult::success(&call.id, text),
Err(err) => ToolResult::failure(&call.id, err.message()),
}
}
}
/// Several resolvers behind one seam: specs concatenate in order, and a
/// call is served by the first resolver offering that tool's name. Tool
/// names should be unique across the chain; on a duplicate, the earlier
/// resolver wins and the later one is unreachable for it.
pub struct ResolverChain {
resolvers: Vec<Arc<dyn ToolResolver>>,
}
impl ResolverChain {
/// A chain serving tools from `resolvers`, in order.
pub fn new(resolvers: Vec<Arc<dyn ToolResolver>>) -> Self {
Self { resolvers }
}
/// The resolver offering `name`, if any.
fn owner(&self, name: &str) -> Option<&Arc<dyn ToolResolver>> {
self.resolvers
.iter()
.find(|resolver| resolver.specs().iter().any(|spec| spec.name == name))
}
}
#[async_trait]
impl ToolResolver for ResolverChain {
fn specs(&self) -> Vec<ToolSpec> {
self.resolvers
.iter()
.flat_map(|resolver| resolver.specs())
.collect()
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
self.owner(name)
.map(|resolver| resolver.replay_safety(name))
.unwrap_or(ReplaySafety::Unsafe)
}
async fn resolve(&self, call: ToolCall, ctx: &ToolContext) -> ToolResult {
match self.owner(&call.name) {
Some(resolver) => resolver.resolve(call, ctx).await,
None => ToolResult::failure(&call.id, format!("unknown tool: {}", call.name)),
}
}
/// Streams through the owning resolver: the shell is long, and its
/// live lines are the reason this chain exists as a seam rather than
/// a filter.
async fn resolve_streaming(
&self,
call: ToolCall,
ctx: &ToolContext,
progress: &mut dyn ToolProgress,
) -> ToolResult {
match self.owner(&call.name) {
Some(resolver) => resolver.resolve_streaming(call, ctx, progress).await,
None => ToolResult::failure(&call.id, format!("unknown tool: {}", call.name)),
}
}
}
/// The `TOOL.yaml` body this module reads.
#[derive(Debug, Deserialize)]
struct ManifestYaml {
name: String,
description: String,
#[serde(default)]
parameters: Option<serde_yaml::Value>,
#[serde(default)]
replay_safety: Option<ReplayYaml>,
run: Run,
}
/// The `run` binding: the kind's field name is the variant, so `builtin`
/// names a compiled operation the consumer registered under that id, and
/// a future kind is another variant.
#[derive(Debug, Deserialize)]
struct Run {
#[serde(flatten)]
kind: RunKind,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RunKind {
Builtin { builtin: String },
}
/// The manifest's `replay_safety`, lowercase to read like the yaml it
/// sits in; maps onto [`ReplaySafety`].
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ReplayYaml {
Unsafe,
Safe,
}
#[cfg(test)]
mod tests {
use super::*;
struct Echo;
#[async_trait]
impl ToolOp for Echo {
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
Ok(args.to_string())
}
}
struct Boom;
#[async_trait]
impl ToolOp for Boom {
async fn invoke(&self, _args: Value) -> Result<String, ToolError> {
Err(ToolError::new("exploded"))
}
}
fn builtins() -> BTreeMap<String, Arc<dyn ToolOp>> {
BTreeMap::from([
("test.echo".to_owned(), Arc::new(Echo) as Arc<dyn ToolOp>),
("test.boom".to_owned(), Arc::new(Boom) as Arc<dyn ToolOp>),
])
}
#[test]
fn a_full_manifest_parses() {
let manifest = parse_manifest(
"name: probe\n\
description: |\n\
\x20 Probe the parser.\n\
parameters:\n\
\x20 type: object\n\
\x20 properties:\n\
\x20 path:\n\
\x20 type: string\n\
\x20 required: [path]\n\
replay_safety: safe\n\
run:\n\
\x20 builtin: test.echo\n",
)
.expect("parses");
assert_eq!(manifest.name, "probe");
assert_eq!(manifest.description, "Probe the parser.");
assert_eq!(
manifest.parameters,
serde_json::json!({
"type": "object",
"properties": { "path": { "type": "string" } },
"required": ["path"]
})
);
assert_eq!(manifest.replay_safety, ReplaySafety::Safe);
assert_eq!(manifest.builtin, "test.echo");
}
#[test]
fn omissions_take_defaults() {
let manifest =
parse_manifest("name: probe\ndescription: Probe.\nrun:\n builtin: test.echo\n")
.expect("parses");
assert_eq!(manifest.parameters, serde_json::json!({ "type": "object" }));
assert_eq!(manifest.replay_safety, ReplaySafety::Unsafe);
}
#[test]
fn blank_fields_and_a_missing_run_are_rejected() {
assert!(parse_manifest("description: Probe.\nrun:\n builtin: test.echo\n").is_err());
assert!(
parse_manifest("name: probe\ndescription: \" \"\nrun:\n builtin: test.echo\n")
.is_err()
);
assert!(
parse_manifest("name: probe\ndescription: Probe.\nrun:\n builtin: \" \"\n").is_err()
);
assert!(parse_manifest("name: probe\ndescription: Probe.\n").is_err());
}
#[test]
fn an_unknown_run_kind_is_rejected_not_silently_dropped() {
let err = parse_manifest("name: probe\ndescription: Probe.\nrun:\n exec: ./run.sh\n")
.expect_err("exec is not a binding");
assert!(
err.to_string().contains("did not match any variant"),
"{err}"
);
}
#[test]
fn loading_resolves_builtins_and_reports_skips() {
let manifests = [
(
"probe",
"name: probe\ndescription: Probe.\nrun:\n builtin: test.echo\n",
),
("bad", "name: bad\ndescription: Probe.\n"),
(
"orphan",
"name: orphan\ndescription: Probe.\nrun:\n builtin: test.nope\n",
),
];
let (tools, skipped) = builtin_tools(&manifests, &builtins());
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "probe");
assert_eq!(skipped.len(), 2, "{skipped:?}");
assert!(skipped[0].starts_with("bad:"), "{skipped:?}");
assert!(skipped[1].contains("test.nope"), "{skipped:?}");
}
#[test]
fn a_loaded_tool_registers_under_its_manifest_name_and_classifies() {
let manifests = [(
"probe",
"name: probe\ndescription: Probe.\nreplay_safety: safe\nrun:\n builtin: test.echo\n",
)];
let (tools, skipped) = builtin_tools(&manifests, &builtins());
assert!(skipped.is_empty(), "{skipped:?}");
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
assert_eq!(registry.len(), 1);
let resolver = registry.resolver_for(&Allowlist::permissive());
assert_eq!(resolver.specs()[0].name, "probe");
assert_eq!(
resolver.replay_safety("probe"),
ReplaySafety::Safe,
"the manifest's classification reaches the resolver"
);
assert_eq!(resolver.replay_safety("unknown"), ReplaySafety::Unsafe);
}
fn call(name: &str) -> ToolCall {
ToolCall {
id: "c1".into(),
name: name.into(),
args: serde_json::json!({ "a": 1 }),
provider_data: Value::Null,
}
}
#[tokio::test]
async fn a_filtered_resolver_hides_what_it_forbids_and_fails_a_call_for_it() {
let (tools, _) = builtin_tools(
&[
(
"echo",
"name: echo\ndescription: Echo.\nrun:\n builtin: test.echo\n",
),
(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
),
],
&builtins(),
);
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
let resolver = registry.resolver_for(&Allowlist::from_tools(["echo"]));
let names: Vec<String> = resolver.specs().iter().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["echo".to_owned()]);
let forbidden = resolver
.resolve(call("boom"), &ToolContext::default())
.await;
assert!(forbidden.is_error);
assert_eq!(forbidden.content, "unknown tool: boom");
}
#[tokio::test]
async fn an_operation_error_is_an_in_band_failure_with_its_message() {
let (tools, _) = builtin_tools(
&[(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
)],
&builtins(),
);
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
let resolver = registry.resolver_for(&Allowlist::permissive());
let result = resolver
.resolve(call("boom"), &ToolContext::default())
.await;
assert!(result.is_error);
assert_eq!(result.content, "exploded");
assert_eq!(result.id, "c1");
}
#[tokio::test]
async fn a_chain_serves_each_name_from_its_own_resolver() {
let (tools, _) = builtin_tools(
&[
(
"echo",
"name: echo\ndescription: Echo.\nreplay_safety: safe\nrun:\n builtin: test.echo\n",
),
(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
),
],
&builtins(),
);
let mut left = ToolRegistry::new();
left.register(tools[0].clone());
let mut right = ToolRegistry::new();
right.register(tools[1].clone());
let chain = ResolverChain::new(vec![
left.resolver_for(&Allowlist::permissive()),
right.resolver_for(&Allowlist::permissive()),
]);
let names: Vec<String> = chain.specs().iter().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["echo".to_owned(), "boom".to_owned()]);
assert_eq!(chain.replay_safety("echo"), ReplaySafety::Safe);
assert_eq!(chain.replay_safety("boom"), ReplaySafety::Unsafe);
assert_eq!(
chain
.resolve(call("echo"), &ToolContext::default())
.await
.content,
r#"{"a":1}"#
);
assert!(
chain
.resolve(call("boom"), &ToolContext::default())
.await
.is_error
);
assert_eq!(
chain
.resolve(call("nope"), &ToolContext::default())
.await
.content,
"unknown tool: nope"
);
}
#[test]
fn an_empty_allowlist_permits_nothing() {
let allowlist = Allowlist::from_tools(Vec::<String>::new());
assert!(!allowlist.allows("bash"));
assert_eq!(Allowlist::default(), Allowlist::permissive());
}
}
+3 -1
View File
@@ -325,6 +325,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
text_delta("hi"), text_delta("hi"),
], ],
@@ -348,7 +349,8 @@ mod tests {
0, 0,
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
), ),
(1, text_delta("hi")), (1, text_delta("hi")),
+14 -15
View File
@@ -9,21 +9,15 @@
#![forbid(unsafe_code)] #![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, provisioned at first use and kept for the
/// process's life — the toolkit's own process-wide cache holds it, so
/// The daemon's wiring, established at first use and kept for the /// `None` only when provisioning failed, and a failure does not retry.
/// process's life. `None` only when provisioning failed, cached like pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
/// every answer this static gives. rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
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 init file a later provisioner chains through — `None` when the /// 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 /// Layers the wiring onto one agent config: the shell env map (the
/// init file, the binary, the staging directory) and the prompt's /// init file, the binary, the staging directory) and the prompt's
/// vision section. A frontend without wiring changes nothing. /// 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 { let Some(wired) = wired() else {
return; return;
}; };
@@ -52,7 +46,12 @@ mod tests {
/// values are constants, so extending twice is the same map. /// values are constants, so extending twice is the same map.
#[test] #[test]
fn apply_twice_is_apply_once() { 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); apply(&mut config);
let once = config.shell_env.clone(); let once = config.shell_env.clone();
apply(&mut config); apply(&mut config);
+126
View File
@@ -114,6 +114,13 @@ CREATE TABLE IF NOT EXISTS watch_health (
consecutive_failures INTEGER NOT NULL DEFAULT 0, consecutive_failures INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (scope, forge, subject) 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. /// Why a watch-table operation failed.
@@ -315,6 +322,14 @@ impl ClawStore {
"DELETE FROM watches WHERE forge = ?1 AND repo = ?2", "DELETE FROM watches WHERE forge = ?1 AND repo = ?2",
params![forge.trim(), repo.trim()], 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) Ok(removed == 1)
} }
@@ -380,6 +395,13 @@ impl ClawStore {
"DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2", "DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2",
params![forge.trim(), account_id.trim()], params![forge.trim(), account_id.trim()],
)?; )?;
// The cursor goes with the watch, like a repo watch's: a re-add
// is a new watch, and its first pass asks from nothing rather
// than resuming where the old one stopped.
conn.execute(
"DELETE FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3",
params![SCOPE_ACCOUNT, forge.trim(), account_id.trim()],
)?;
Ok(removed == 1) Ok(removed == 1)
} }
@@ -391,6 +413,11 @@ impl ClawStore {
"DELETE FROM account_watches WHERE account_id = ?1", "DELETE FROM account_watches WHERE account_id = ?1",
params![account_id.trim()], params![account_id.trim()],
)?; )?;
// The cursors go with the watches, every forge at once.
conn.execute(
"DELETE FROM watch_cursors WHERE scope = ?1 AND subject = ?2",
params![SCOPE_ACCOUNT, account_id.trim()],
)?;
Ok(removed) Ok(removed)
} }
@@ -419,6 +446,51 @@ impl ClawStore {
.map_err(WatchStoreError::from)?; .map_err(WatchStoreError::from)?;
Ok(rows) 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 /// Records a successful poll: the streak resets, and the row stops
/// reading as broken. /// reading as broken.
pub fn record_poll_ok( pub fn record_poll_ok(
@@ -637,6 +709,60 @@ mod tests {
assert_eq!(store.list_health().expect("list reads").len(), 1); 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] #[test]
fn validation_fails_a_watch_loudly_and_specificly() { fn validation_fails_a_watch_loudly_and_specificly() {
assert_eq!( assert_eq!(
+10 -12
View File
@@ -14,7 +14,8 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -62,8 +63,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `unwatch_repo`, `list_watches` — specs from the embedded manifests, /// `unwatch_repo`, `list_watches` — specs from the embedded manifests,
/// operations compiled here. /// operations compiled here.
pub fn registry(store: Arc<ClawStore>) -> ToolRegistry { pub fn registry(store: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!( assert!(
skipped.is_empty(), skipped.is_empty(),
"the watch tool manifests must all load: {skipped:?}" "the watch tool manifests must all load: {skipped:?}"
@@ -197,7 +197,7 @@ mod tests {
fn names(registry: &ToolRegistry) -> Vec<String> { fn names(registry: &ToolRegistry) -> Vec<String> {
registry registry
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive()) .resolver_for(&crate::toolkit::Allowlist::permissive())
.specs() .specs()
.into_iter() .into_iter()
.map(|spec| spec.name) .map(|spec| spec.name)
@@ -206,8 +206,7 @@ mod tests {
#[test] #[test]
fn every_manifest_loads_against_its_builtin() { fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) = let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}"); assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect(); let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!( assert_eq!(
@@ -221,7 +220,7 @@ mod tests {
let mut covered = Vec::new(); let mut covered = Vec::new();
for (source, raw) in MANIFESTS { for (source, raw) in MANIFESTS {
covered.push( covered.push(
rhema_autonomous_agent::manifest::parse(raw) crate::toolkit::parse_manifest(raw)
.unwrap_or_else(|err| panic!("{source}: {err}")) .unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin, .builtin,
); );
@@ -236,8 +235,7 @@ mod tests {
#[test] #[test]
fn replay_safety_comes_from_the_manifest() { fn replay_safety_comes_from_the_manifest() {
let resolver = let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!( assert_eq!(
resolver.replay_safety("list_watches"), resolver.replay_safety("list_watches"),
rhema_core::ReplaySafety::Safe rhema_core::ReplaySafety::Safe
@@ -263,7 +261,7 @@ mod tests {
async fn watch_repo_lands_a_row_and_answers_json() { async fn watch_repo_lands_a_row_and_answers_json() {
let store = store(); let store = store();
let tools = registry(store.clone()); let tools = registry(store.clone());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive()); let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default(); let ctx = rhema_core::ToolContext::default();
let result = resolver let result = resolver
.resolve( .resolve(
@@ -303,7 +301,7 @@ mod tests {
async fn a_bad_watch_fails_in_band_with_the_reason() { async fn a_bad_watch_fails_in_band_with_the_reason() {
let store = store(); let store = store();
let tools = registry(store.clone()); let tools = registry(store.clone());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive()); let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default(); let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| { let call = |name: &str, args: Value| {
resolver.resolve( resolver.resolve(
@@ -356,7 +354,7 @@ mod tests {
store.add("github", "acme/widgets", None, "").expect("seed"); store.add("github", "acme/widgets", None, "").expect("seed");
store.add("gitlab", "group/prop", None, "").expect("seed"); store.add("gitlab", "group/prop", None, "").expect("seed");
let tools = registry(store.clone()); let tools = registry(store.clone());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive()); let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default(); let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| { let call = |name: &str, args: Value| {
resolver.resolve( resolver.resolve(
+16 -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 /// carrying watches, and the test speaks to the daemon the way an
/// integration would: through the store the routes share. /// integration would: through the store the routes share.
fn seed_watch(dir: &tempfile::TempDir, host: &str) { fn seed_watch(dir: &tempfile::TempDir, host: &str) {
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")) let store =
.expect("the watch table opens") rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok") .add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands"); .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_core::{Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
use rhema_rsd::{KeyState, Outcome, ResourceKey, SqliteStore, Store}; use rhema_rsd::{KeyState, Outcome, ResourceKey, SqliteStore, Store};
@@ -81,6 +93,8 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None, tools_bin: None,
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
+16 -2
View File
@@ -59,6 +59,8 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None, tools_bin: None,
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
@@ -67,10 +69,22 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
/// carrying watches, and the test speaks to the daemon the way an /// carrying watches, and the test speaks to the daemon the way an
/// integration would: through the store the routes share. /// integration would: through the store the routes share.
fn seed_watch(dir: &tempfile::TempDir, host: &str) { fn seed_watch(dir: &tempfile::TempDir, host: &str) {
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")) let store =
.expect("the watch table opens") rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok") .add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands"); .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] #[tokio::test]
+795 -17
View File
@@ -11,14 +11,14 @@ use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use rhema_autonomous_agent::Allowlist; use rhema_claw::toolkit::Allowlist;
use rhema_claw::watch_tools; use rhema_claw::watch_tools;
use rhema_claw::{ClawConfig, Daemon}; use rhema_claw::{ClawConfig, Daemon};
use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage}; use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
use rhema_rsd::{ResourceKey, SqliteStore, Store}; use rhema_rsd::{ResourceKey, SqliteStore, Store};
use serde_json::{Value, json}; use serde_json::{Value, json};
use tokio_stream::StreamExt; use tokio_stream::StreamExt;
use wiremock::matchers::{method, path}; use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate}; use wiremock::{Mock, MockServer, ResponseTemplate};
/// The scripted assistant turn: one text reply, nothing else. /// 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 { fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput {
ModelOutput { ModelOutput {
message: Message { message: Message {
annotations: Default::default(),
role: Role::Assistant, role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall { content: vec![Content::ToolCall(rhema_core::ToolCall {
id: id.to_owned(), id: id.to_owned(),
@@ -65,6 +66,8 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
tools_bin: None, tools_bin: None,
ingest_token: None, ingest_token: None,
transcript: None, transcript: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
@@ -232,21 +235,34 @@ impl rhema_core::ModelProvider for RecordingProvider {
/// One quiet GitHub repo, for the watches test: an issues list with a /// One quiet GitHub repo, for the watches test: an issues list with a
/// single closed issue and a quiet comments feed. /// single closed issue and a quiet comments feed.
async fn mount_github(server: &MockServer) { async fn mount_github(server: &MockServer) {
// 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",
"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": "2026-10-02T10:00:00Z",
"html_url": "https://github.com/acme/widgets/issues/7"
}]);
Mock::given(method("GET")) Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues")) .and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([{ .and(query_param("since", "2026-10-01T00:00:00Z"))
"id": 1007, .respond_with(ResponseTemplate::new(200).set_body_json(row))
"number": 7, .with_priority(1)
"state": "closed", .mount(server)
"title": "crash on save", .await;
"user": { "login": "alice" }, Mock::given(method("GET"))
"labels": [], .and(path("/repos/acme/widgets/issues"))
"body": "steps to reproduce…", .respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
"created_at": "2026-10-01T09:00:00Z", .with_priority(2)
"updated_at": "2026-10-02T10:00:00Z",
"closed_at": "2026-10-02T10:00:00Z",
"html_url": "https://github.com/acme/widgets/issues/7"
}])))
.mount(server) .mount(server)
.await; .await;
Mock::given(method("GET")) Mock::given(method("GET"))
@@ -498,6 +514,225 @@ async fn a_message_into_a_live_turn_steers_it() {
); );
} }
/// The session controls: pause holds a key's dispatch (its queued work
/// waits, the inventory says held), resume lifts the hold and the work
/// drains, and abort cuts what runs or drops what waits. The three
/// routes answer the shape the sidebar reads, and none of them reaches
/// into the transcript beyond the cut's own `aborted` marker.
#[tokio::test]
async fn sessions_pause_resume_and_abort_over_http() {
let gate = Arc::new(WireGate::default());
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(GatedProvider::new(gate.clone()))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// The key exists first: the create route is what puts it in the
// inventory, and the controls 404 on a key that is not there.
let created = client
.post(format!("{base}/v1/sessions"))
.json(&json!({"name": "web"}))
.send()
.await
.expect("the create posts");
assert_eq!(created.status(), 201, "the session is created");
let paused = client
.post(format!("{base}/v1/sessions/interactive:web/pause"))
.send()
.await
.expect("the pause posts");
assert_eq!(paused.status(), 200);
assert_eq!(
paused.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "paused": true})
);
// Two messages into the held key: accepted, queued, dispatched by
// nobody, and the inventory says so.
for text in ["first", "second"] {
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({"text": text}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
}
let listed = client
.get(format!("{base}/v1/sessions"))
.send()
.await
.expect("the listing reads");
let sessions: Vec<Value> = listed.json().await.expect("the listing parses");
let web = sessions
.iter()
.find(|row| row["key"] == "interactive:web")
.expect("the key is listed");
assert_eq!(web["paused"], json!(true));
assert_eq!(web["state"], json!("idle"), "held work does not dispatch");
// Abort with nothing running drains the queue and says how much it
// dropped; a second abort is the idempotent no-op.
let aborted = client
.post(format!("{base}/v1/sessions/interactive:web/abort"))
.send()
.await
.expect("the abort posts");
assert_eq!(aborted.status(), 200);
assert_eq!(
aborted.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "cut": false, "dropped": 2})
);
let again = client
.post(format!("{base}/v1/sessions/interactive:web/abort"))
.send()
.await
.expect("the second abort posts");
assert_eq!(
again.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "cut": false, "dropped": 0})
);
let quiet = client
.get(format!("{base}/v1/sessions"))
.send()
.await
.expect("the listing reads");
let sessions: Vec<Value> = quiet.json().await.expect("the listing parses");
let web = sessions
.iter()
.find(|row| row["key"] == "interactive:web")
.expect("the key is listed");
assert_eq!(web["inbox_depth"], json!(0));
// Resume, then a fresh message runs: the hold is gone.
let resumed = client
.post(format!("{base}/v1/sessions/interactive:web/resume"))
.send()
.await
.expect("the resume posts");
assert_eq!(
resumed.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "paused": false})
);
// A live turn, and the abort that cuts it: the stream closes on the
// `aborted` marker and the answer reports the cut.
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();
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({"text": "hello"}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
let mut in_flight = gate.in_flight_rx();
while !*in_flight.borrow_and_update() {
in_flight
.changed()
.await
.expect("the in-flight sender lives");
}
let cut = client
.post(format!("{base}/v1/sessions/interactive:web/abort"))
.send()
.await
.expect("the abort posts");
assert_eq!(
cut.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "cut": true, "dropped": 0})
);
read_until(&mut stream, &mut seen, "\"aborted\"").await;
assert!(seen.contains("\"outcome\":\"aborted\""), "seen: {seen}");
// Unknown keys are 404 on all three, and the inventory survives.
for verb in ["pause", "resume", "abort"] {
let missing = client
.post(format!("{base}/v1/sessions/nope:gone/{verb}"))
.send()
.await
.expect("the route answers");
assert_eq!(missing.status(), 404, "{verb} on an unknown key");
}
}
/// An abort on an idle `job:` key drops the queued delivery *and*
/// lands the row: the coding job's table is the jobs' truth, so a row
/// whose only delivery was dropped must not sit queued forever — it
/// fails with `aborted`, the same word the handler's own cut uses.
#[tokio::test]
async fn an_abort_on_a_queued_job_key_fails_its_row() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, Some("sekrit")),
mock_registry(Arc::new(MockProvider::new(Vec::new()))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let auth = |request: reqwest::RequestBuilder| {
request.header(reqwest::header::AUTHORIZATION, "Bearer sekrit")
};
// The row the job's table holds — enqueued through the store the
// daemon reads, quiet: nothing runs, the daemon's own loop is not
// started in this test.
let jobs = rhema_claw::job_store::CodingJobStore::open(dir.path().join("dispatch.db"))
.expect("the job store opens");
jobs.add_instance("rhema", "/tmp")
.expect("the instance lands");
let job = jobs
.enqueue("rhema", "tidy the crate")
.expect("the job queues");
assert_eq!(job.status, rhema_claw::job_store::JobStatus::Queued);
// Whatever would dispatch it sits on the key: the jobs source's own
// delivery, stood in for by the external ingest door.
let ingested = auth(client.post(format!("{base}/v1/ingest")))
.json(&json!({
"source": "phone",
"key": format!("job:rhema#{}", job.id),
"payload": {"job_id": job.id},
}))
.send()
.await
.expect("the event posts");
assert_eq!(ingested.status(), 202);
let aborted: Value =
auth(client.post(format!("{base}/v1/sessions/job:rhema%23{}/abort", job.id)))
.send()
.await
.expect("the abort posts")
.json()
.await
.expect("the answer parses");
assert_eq!(
aborted,
json!({"key": format!("job:rhema#{}", job.id), "cut": false, "dropped": 1}),
"{aborted}"
);
let row = jobs
.job(job.id)
.expect("the row reads")
.expect("the row is there");
assert_eq!(row.status, rhema_claw::job_store::JobStatus::Failed);
assert_eq!(row.result.as_deref(), Some("aborted"));
}
/// A chat message with images: the route enforces the budget (media /// A chat message with images: the route enforces the budget (media
/// type, non-empty body, decoded size, count), the transcript's /// type, non-empty body, decoded size, count), the transcript's
/// user_message card names the stored ids and media types, and each id /// user_message card names the stored ids and media types, and each id
@@ -655,6 +890,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_claw::paste::spans(ask).len(), 1);
assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_claw::paste::spans(ask)[0].lines, 2);
}
/// A turn nobody watched is still replayable: a client arriving after /// A turn nobody watched is still replayable: a client arriving after
/// the fact — a reloaded browser, a reopened phone — subscribes cold and /// the fact — a reloaded browser, a reopened phone — subscribes cold and
/// gets the finished turns back before the live feed. The same holds /// gets the finished turns back before the live feed. The same holds
@@ -1109,7 +1415,23 @@ async fn watches_added_over_http_feed_the_next_detect_pass() {
"the token is not serialized: {listed}" "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"); let report = daemon.tick().await.expect("the pass runs");
assert_eq!(report.detected, 1, "the new watch's feed event was fed"); assert_eq!(report.detected, 1, "the new watch's feed event was fed");
@@ -2209,6 +2531,252 @@ async fn providers_gain_and_lose_backends_over_the_surface() {
assert_eq!(gone.status(), 400); 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 ssh sandbox over the surface: a choice without a host is a 400,
/// a complete one lists its host and reports the workspace under the
/// configured base, and switching back to this host keeps the ssh
/// fields staged for the next switch. The private key rides the same
/// write-only contract the token has: it goes in, a bit comes back,
/// and `clear_private_key` drops it without moving the host.
#[tokio::test]
async fn the_ssh_sandbox_is_switchable_over_the_surface() {
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 refused = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(refused.status(), 400, "an ssh choice without a host");
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "workspace": "/srv/claw"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "ssh");
assert_eq!(switched["host"], "me@box.example");
let workspace = switched["workspace"].as_str().expect("the workspace reads");
assert!(
workspace.starts_with("/srv/claw/rhema-claw-"),
"the workspace sits under the configured base: {workspace}"
);
// The private key rides the same route: it goes in as the key
// text (the store-held credential, no file to stage), only the
// `private_key_set` bit comes back, and an absent field leaves
// the stored key alone the way the token's partial save does.
let keyed: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "ssh",
"host": "me@box.example",
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(keyed["private_key_set"], true);
assert!(
keyed.get("private_key").is_none(),
"the key stays write-only"
);
// A present-but-blank key clears the stored one, the token's
// exact contract: absent keeps, present replaces, even blank.
let blank: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "private_key": " "}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(blank["private_key_set"], false);
// The key is gone now, so set it again before the clear step:
// `clear_private_key` drops the stored key without moving the
// host.
let _again: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "ssh",
"host": "me@box.example",
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n"
}))
.send()
.await
.expect("the re-set posts")
.json()
.await
.expect("the re-set parses");
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "clear_private_key": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["private_key_set"], false);
assert_eq!(cleared["host"], "me@box.example");
// Back to this host: the workspace flips, the ssh fields stay
// staged for the next switch.
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["host"], "me@box.example");
assert!(
local["workspace"].as_str().expect("the workspace reads") != workspace,
"the workspace path follows the choice"
);
}
/// The agent identity surface: the text fields round-trip with /// The agent identity surface: the text fields round-trip with
/// partial-save semantics (an absent field is left alone, an empty one /// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type, /// clears), the avatar uploads and serves back with its content type,
@@ -2239,7 +2807,7 @@ async fn the_agent_identity_is_editable_over_the_surface() {
// A save names the fields it touches. // A save names the fields it touches.
let saved: Value = client let saved: Value = client
.put(format!("{base}/v1/agent")) .put(format!("{base}/v1/agent"))
.json(&json!({"name": "Kosmos", "mark": "✦", "tagline": "order"})) .json(&json!({"name": "Kosmos", "email": "kosmos@example.net", "mark": "✦", "tagline": "order"}))
.send() .send()
.await .await
.expect("the save posts") .expect("the save posts")
@@ -2248,6 +2816,7 @@ async fn the_agent_identity_is_editable_over_the_surface() {
.expect("the save parses"); .expect("the save parses");
assert_eq!(saved["name"], "Kosmos"); assert_eq!(saved["name"], "Kosmos");
assert_eq!(saved["mark"], "✦"); assert_eq!(saved["mark"], "✦");
assert_eq!(saved["email"], "kosmos@example.net");
assert_eq!(saved["avatar"], false); assert_eq!(saved["avatar"], false);
// A partial save leaves the fields it omitted. // A partial save leaves the fields it omitted.
@@ -2262,6 +2831,10 @@ async fn the_agent_identity_is_editable_over_the_surface() {
.expect("the partial save parses"); .expect("the partial save parses");
assert_eq!(partial["name"], "Kosmos Prime"); assert_eq!(partial["name"], "Kosmos Prime");
assert_eq!(partial["mark"], "✦", "untouched by the partial save"); assert_eq!(partial["mark"], "✦", "untouched by the partial save");
assert_eq!(
partial["email"], "kosmos@example.net",
"untouched by the partial save"
);
// An empty string clears its field. // An empty string clears its field.
let cleared: Value = client let cleared: Value = client
@@ -3263,6 +3836,29 @@ async fn a_restart_releases_a_dead_lease_and_the_key_answers() {
let base = serve(&daemon).await; let base = serve(&daemon).await;
let client = reqwest::Client::new(); let client = reqwest::Client::new();
// The turn the restart cut is not left wearing an outcome it never
// earned: recovery releases it as superseded, and the read-only
// transcript ends the turn aborted, not handled.
let thread: Value = client
.get(format!("{base}/v1/sessions/interactive:web/history"))
.send()
.await
.expect("the history request goes out")
.json()
.await
.expect("the history body parses");
let closes: Vec<&Value> = thread["events"]
.as_array()
.expect("events is a list")
.iter()
.filter(|event| event["event"]["type"] == "turn_done")
.collect();
let last = closes.last().map(|event| event["event"]["outcome"].clone());
assert!(
last.as_ref().is_none_or(|outcome| outcome == "aborted"),
"a cut turn is not handled: {thread}"
);
// The key reads idle, not leased: the ghost lease is gone. // The key reads idle, not leased: the ghost lease is gone.
let sessions: Value = client let sessions: Value = client
.get(format!("{base}/v1/sessions")) .get(format!("{base}/v1/sessions"))
@@ -3523,3 +4119,185 @@ async fn a_leased_session_is_not_deletable() {
assert_eq!(sessions[0]["key"], "interactive:web"); assert_eq!(sessions[0]["key"], "interactive:web");
assert_eq!(sessions[0]["state"], "leased", "{sessions:?}"); assert_eq!(sessions[0]["state"], "leased", "{sessions:?}");
} }
/// The turn a restart cut must not wear the previous turn's outcome. A
/// record keeps the outcome of its last release, so a dispatch that
/// checkpointed its prompt and the model's first words and then died
/// would read back as "handled" beside text it never finished: handled
/// is what the turn before it was. Boot releases the dead lease as
/// superseded, and the transcript says aborted.
#[tokio::test]
async fn a_restart_cut_turn_reads_aborted_not_the_previous_outcome() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("dispatch.db");
let key = ResourceKey::from("github:pull:acme/widgets#2");
{
let store = SqliteStore::open(&db).expect("the store opens");
let mut record = rhema_rsd::KeyRecord::fresh(key.clone(), 1);
let mut session = rhema_rsd::Session::fresh(key.clone(), 1);
session.core.history = vec![
Message::text(Role::User, "address the review feedback"),
Message::text(Role::Assistant, "I'll start by looking at the workspace."),
];
record.session = Some(session);
// The dispatch before this one finished handled, and its release
// is the record's last outcome.
record.last_outcome = Some(rhema_rsd::Outcome::Handled);
// This one held a lease when the process died.
record.state = rhema_rsd::KeyState::Leased;
record.lease = Some(rhema_rsd::LeaseRecord {
id: rhema_rsd::LeaseId::new("lease-old"),
holder: "the-old-process".to_owned(),
acquired_at: 1,
expires_at: u64::MAX,
});
store.save(record, None).expect("the record seeds");
}
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
daemon.bootstrap().await.expect("recovery runs");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let body: Value = client
.get(format!(
"{base}/v1/sessions/github%3Apull%3Aacme%2Fwidgets%232/history"
))
.send()
.await
.expect("the history request goes out")
.json()
.await
.expect("the history body parses");
let events = body["events"].as_array().expect("events is a list");
let close = events
.iter()
.find(|event| event["event"]["type"] == "turn_done")
.expect("the cut turn closes");
assert_eq!(
close["event"]["outcome"], "aborted",
"the cut turn is not the handled turn before it: {body}"
);
assert_eq!(
close["event"]["reply"], "I'll start by looking at the workspace.",
"what the turn said before it was cut still reads: {body}"
);
}
/// A key the resident context does not own has no turn record: its
/// handler never streams, and the events route refuses it. The history
/// route still opens it, read-only, from the session stash the step
/// engine checkpointed — the same page shape, cut the same way, so a
/// chat surface paints a finished forge thread with its own renderer.
#[tokio::test]
async fn a_forge_thread_reads_back_as_a_read_only_snapshot() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("dispatch.db");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// What a finished dispatch leaves behind: the engine's own history
// in the record's session stash.
let key = ResourceKey::from("github:issue:acme/widgets#7");
{
let store = SqliteStore::open(&db).expect("the store opens");
let mut record = rhema_rsd::KeyRecord::fresh(key.clone(), 1);
let mut session = rhema_rsd::Session::fresh(key.clone(), 1);
session.core.history = vec![
Message::text(Role::User, "review the failing check"),
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall {
id: "call-1".to_owned(),
name: "bash".to_owned(),
args: json!({"command": "gh pr checks 7"}),
provider_data: Value::Null,
})],
},
Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(rhema_core::ToolResult {
id: "call-1".to_owned(),
content: "build\tfail\t2m".to_owned(),
is_error: false,
code: Some(1),
images: Vec::new(),
})],
},
Message::text(Role::Assistant, "The build is red; rerunning."),
];
record.session = Some(session);
record.last_outcome = Some(rhema_rsd::Outcome::Handled);
store.save(record, None).expect("the record seeds");
}
let page = client
.get(format!(
"{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/history"
))
.send()
.await
.expect("the history request goes out");
assert_eq!(page.status(), 200, "a stash has a transcript to read");
let body: Value = page.json().await.expect("the body parses");
assert_eq!(body["read_only"], true, "the client must not open a stream");
assert_eq!(body["more"], false);
let events = body["events"].as_array().expect("events is a list");
let types: Vec<&str> = events
.iter()
.map(|entry| entry["event"]["type"].as_str().expect("a type"))
.collect();
assert_eq!(
types,
[
"user_message",
"tool_start",
"tool_result",
"text_delta",
"turn_done"
],
"{events:?}"
);
assert_eq!(events[0]["event"]["text"], "review the failing check");
assert_eq!(events[2]["event"]["name"], "bash");
assert_eq!(
events[2]["event"]["command"], "gh pr checks 7",
"the shell's command line survives the stash"
);
assert_eq!(events[2]["event"]["code"], 1);
assert_eq!(events[4]["event"]["reply"], "The build is red; rerunning.");
// Read-only for real: the message route still refuses the prefix,
// and the stream route refuses it too — a client that followed
// `read_only=false` would retry a 400 forever.
let refused = client
.post(format!(
"{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/messages"
))
.json(&json!({"text": "hello"}))
.send()
.await
.expect("the message posts");
assert_eq!(refused.status(), 400);
let stream = client
.get(format!(
"{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/events"
))
.send()
.await
.expect("the events request goes out");
assert_eq!(stream.status(), 400);
}
+222
View File
@@ -0,0 +1,222 @@
//! 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,
git: 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"),
)
}
+11 -5
View File
@@ -3,11 +3,12 @@
name: identity_set name: identity_set
description: >- description: >-
Set your own presentation identity: the name, mark, initials, Set your own presentation identity: the name, mark, initials,
tagline, and signoff the interfaces render, and your avatar or logo tagline, and signoff the interfaces render, an email to commit and
images. This is how you look, not who you are — personality lives in write as, and your avatar or logo images. This is how you look, not
SOUL.md. Leave a field out to keep what is set; an empty string who you are — personality lives in SOUL.md. Leave a field out to
clears it. The avatar and logo take a workspace-relative path to an keep what is set; an empty string clears it. The avatar and logo
image file (png, jpeg, gif, or webp, under 2 MiB — svg is refused). take a workspace-relative path to an image file (png, jpeg, gif, or
webp, under 2 MiB — svg is refused).
parameters: parameters:
type: object type: object
properties: properties:
@@ -16,6 +17,11 @@ parameters:
description: >- description: >-
Display name: message author, window title, notifications. Up Display name: message author, window title, notifications. Up
to 64 chars. to 64 chars.
email:
type: string
description: >-
The author address on the commits your workspaces make. Up to
120 chars.
mark: mark:
type: string type: string
description: Glyph or emoji for the rail and favicon. Up to 8 chars. description: Glyph or emoji for the rail and favicon. Up to 8 chars.
+26 -44
View File
@@ -10,55 +10,14 @@ WORKDIR /build
# Manifests first: the registry cache this populates survives source edits. # Manifests first: the registry cache this populates survives source edits.
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ 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-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 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 COPY integrations/rhema-calendar-integration/Cargo.toml integrations/rhema-calendar-integration/Cargo.toml
# workspace: the member manifests inherit from that root, so the root
# rides along with them.
COPY tools/Cargo.toml tools/Cargo.toml COPY tools/Cargo.toml tools/Cargo.toml
COPY tools/contract/Cargo.toml tools/contract/Cargo.toml COPY tools/contract/Cargo.toml tools/contract/Cargo.toml
COPY tools/common/Cargo.toml tools/common/Cargo.toml COPY tools/common/Cargo.toml tools/common/Cargo.toml
COPY tools/notify/Cargo.toml tools/notify/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 # Cargo validates explicit target
# paths at manifest-parse time, so the fetch needs stub files at every # paths at manifest-parse time, so the fetch needs stub files at every
# declared target path: src/ for every member, plus examples/tests/benches # declared target path: src/ for every member, plus examples/tests/benches
@@ -89,9 +48,26 @@ FROM debian:stable-slim
# bash and git are load-bearing, not conveniences: the coding agent shells # bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces. # out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \ && apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# gob (github.com/juanibiapina/gob) is the agent's process manager: a turn
# starts a dev server or a build with `gob add`, and a later turn reads its
# logs, status and ports. Without it a long command either blocks the turn
# for its whole run or is backgrounded with `&`, which no later turn can
# find again. The release is a static binary, so nothing rides along but
# the file; its state lands under XDG_STATE_HOME (/data/state, the volume)
# and its socket under XDG_RUNTIME_DIR. Only amd64 and arm64 are published,
# and a build for any other arch fails here rather than shipping a daemon
# with no `gob` on PATH.
ARG GOB_VERSION=3.9.0
RUN arch="$(dpkg --print-architecture)" \
&& curl -fsSL -o /tmp/gob.tar.gz \
"https://github.com/juanibiapina/gob/releases/download/v${GOB_VERSION}/gob_${GOB_VERSION}_linux_${arch}.tar.gz" \
&& tar -xzf /tmp/gob.tar.gz -C /usr/local/bin gob \
&& rm /tmp/gob.tar.gz \
&& gob --version
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name. # Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
RUN useradd --uid 1000 --user-group --create-home claw \ RUN useradd --uid 1000 --user-group --create-home claw \
&& install -d -o 1000 -g 1000 /config /data && install -d -o 1000 -g 1000 /config /data
@@ -100,8 +76,14 @@ COPY --from=builder /build/target/release/rhema-claw /usr/local/bin/rhema-claw
# The chart passes --config /config/claw.yaml (the ConfigMap mount) and # The chart passes --config /config/claw.yaml (the ConfigMap mount) and
# mounts the state PVC at /data; these defaults serve a bare `docker run`. # mounts the state PVC at /data; these defaults serve a bare `docker run`.
#
# XDG_RUNTIME_DIR is gob's socket directory. Left unset, gob looks in
# /run/user/1000, which nothing creates here, and its daemon dies with
# "socket not created". A socket does not belong on the volume (an NFS
# PVC cannot hold one), so it lives in the container's own /tmp.
ENV XDG_CONFIG_HOME=/config \ ENV XDG_CONFIG_HOME=/config \
XDG_STATE_HOME=/data/state XDG_STATE_HOME=/data/state \
XDG_RUNTIME_DIR=/tmp/run
VOLUME /data VOLUME /data
EXPOSE 7799 EXPOSE 7799
+5 -42
View File
@@ -12,53 +12,16 @@ WORKDIR /build
# Manifests first: the registry cache this populates survives source edits. # Manifests first: the registry cache this populates survives source edits.
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ 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-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 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 COPY integrations/rhema-calendar-integration/Cargo.toml integrations/rhema-calendar-integration/Cargo.toml
# workspace: the member manifests inherit from that root, so the root
# rides along with them.
COPY tools/Cargo.toml tools/Cargo.toml COPY tools/Cargo.toml tools/Cargo.toml
COPY tools/contract/Cargo.toml tools/contract/Cargo.toml COPY tools/contract/Cargo.toml tools/contract/Cargo.toml
COPY tools/common/Cargo.toml tools/common/Cargo.toml COPY tools/common/Cargo.toml tools/common/Cargo.toml
COPY tools/notify/Cargo.toml tools/notify/Cargo.toml COPY tools/notify/Cargo.toml tools/notify/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
# Resolution reads the vendored crossterm (the root manifest path-patches # rides along with them.
# to it) even though the image builds the daemon, which does not link it.
COPY vendor/ vendor/
# Cargo validates explicit target # Cargo validates explicit target
# paths at manifest-parse time, so the fetch needs stub files at every # 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 # load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
# neither). # neither).
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \ && apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name. # 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 description: "The resident forge-watching agent daemon: forge watches and a
chat HTTP surface over one SQLite store." chat HTTP surface over one SQLite store."
type: application type: application
version: 0.1.0 version: 0.4.1
appVersion: "0.1.0" appVersion: "0.4.1"
+8
View File
@@ -31,6 +31,14 @@ config:
# - forge: github # - forge: github
# repo: acme/widgets # repo: acme/widgets
watches: [] watches: []
# The git identity the daemon writes into its user's global git
# config at boot, so workspace commits carry the agent as author.
# A field set here wins over the agent's own identity (Agent ·
# General in the UI); values the daemon did not write are left
# alone. Example:
# git:
# name: claw
# email: claw@example.net
service: service:
type: ClusterIP type: ClusterIP
@@ -15,20 +15,20 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] } rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped # The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's # like the task scheduler's
rhema-autonomous-agent = { path = "../../crates/rhema-autonomous-agent", version = "0.2.3" } rhema-autonomous-agent = "0.4.2"
# The reminder source ingests its slots into a `Dispatcher`; the event # The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's # and key-function shapes are the dispatcher's
rhema-rsd = { path = "../../crates/rhema-rsd", version = "0.2.3" } rhema-rsd = "0.4.2"
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
async-trait = { workspace = true } async-trait = { workspace = true }
# HTTP against the three feed kinds: one bounded request per poll, no # HTTP against the three feed kinds: one bounded request per poll, no
# streaming # streaming
reqwest = { version = "0.12", features = ["json"] } reqwest = { version = "0.13", features = ["json", "query"] }
# The CalDAV adapter reads 207 multistatus bodies; the element set it # The CalDAV adapter reads 207 multistatus bodies; the element set it
# cares about is small enough that a pull parser beats a DOM # cares about is small enough that a pull parser beats a DOM
quick-xml = "0.41" quick-xml = "0.42"
# Every wire time (RFC 3339, iCalendar's compact `YYYYMMDDTHHMMSS[Z]`, # Every wire time (RFC 3339, iCalendar's compact `YYYYMMDDTHHMMSS[Z]`,
# `VALUE=DATE` all-days) normalizes to an OffsetDateTime, and the # `VALUE=DATE` all-days) normalizes to an OffsetDateTime, and the
# vocabulary's instants round-trip as RFC 3339. # vocabulary's instants round-trip as RFC 3339.
@@ -186,10 +186,9 @@ fn compact_z(at: OffsetDateTime) -> String {
/// namespace URIs the element binds. Matching local names inside a /// namespace URIs the element binds. Matching local names inside a
/// `prop` stat is the pragmatic read every DAV client ships. /// `prop` stat is the pragmatic read every DAV client ships.
fn local_name(name: quick_xml::name::QName<'_>) -> &str { fn local_name(name: quick_xml::name::QName<'_>) -> &str {
// The reader was built from a &str, so every borrowed name is // The reader was built from a &str, so a borrowed name is valid
// UTF-8 already; a decoding failure cannot say anything truer than // UTF-8 by construction; no decode step can fail here.
// "not the element we were looking for". name.local_name().into_inner()
std::str::from_utf8(name.local_name().into_inner()).unwrap_or("")
} }
/// Pulls every `calendar-data` value out of a 207 multistatus, in /// Pulls every `calendar-data` value out of a 207 multistatus, in
@@ -215,10 +214,8 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
// where the iCalendar needs CRLF, and an unexpanded // where the iCalendar needs CRLF, and an unexpanded
// reference would fold the whole object into one line // reference would fold the whole object into one line
// and read as quietly empty. // and read as quietly empty.
let decoded = text let content = text.xml10_content();
.xml10_content() let decoded = unescape(&content)
.map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?;
let decoded = unescape(&decoded)
.map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?; .map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?;
current.push_str(&decoded); current.push_str(&decoded);
} }
@@ -228,9 +225,7 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
Ok(Some(ch)) => current.push(ch), Ok(Some(ch)) => current.push(ch),
// A named entity (`&amp;`): the escape table's. // A named entity (`&amp;`): the escape table's.
Ok(None) => { Ok(None) => {
let raw = reference.xml10_content().map_err(|err| { let raw = reference.xml10_content();
CalendarError::Parse(format!("multistatus text: {err}"))
})?;
let entity = format!("&{raw};"); let entity = format!("&{raw};");
let decoded = unescape(&entity).map_err(|err| { let decoded = unescape(&entity).map_err(|err| {
CalendarError::Parse(format!("multistatus text: {err}")) CalendarError::Parse(format!("multistatus text: {err}"))
@@ -243,7 +238,7 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
} }
} }
Ok(XmlEvent::CData(text)) if capturing => { Ok(XmlEvent::CData(text)) if capturing => {
current.push_str(&String::from_utf8_lossy(text.as_ref())); current.push_str(&text);
} }
Ok(XmlEvent::End(element)) => { Ok(XmlEvent::End(element)) => {
if capturing && local_name(element.name()) == "calendar-data" { if capturing && local_name(element.name()) == "calendar-data" {
@@ -13,14 +13,14 @@ publish = false
[dependencies] [dependencies]
# The dispatch seam: watches ingest into a Dispatcher # The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = { path = "../../crates/rhema-rsd", version = "0.2.3" } rhema-rsd = "0.4.2"
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
async-trait = { workspace = true } async-trait = { workspace = true }
# HTTP against the three forge REST APIs: JSON request/response bodies, # HTTP against the three forge REST APIs: JSON request/response bodies,
# no streaming # no streaming
reqwest = { version = "0.12", features = ["json"] } reqwest = { version = "0.13", features = ["json", "query"] }
[dev-dependencies] [dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
@@ -230,6 +230,17 @@ pub struct Notification {
/// When the notification row was last touched. The poll cursor /// When the notification row was last touched. The poll cursor
/// advances to the newest of these. /// advances to the newest of these.
pub timestamp: Timestamp, pub timestamp: Timestamp,
/// What the backend's read-marking route keys on, when it has one —
/// GitHub's `PUT /notifications/threads/{id}` takes the numeric
/// notification id, which [`Notification::id`] embeds only as text
/// (its suffix is the dedup timestamp, not the row's identity).
/// `None` on a backend with no read route.
///
/// Defaulted on deserialize: rows already in a dispatcher inbox were
/// written before this field existed, and a replay must not fail on
/// one.
#[serde(default)]
pub read_key: Option<String>,
/// The untouched wire row, minus the keys the notification lifts. /// The untouched wire row, minus the keys the notification lifts.
pub raw: serde_json::Value, pub raw: serde_json::Value,
} }
@@ -380,6 +391,46 @@ impl Timestamp {
pub fn epoch_secs(&self) -> i64 { pub fn epoch_secs(&self) -> i64 {
self.secs 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. /// A run of ASCII digits at `range`, as its number.
@@ -524,4 +575,32 @@ mod tests {
.expect("deserializes"); .expect("deserializes");
assert_eq!(round, event); 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"
);
}
} }
@@ -16,7 +16,9 @@
use async_trait::async_trait; use async_trait::async_trait;
use crate::error::ForgeError; use crate::error::ForgeError;
use crate::event::{ForgeEvent, ForgeThreadKind, NotificationPage, RepoRef, Snapshot, Timestamp}; use crate::event::{
ForgeEvent, ForgeThreadKind, Notification, NotificationPage, RepoRef, Snapshot, Timestamp,
};
/// One poll's worth of activity, with the cursor to continue from. /// One poll's worth of activity, with the cursor to continue from.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@@ -99,6 +101,38 @@ pub trait Forge: Send + Sync {
&self, &self,
since: Option<&Timestamp>, since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>; ) -> Result<NotificationPage, ForgeError>;
/// Marks `notification` read on the forge, so the account's feed
/// stops returning it.
///
/// The feed is at-least-once: `since` is inclusive at the boundary
/// and the cursor only ever advances to the newest row seen, so a row
/// that the poll cannot get past — anything at or before the cursor,
/// every poll — comes back for as long as the forge considers it
/// unread. Dedup ids absorb a repeat *within* one pass, but a row
/// re-read on the next pass is a fresh event with the same id, and a
/// restart drops the in-memory cursor entirely and asks for the whole
/// unread feed again. Deciding a row is therefore not the same as
/// consuming it; this is the call that consumes it.
///
/// The default is a no-op: a backend with no read route repeats its
/// rows, which its dedup ids absorb — noisier, never wrong.
async fn mark_read(&self, _notification: &Notification) -> Result<(), ForgeError> {
Ok(())
}
/// 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)] #[cfg(test)]
@@ -477,20 +477,17 @@ fn review_event(
/// The comment event a repo-wide comments row carries. /// The comment event a repo-wide comments row carries.
fn comment_event(row: &WireComment, repo: &RepoRef) -> Result<Option<ForgeEvent>, ForgeError> { fn comment_event(row: &WireComment, repo: &RepoRef) -> Result<Option<ForgeEvent>, ForgeError> {
let id = required(row.id, "comment id")?; let id = required(row.id, "comment id")?;
let issue_url = required(row.issue_url.clone(), "comment issue_url")?; let number = comment_parent(row).ok_or_else(|| {
let number = parent_number(&issue_url).ok_or_else(|| {
ForgeError::Parse(format!( 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( let timestamp = required(
row.updated_at.clone().or_else(|| row.created_at.clone()), row.updated_at.clone().or_else(|| row.created_at.clone()),
"comment timestamp", "comment timestamp",
)?; )?;
let is_pr = row let is_pr = comment_is_pr(row);
.pull_request_url
.as_deref()
.is_some_and(|url| !url.is_empty());
Ok(Some(ForgeEvent { Ok(Some(ForgeEvent {
id: format!("gitea:comment:{id}"), id: format!("gitea:comment:{id}"),
kind: EventKind::Comment, 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> { 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 /// The fixed [`NotificationReason::Other`] spelling every reason-less
@@ -549,6 +585,9 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(), title: subject.title.clone(),
url: None, url: None,
timestamp: updated, timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()), raw: Value::Object(row.raw.clone()),
})) }))
} }
@@ -690,6 +729,11 @@ impl Forge for GiteaForge {
Ok(()) 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( async fn snapshot(
&self, &self,
repo: &RepoRef, repo: &RepoRef,
@@ -895,4 +939,57 @@ mod tests {
.expect("comment carries an event"); .expect("comment carries an event");
assert!(!event.is_pr); 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:?}");
}
} }
@@ -120,6 +120,17 @@ impl GitHubForge {
} }
} }
/// A PUT builder for `path` with auth applied.
fn put(&self, path: &str) -> reqwest::RequestBuilder {
let base = &self.base_url;
let request = self.http.put(format!("{base}{path}"));
if self.token.is_empty() {
request
} else {
request.bearer_auth(&self.token)
}
}
/// Follows `per_page`/`page` pagination until a short page. /// Follows `per_page`/`page` pagination until a short page.
async fn paged<T: DeserializeOwned>( async fn paged<T: DeserializeOwned>(
&self, &self,
@@ -287,7 +298,9 @@ struct WireComment {
/// One row of the account notifications feed. /// One row of the account notifications feed.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
struct WireNotification { 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>, id: Option<i64>,
#[serde(default)] #[serde(default)]
reason: Option<String>, reason: Option<String>,
@@ -452,6 +465,32 @@ fn parent_number(url: &str) -> Option<u64> {
url.trim_end_matches('/').rsplit('/').next()?.parse().ok() 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 /// The notification a notifications row carries. GitHub's `reason` field
/// is the row's whole why; the subject's API URL yields the thread. /// is the row's whole why; the subject's API URL yields the thread.
fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> { fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> {
@@ -481,6 +520,9 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(), title: subject.title.clone(),
url: None, url: None,
timestamp: updated, timestamp: updated,
// `PUT /notifications/threads/{id}` is keyed on this same id:
// the notification, not the thread's number.
read_key: Some(id.to_string()),
raw: Value::Object(row.raw.clone()), raw: Value::Object(row.raw.clone()),
})) }))
} }
@@ -646,6 +688,16 @@ impl Forge for GitHubForge {
Ok(()) 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( async fn snapshot(
&self, &self,
repo: &RepoRef, repo: &RepoRef,
@@ -698,6 +750,22 @@ impl Forge for GitHubForge {
} }
Ok(NotificationPage::finish(notifications, since)) Ok(NotificationPage::finish(notifications, since))
} }
async fn mark_read(&self, notification: &Notification) -> Result<(), ForgeError> {
let Some(read_key) = notification.read_key.as_deref() else {
// A row built without one is a shape break, not a forge
// outage: say so instead of silently re-reading it forever.
return Err(ForgeError::Parse(format!(
"notification {} carries no read key",
notification.id
)));
};
let path = format!("/notifications/threads/{read_key}");
let response = self.put(&path).send().await.map_err(ForgeError::network)?;
// 205 Reset Content: marked, nothing to decode.
ensure_success(response).await?;
Ok(())
}
} }
#[cfg(test)] #[cfg(test)]
@@ -860,4 +928,63 @@ mod tests {
assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3"); assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3");
assert!(event.raw.get("title").is_none()); 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"
);
assert_eq!(notification.read_key.as_deref(), Some("27210544329"));
}
#[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"
);
assert_eq!(notification.read_key.as_deref(), Some("42188"));
}
#[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}");
}
} }
@@ -331,6 +331,9 @@ fn todo_notification(row: &WireTodo) -> Result<Option<Notification>, ForgeError>
title: target.title.clone(), title: target.title.clone(),
url: row.target_url.clone(), url: row.target_url.clone(),
timestamp: updated, timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()), raw: Value::Object(row.raw.clone()),
})) }))
} }
@@ -523,6 +526,18 @@ impl Forge for GitLabForge {
Ok(()) 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( async fn snapshot(
&self, &self,
repo: &RepoRef, repo: &RepoRef,
@@ -97,6 +97,7 @@ mod tests {
title: None, title: None,
url: None, url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"), timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}), raw: serde_json::json!({}),
} }
} }
@@ -177,12 +177,24 @@ impl Watcher {
.cloned() .cloned()
} }
/// One poll of `repo`: the page's events are ingested in feed order /// One poll of `repo` from the watcher's own cursor.
/// and the cursor advances to the page's. Returns how many events were
/// fed to the dispatcher — replayed ids included, they dedup there.
pub async fn poll(&self, forge: &dyn Forge, repo: &RepoRef) -> Result<usize, WatchError> { pub async fn poll(&self, forge: &dyn Forge, repo: &RepoRef) -> Result<usize, WatchError> {
let since = self.cursor(repo); 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 now = SystemClock.now_millis();
let mut fed = 0; let mut fed = 0;
for event in &page.events { 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.repo, RepoRef::new("acme", "widgets"));
assert_eq!(note.title.as_deref(), Some("Fix the gate")); 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())
);
}
@@ -2,8 +2,8 @@
//! wiremock server. Zero network. //! wiremock server. Zero network.
use rhema_forge_integration::{ use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, NotificationReason, RepoRef, EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, Notification, NotificationReason,
Timestamp, RepoRef, Timestamp,
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
use wiremock::matchers::{header, method, path, query_param}; use wiremock::matchers::{header, method, path, query_param};
@@ -532,3 +532,102 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses")) Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses"))
); );
} }
/// A notification row, as the account's feed sends it.
fn notification_row(id: i64, reason: &str, number: u64) -> Value {
json!({
"id": id,
"unread": true,
"reason": reason,
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": format!("https://api.github.com/repos/acme/widgets/issues/{number}"),
"type": "Issue"
},
"repository": { "full_name": "acme/widgets" }
})
}
/// Deciding a row is not consuming it: the feed keeps returning anything
/// the account still has unread, so the read route is what ends the
/// repeat. It keys on the notification's own id, not the thread number —
/// the dedup id keeps that integer only as text.
#[tokio::test]
async fn marking_a_notification_read_puts_its_thread() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([notification_row(
42188,
"review_requested",
142
)])),
)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/notifications/threads/42188"))
.and(header("authorization", "Bearer tok"))
.respond_with(ResponseTemplate::new(205))
.mount(&server)
.await;
let forge = forge(&server);
let page = forge.notifications(None).await.expect("poll succeeds");
let notification = &page.notifications[0];
forge.mark_read(notification).await.expect("marks read");
let requests = server.received_requests().await.expect("recording is on");
let puts: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(puts.len(), 1, "one read call, on the row's id");
assert_eq!(puts[0].url.path(), "/notifications/threads/42188");
}
/// A row that reaches the caller with no read key is a shape break, not a
/// silent no-op: re-reading the same thread forever is the failure this
/// whole route exists to stop.
#[tokio::test]
async fn a_notification_without_a_read_key_fails_loudly() {
// Defaulted on deserialize, so this is also the row an inbox written
// before the field existed decodes to.
let notification: Notification = serde_json::from_value(json!({
"id": "github:notification:42188@2026-10-05T12:00:00Z",
"reason": "review_requested",
"repo": { "owner": "acme", "name": "widgets" },
"number": 142,
"is_pr": false,
"actor": null,
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-05T12:00:00Z",
"raw": {}
}))
.expect("a read-key-less row parses");
let err = GitHubForge::new("tok")
.mark_read(&notification)
.await
.expect_err("loud failure");
assert!(matches!(err, ForgeError::Parse(_)), "got: {err:?}");
}
/// 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") 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" edition = "2024"
rust-version = "1.85" rust-version = "1.85"
license = "MIT" license = "MIT"
repository = "https://github.com/vhaudiquet/rhema" repository = "https://git.vhaudiquet.fr/vhaudiquet/rhema-claw"
authors = ["Valentin Haudiquet"] authors = ["Valentin Haudiquet"]
[workspace.dependencies] [workspace.dependencies]
+60 -22
View File
@@ -60,9 +60,12 @@ Two consequences worth knowing before changing this code:
fire-and-forget (202); the reply streams back on fire-and-forget (202); the reply streams back on
`GET /v1/sessions/{key}/events`. The transcript here is a mirror of `GET /v1/sessions/{key}/events`. The transcript here is a mirror of
the stream, and the stream opens on the newest turn before the live the stream, and the stream opens on the newest turn before the live
feed — a reload paints the latest conversation at once instead of feed. That turn comes back whole even when it is longer than the
replaying a session that may have run for weeks, and the turns above replay window, so a reload never lands mid-reply with the file the
it come from `GET /v1/sessions/{key}/history`, one whole turn per turn handed over above the cut. A reload paints the latest
conversation at once instead of replaying a session that may have run
for weeks, and the turns above it come from
`GET /v1/sessions/{key}/history`, one whole turn per
page, as the reader scrolls up (or right away, while the transcript page, as the reader scrolls up (or right away, while the transcript
is shorter than the screen). So the transcript survives the browser, is shorter than the screen). So the transcript survives the browser,
not just the claw. not just the claw.
@@ -90,12 +93,21 @@ Two consequences worth knowing before changing this code:
## What the transcript does with the stream ## 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 - **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 `PASTE_INLINE_LINES`) never lands in the composer; it stages as a
droppable chip (`▣1 42L`) and embeds into the sent text as droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s the plain draft — the claw composes the record (the payload in
`paste::embed` keeps — so the transcript renders each embed back as place, the span note beside it) — so no mark ever crosses the wire.
a chip in place of the payload. An unpaired mark is literal text. 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 - **The agent can ask.** A `consent_request` event renders as an
inline card: kind `secret` gets a password input plus submit, kind inline card: kind `secret` gets a password input plus submit, kind
`phone` gets Approve/Deny, and both carry a deny link `phone` gets Approve/Deny, and both carry a deny link
@@ -103,11 +115,16 @@ Two consequences worth knowing before changing this code:
and again on the stream's `consent_resolved` echo; nothing persists and again on the stream's `consent_resolved` echo; nothing persists
client-side, so a reload rebuilds the cards from the replay. client-side, so a reload rebuilds the cards from the replay.
- **Attachments render inline.** An `attachment` event becomes a card - **Attachments render inline.** An `attachment` event becomes a card
— media glyph, file name, B/KB/MB size, caption. Images fetch the — media glyph, file name, B/KB/MB size, caption. The media kind comes
bearer-guarded bytes (`GET /v1/attachments/{id}`, blob → object URL, from the file extension, decided by the daemon when it stores the
like the identity images) and render capped at 240px; code and file file, so a `.png` renders and a `.patch` downloads without the client
cards download on click. Object URLs cache per id, so a replay never guessing. Images fetch the bearer-guarded bytes
refetches. (`GET /v1/attachments/{id}`, blob → object URL, like the identity
images) and render capped at 240px; every card downloads on click,
images included. A card lives inside the turn that produced it, so
the scan that fetches image bytes walks finished turns and the live
one, not just the top-level rows. Object URLs cache per id, so a
replay never refetches.
- **Your images ride along.** The composer's `+` — and an image on the - **Your images ride along.** The composer's `+` — and an image on the
clipboard — stage as removable chips (`▣1 photo.png 1.2 MB`), the clipboard — stage as removable chips (`▣1 photo.png 1.2 MB`), the
claw's own budget enforced client-side (8 a message, 5 MiB decoded claw's own budget enforced client-side (8 a message, 5 MiB decoded
@@ -119,11 +136,21 @@ Two consequences worth knowing before changing this code:
- **Sessions are created in place.** The sidebar's `+` form posts - **Sessions are created in place.** The sidebar's `+` form posts
`POST /v1/sessions` with a client-validated name `POST /v1/sessions` with a client-validated name
(`[A-Za-z0-9._-]{1,64}`), switches the chat to the new key, and (`[A-Za-z0-9._-]{1,64}`), switches the chat to the new key, and
lets 400/409 land in the error banner. The inventory lists only the lets 400/409 land in the error banner. The interactive prefixes
resident prefixes (`interactive:`, `task:`, `calendar:`) — the ones the (`interactive:`) list above the fold; *others* holds the whole rest
message, event and history routes answer for. The phone's status keys of the inventory — `task:`, `calendar:`, the phone's keys
(`phone:…`), the coding jobs' `job:<instance>#<id>` keys and forge keys (`phone:…`), the coding jobs' `job:<instance>#<id>` keys and forge
stay out, and the full list stays on the wire. keys.
- **Every row opens, and some open read-only.** A resident key
(`interactive:`, `task:`, `phone:`, `calendar:`) has a live stream,
and the chat resets its mirror whenever that stream reopens. A key
outside them has none: its dispatch runs outside the hub. The panel
fetches `GET /v1/sessions/{key}/history` instead, which serves the
session the engine checkpointed, and shows the turns with a
`snapshot` status and the composer replaced by a line saying why.
The inventory's `revision` is that view's only reload signal: a poll
that sees it move fetches the newest page again, so an older page
the reader walked back to survives polling until a turn runs.
- **Deleting a session is a decision, not a click.** The row's delete - **Deleting a session is a decision, not a click.** The row's delete
button only names the key; the shell's dialog spells out that the button only names the key; the shell's dialog spells out that the
turn history goes with it, and `DELETE /v1/sessions/{key}` runs on turn history goes with it, and `DELETE /v1/sessions/{key}` runs on
@@ -132,6 +159,16 @@ Two consequences worth knowing before changing this code:
error banner like every other refusal, and the chat moves to the error banner like every other refusal, and the chat moves to the
first remaining session, the stream's watcher following the key so first remaining session, the stream's watcher following the key so
nothing keeps streaming a session that no longer exists. nothing keeps streaming a session that no longer exists.
- **Every row is controllable.** Beside the delete button, on hover:
`hold` posts `POST /v1/sessions/{key}/pause` and the row badges
`held` — queued work accumulates and nothing dispatches until `run`
posts the resume, both answered by the inventory's `paused` flag.
`stop` posts `POST /v1/sessions/{key}/abort`: a live turn is cut
(the stream closes on its `aborted` marker, in the warn tone, since
nothing failed), and an idle key's queued work is dropped instead —
the notice says which, from the answer's `cut`/`dropped`. A key with
neither running nor queued work has `stop` disabled rather than
sending a no-op.
## Layout ## Layout
@@ -175,10 +212,10 @@ app/
raw HTML escaped, styles in main.css .md) raw HTML escaped, styles in main.css .md)
ClawBanner.vue the one error/notice banner surface ClawBanner.vue the one error/notice banner surface
ChatPanel.vue transcript: sent lines (paste chips), ChatPanel.vue transcript: sent lines (paste chips),
streamed turns as bash shell lines and streamed turns as reply text plus
glyph rows, consent + attachment consent + attachment cards; the growing
cards; the growing composer; agent composer; agent replies render through
replies render through AppMarkdown AppMarkdown
SessionsSidebar.vue conversable dispatch keys (phone status SessionsSidebar.vue conversable dispatch keys (phone status
keys hidden), interactive first; the keys hidden), interactive first; the
+ form creates a session + form creates a session
@@ -193,7 +230,8 @@ app/
composables/ composables/
useClaw.ts the typed API client + fetch-based SSE useClaw.ts the typed API client + fetch-based SSE
useTranscript.ts folds TurnEvents into renderable turn 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/ server/
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
``` ```
+216 -45
View File
@@ -17,10 +17,12 @@ import type {
NewAccount, NewAccount,
ProviderCredentials, ProviderCredentials,
ProvidersState, ProvidersState,
SandboxSelection,
SandboxState,
StreamStatus, StreamStatus,
} from '~/composables/useClaw' } from '~/composables/useClaw'
import { useTranscript } from '~/composables/useTranscript' import { composeChips, useTranscript } from '~/composables/useTranscript'
import type { StagedImage } from '~/composables/useTranscript' import type { AttachmentCard, StagedImage } from '~/composables/useTranscript'
const TOKEN_STORE_KEY = 'claw.token' const TOKEN_STORE_KEY = 'claw.token'
const ACTIVE_STORE_KEY = 'claw.activeKey' const ACTIVE_STORE_KEY = 'claw.activeKey'
@@ -58,7 +60,13 @@ const SETTINGS_SECTIONS: { label: string; entries: { id: string; label: string }
], ],
}, },
{ label: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] }, { 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 { function parseHash(): Route {
@@ -113,9 +121,12 @@ const {
// for weeks costs nothing up front and still reaches its first message. // for weeks costs nothing up front and still reaches its first message.
const olderAvailable = ref(true) const olderAvailable = ref(true)
// Attachment ids this page already tried to fetch; a failed fetch is // The cards this page already tried to fetch. Keyed by the card object
// not retried until the stream resets and clears the set. // rather than the attachment id: a page read, a mirror reset, or a live
const attemptedAttachments = new Set<string>() // turn folding into a record builds new cards, and a new card deserves
// its fetch — the useClaw cache answers a repeat with the blob it
// already holds, so a retry costs no request.
let attemptedAttachments = new WeakSet<object>()
// Image cards need their bytes before they can render: fetched as the // Image cards need their bytes before they can render: fetched as the
// card appears, not on any timer. code/file fetch on download instead. // card appears, not on any timer. code/file fetch on download instead.
@@ -123,39 +134,49 @@ const attemptedAttachments = new Set<string>()
// their attachment ids, never the bytes; locally sent rows hold their // their attachment ids, never the bytes; locally sent rows hold their
// own object URLs. // own object URLs.
// //
// The watch is deep (rows mutate in place as their bytes land), and it // The cards sit at two depths. One handed over mid-turn lands in the
// fires on every streamed delta, so the scan covers only the items the // open turn's entries and rides into the finished turn with it, so a
// last pass did not see — the transcript only ever appends. // scan of the top-level rows alone would never see it and the card
let scannedItems = 0 // would stay a name with no picture. Every path that can hold a card is
// walked here; the attempt set makes a repeated pass free.
watch( function requestAttachmentImages(): void {
transcriptItems, const fetchAttachment = (attachment: AttachmentCard) => {
(items) => { const { id, media, url } = attachment
for (const item of items.slice(scannedItems)) { if (media !== 'image' || url !== null || attemptedAttachments.has(attachment)) return
if (item.kind === 'attachment') { attemptedAttachments.add(attachment)
const { id, media, url } = item.attachment claw
if (media !== 'image' || url !== null || attemptedAttachments.has(id)) continue .attachmentUrl(id)
attemptedAttachments.add(id) .then((fetched) => transcript.setAttachmentUrl(id, fetched))
.catch((err) => noteApiError(err))
}
for (const item of transcriptItems.value) {
if (item.kind === 'attachment') {
fetchAttachment(item.attachment)
} else if (item.kind === 'turn') {
for (const entry of item.turn.entries) {
if (entry.kind === 'attachment') fetchAttachment(entry.attachment)
}
} else if (item.kind === 'sent') {
for (const image of item.images) {
const { id, url } = image
if (id === null || url !== null || attemptedAttachments.has(image)) continue
attemptedAttachments.add(image)
claw claw
.attachmentUrl(id) .attachmentUrl(id)
.then((fetched) => transcript.setAttachmentUrl(id, fetched)) .then((fetched) => transcript.setSentImageUrl(id, fetched))
.catch((err) => noteApiError(err)) .catch((err) => noteApiError(err))
} else if (item.kind === 'sent') {
for (const image of item.images) {
const { id, url } = image
if (id === null || url !== null || attemptedAttachments.has(id)) continue
attemptedAttachments.add(id)
claw
.attachmentUrl(id)
.then((fetched) => transcript.setSentImageUrl(id, fetched))
.catch((err) => noteApiError(err))
}
} }
} }
scannedItems = items.length }
}, for (const entry of transcript.live.value?.entries ?? []) {
{ deep: true }, if (entry.kind === 'attachment') fetchAttachment(entry.attachment)
) }
}
watch([transcriptItems, transcript.live], requestAttachmentImages, {
deep: true,
immediate: true,
})
// --- the agent's identity -------------------------------------------- // --- the agent's identity --------------------------------------------
const identity = ref<AgentIdentity | null>(null) const identity = ref<AgentIdentity | null>(null)
@@ -265,6 +286,8 @@ const mutatingIdentity = ref(false)
const accounts = ref<ClawAccount[] | null>(null) const accounts = ref<ClawAccount[] | null>(null)
const accountsLoading = ref(false) const accountsLoading = ref(false)
const mutatingAccounts = ref(false) const mutatingAccounts = ref(false)
const sandboxState = ref<SandboxState | null>(null)
const savingSandbox = ref(false)
const streamStatus = ref<StreamStatus>('connecting') const streamStatus = ref<StreamStatus>('connecting')
const busy = ref(false) const busy = ref(false)
const authRequired = ref(false) const authRequired = ref(false)
@@ -300,6 +323,13 @@ async function refreshSessions(): Promise<void> {
try { try {
sessions.value = await claw.sessions() sessions.value = await claw.sessions()
apiError.value = null apiError.value = null
// A read-only thread has no stream to tell it a dispatch ran; the
// inventory's revision does. Reload the snapshot when it moved, and
// only then — a reload drops the pages the reader walked back to.
if (activeKey.value !== '' && !isResidentKey(activeKey.value) && !threadLoading) {
const revision = sessions.value.find((s) => s.key === activeKey.value)?.revision ?? null
if (revision !== threadRevision) void loadThread()
}
} catch (err) { } catch (err) {
noteApiError(err) noteApiError(err)
} finally { } finally {
@@ -367,6 +397,49 @@ async function confirmDeleteSession(): Promise<void> {
} }
} }
/** The pause gate: hold a key's dispatch, lift the hold. The inventory
* refresh carries the `paused` flag back to the sidebar. */
async function pauseSession(key: string): Promise<void> {
try {
await claw.pauseSession(key)
pushNotice(`${key} held`)
apiError.value = null
} catch (err) {
noteApiError(err)
}
void refreshSessions()
}
async function resumeSession(key: string): Promise<void> {
try {
await claw.resumeSession(key)
pushNotice(`${key} resumed`)
apiError.value = null
} catch (err) {
noteApiError(err)
}
void refreshSessions()
}
/** Abort: cut a live turn, or drop the key's queued work. The answer
* says which happened; the inventory refresh settles the row. */
async function abortSession(key: string): Promise<void> {
try {
const result = await claw.abortSession(key)
pushNotice(
result.cut
? `turn on ${key} stopped`
: result.dropped > 0
? `${result.dropped} queued item(s) dropped on ${key}`
: `nothing running on ${key}`,
)
apiError.value = null
} catch (err) {
noteApiError(err)
}
void refreshSessions()
}
async function refreshProviders(): Promise<void> { async function refreshProviders(): Promise<void> {
try { try {
providersState.value = await claw.providers() providersState.value = await claw.providers()
@@ -499,21 +572,54 @@ async function removeProvider(id: string): Promise<void> {
} }
} }
async function send(message: { text: string; images: StagedImage[] }): Promise<void> { async function refreshSandbox(): Promise<void> {
// The optimistic row renders the staged previews; the stream's try {
// user_message echo carries the stored ids and dedupes against it. 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'
: choice.kind === 'ssh'
? 'sandbox: ssh 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( const rowId = transcript.addSent(
message.text, composed.text,
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })), message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
composed.pastes,
) )
busy.value = true busy.value = true
try { try {
// Fire-and-forget by design: the claw answers 202 and the reply // Fire-and-forget by design: the claw answers 202 and the reply
// arrives on the event stream. The body carries the images only // arrives on the event stream. The chips and the images ride the
// when there are some. // body only when there are some.
await claw.sendMessage( await claw.sendMessage(
activeKey.value, activeKey.value,
message.text, message.text,
message.pastes,
message.images.map(({ media_type, data }) => ({ media_type, data })), message.images.map(({ media_type, data }) => ({ media_type, data })),
) )
apiError.value = null apiError.value = null
@@ -559,7 +665,11 @@ async function downloadAttachment(id: string, name: string): Promise<void> {
const anchor = document.createElement('a') const anchor = document.createElement('a')
anchor.href = url anchor.href = url
anchor.download = name anchor.download = name
// A click on a detached anchor is a no-op in some browsers; the
// element joins the document for the length of the click.
document.body.append(anchor)
anchor.click() anchor.click()
anchor.remove()
} catch (err) { } catch (err) {
noteApiError(err) noteApiError(err)
} }
@@ -581,22 +691,43 @@ function saveToken(): void {
void refreshSessions() void refreshSessions()
void refreshIdentity() void refreshIdentity()
void refreshAccounts() void refreshAccounts()
void refreshSandbox()
} }
// --- the one live subscription --------------------------------------- // --- the one live subscription ---------------------------------------
let stream: { close: () => void } | null = null let stream: { close: () => void } | null = null
/** The revision the read-only thread on screen was loaded at; a poll
* that sees a newer one reloads it, since no stream will. */
let threadRevision: number | null = null
/** A load is in flight: a poll landing mid-load must not start a second
* one and append the same page twice. */
let threadLoading = false
/** Whether the key on screen answers a snapshot. The key's prefix says
* so before the fetch lands; the page's own `read_only` has the last
* word. */
const threadReadOnly = ref(false)
function resubscribe(): void { function resubscribe(): void {
stream?.close() stream?.close()
stream = null stream = null
transcript.reset() transcript.reset()
olderAvailable.value = true olderAvailable.value = true
attemptedAttachments.clear() attemptedAttachments = new WeakSet<object>()
notices.value = [] notices.value = []
streamStatus.value = 'connecting' streamStatus.value = 'connecting'
threadRevision = null
threadReadOnly.value = activeKey.value !== '' && !isResidentKey(activeKey.value)
// Deleting the last session clears the key, and an empty key is not a // Deleting the last session clears the key, and an empty key is not a
// stream: subscribing to one would retry a 404 forever. // stream: subscribing to one would retry a 404 forever.
if (activeKey.value === '') return if (activeKey.value === '') return
// A key outside the resident context has no turn record: its handler
// never streams, and the events route answers 400. What the daemon
// does hold is the session stash, which the history route serves as a
// read-only snapshot. The panel shows it with the composer closed.
if (!isResidentKey(activeKey.value)) {
void loadThread()
return
}
stream = claw.subscribeEvents(activeKey.value, { stream = claw.subscribeEvents(activeKey.value, {
onEvent: (event, seq) => transcript.applyEvent(event, seq), onEvent: (event, seq) => transcript.applyEvent(event, seq),
// The record lost what this mirror holds (a wiped or reset // The record lost what this mirror holds (a wiped or reset
@@ -604,8 +735,8 @@ function resubscribe(): void {
onReset: () => { onReset: () => {
transcript.reset() transcript.reset()
olderAvailable.value = true olderAvailable.value = true
attemptedAttachments.clear() attemptedAttachments = new WeakSet<object>()
scannedItems = 0 requestAttachmentImages()
}, },
onStatus: (status) => { onStatus: (status) => {
streamStatus.value = status streamStatus.value = status
@@ -614,8 +745,8 @@ function resubscribe(): void {
// is. Only the attachment set is cleared — a fetch that failed // is. Only the attachment set is cleared — a fetch that failed
// during the outage should retry against the recovered stream. // during the outage should retry against the recovered stream.
if (status === 'reconnecting') { if (status === 'reconnecting') {
attemptedAttachments.clear() attemptedAttachments = new WeakSet<object>()
scannedItems = 0 requestAttachmentImages()
} }
if (status === 'open') void refreshSessions() if (status === 'open') void refreshSessions()
}, },
@@ -623,6 +754,35 @@ function resubscribe(): void {
}) })
} }
/** Loads the newest page of a read-only thread: a snapshot of the
* engine's own history, rendered by the same mirror the stream feeds.
* Pagination is the walk back, unchanged — a page lands, the scroller
* asks for the next one. */
async function loadThread(): Promise<void> {
const key = activeKey.value
threadLoading = true
streamStatus.value = 'open'
// A reload (a finished dispatch moved the revision) rebuilds from the
// newest page: the mirror holds the previous snapshot, and stacking
// the new one under it would duplicate every turn.
transcript.reset()
olderAvailable.value = true
attemptedAttachments = new WeakSet<object>()
try {
const page = await claw.history(key)
if (key !== activeKey.value) return
for (const { seq, event } of page.events) transcript.applyEvent(event, seq)
olderAvailable.value = page.more
threadReadOnly.value = page.readOnly
threadRevision = sessions.value.find((session) => session.key === key)?.revision ?? null
apiError.value = null
} catch (err) {
noteApiError(err)
} finally {
threadLoading = false
}
}
/** Fetches one page of turns older than the mirror's first and stacks /** Fetches one page of turns older than the mirror's first and stacks
* it above. Whole turns only, so the page never duplicates or skips: * it above. Whole turns only, so the page never duplicates or skips:
* the daemon ends it exactly where the mirror begins. */ * the daemon ends it exactly where the mirror begins. */
@@ -657,6 +817,7 @@ onMounted(() => {
void refreshIdentity() void refreshIdentity()
void refreshProviders() void refreshProviders()
void refreshAccounts() void refreshAccounts()
void refreshSandbox()
void refreshSessions() void refreshSessions()
healthTimer = setInterval(checkHealth, 30000) healthTimer = setInterval(checkHealth, 30000)
sessionsTimer = setInterval(() => void refreshSessions(), 20000) sessionsTimer = setInterval(() => void refreshSessions(), 20000)
@@ -725,12 +886,16 @@ onUnmounted(() => {
@refresh="refreshSessions" @refresh="refreshSessions"
@create="createSession" @create="createSession"
@delete="askDeleteSession" @delete="askDeleteSession"
@pause="pauseSession"
@resume="resumeSession"
@abort="abortSession"
/> />
<ChatPanel <ChatPanel
:items="transcriptItems" :items="transcriptItems"
:live="liveTurn" :live="liveTurn"
:active-key="activeKey" :active-key="activeKey"
:can-send="isInteractive(activeKey)" :can-send="isInteractive(activeKey)"
:read-only="threadReadOnly"
:busy="busy" :busy="busy"
:session="activeSession" :session="activeSession"
:active-backend="providersState?.active ?? null" :active-backend="providersState?.active ?? null"
@@ -789,6 +954,12 @@ onUnmounted(() => {
@add="addProvider" @add="addProvider"
@remove="removeProvider" @remove="removeProvider"
/> />
<SettingsSandboxPage
v-show="route.section === 'sandbox'"
:state="sandboxState"
:saving="savingSandbox"
@save="saveSandbox"
/>
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" /> <SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
</template> </template>
</main> </main>
+135 -38
View File
@@ -10,12 +10,14 @@
import { import {
PASTE_INLINE_LINES, PASTE_INLINE_LINES,
chipLabel, chipLabel,
embedPastes, byteToIndex,
chipLinesLabel,
lineCount, lineCount,
normalizePaste, normalizePaste,
pasteParts, pasteParts,
} from '~/composables/useTranscript' } from '~/composables/useTranscript'
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw' import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
import type { PasteSpan } from '~/composables/useClaw'
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript' import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
const props = defineProps<{ const props = defineProps<{
@@ -24,6 +26,8 @@ const props = defineProps<{
activeKey: string activeKey: string
/** Only `interactive:*` keys accept messages (the claw 400s the rest). */ /** Only `interactive:*` keys accept messages (the claw 400s the rest). */
canSend: boolean canSend: boolean
/** The daemon answers this key with a snapshot, not a stream. */
readOnly: boolean
busy: boolean busy: boolean
session: ClawSession | null session: ClawSession | null
activeBackend: { provider: string; model: string } | null activeBackend: { provider: string; model: string } | null
@@ -41,10 +45,34 @@ const props = defineProps<{
const agentName = computed(() => props.identity?.name?.trim() || 'rhema') const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
/** Why the composer is closed. A resident key that is not `interactive:`
* runs on its own trigger; anything else is a snapshot of a stash the
* engine checkpointed, whose answer went out through its dispatch. */
const readOnlyNote = computed(() =>
!props.readOnly
? 'Only interactive: keys take messages. This key runs on its own trigger and the transcript is read-only.'
: 'Read-only snapshot of the turns this key ran. The dispatch takes its input and posts its answer outside the chat.',
)
/** Whose words a user row holds. A chat key's are the human's, on the
* web surface or on the phone; every other key's are the prompt its
* dispatch was started with. */
const userLabel = computed(() =>
/^(interactive|phone):/.test(props.activeKey) ? 'you' : 'dispatch',
)
/** Whether the key has a stream at all. A snapshot answers a page once
* and follows nothing, so the header says so instead of claiming to be
* live. */
const streaming = computed(() => !props.readOnly)
/** One send as the panel hands it up: the text (pastes embedded) and /** One send as the panel hands it up: the text (pastes embedded) and
* the staged images, previews included for the optimistic row. */ * the staged images, previews included for the optimistic row. */
interface SendPayload { interface SendPayload {
text: string 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[] images: StagedImage[]
} }
@@ -136,20 +164,12 @@ watch(
}, },
) )
// Thinking grows inside the trailing entry without changing the // A consent or attachment card opening inside the trailing turn
// entries length, so its total length joins the watch to keep the // changes the rendered height, so the reply length and the entries
// stream pinned at the bottom. // length both join the watch that keeps the stream pinned at the
function liveThinkingLength(): number { // bottom.
return (
props.live?.entries.reduce(
(count, entry) => (entry.kind === 'thinking' ? count + entry.text.length : count),
0,
) ?? 0
)
}
watch( 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 () => { async () => {
if (!pinned.value) return if (!pinned.value) return
await nextTick() await nextTick()
@@ -165,7 +185,7 @@ function submit(): void {
// answers 202 at once) — a running turn never blocks the composer, // answers 202 at once) — a running turn never blocks the composer,
// because a send into one steers it. // because a send into one steers it.
if (!text || !props.canSend || props.busy) return 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++ stageGeneration++
draft.value = '' draft.value = ''
pastes.value = [] pastes.value = []
@@ -367,17 +387,36 @@ function storedImageName(image: SentImage): string {
type MessageSegment = PastePart | { kind: 'chip'; label: string } type MessageSegment = PastePart | { kind: 'chip'; label: string }
/** The message's render pieces: literal text and resolved chips, the /** The message's render pieces: literal text and resolved chips, the
* chips' one-based ids counted across the message. */ * chips' one-based ids counted across the message. The chips come
function messageSegments(text: string): MessageSegment[] { * 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)) {
if (part.kind === 'text') {
if (part.text !== '') segments.push(part)
} else {
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) })
}
}
return segments
}
const indexOf = byteToIndex(text)
const segments: MessageSegment[] = [] const segments: MessageSegment[] = []
let chip = 0 let chip = 0
for (const part of pasteParts(text)) { let cut = 0
if (part.kind === 'text') { for (const span of [...pastes].sort((a, b) => a.start - b.start)) {
if (part.text !== '') segments.push(part) const start = indexOf(span.start)
} else { const end = indexOf(span.end)
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) }) 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 return segments
} }
@@ -412,10 +451,13 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="text"> <div class="text">
<h2>{{ displayName }}</h2> <h2>{{ displayName }}</h2>
</div> </div>
<span class="stream-status" :title="`event stream: ${streamStatus}`"> <span v-if="streaming" class="stream-status" :title="`event stream: ${streamStatus}`">
<StatusDot :tone="streamTone(streamStatus)" /> <StatusDot :tone="streamTone(streamStatus)" />
{{ streamLabel }} {{ streamLabel }}
</span> </span>
<span v-else class="stream-status" title="a snapshot of the stored session; no stream follows this key">
snapshot
</span>
<button class="ghost info" title="session info" @click="infoOpen = true">ⓘ</button> <button class="ghost info" title="session info" @click="infoOpen = true">ⓘ</button>
</header> </header>
@@ -430,7 +472,9 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div ref="scroller" class="stream-area" @scroll.passive="onScroll"> <div ref="scroller" class="stream-area" @scroll.passive="onScroll">
<p v-if="items.length === 0 && !live" class="empty"> <p v-if="items.length === 0 && !live" class="empty">
nothing streamed yet; messages post to the claw and replies arrive here live {{ streaming
? 'nothing streamed yet; messages post to the claw and replies arrive here live'
: 'nothing recorded for this key yet' }}
</p> </p>
<p v-if="loadingOlder" class="older-hint">loading earlier turns</p> <p v-if="loadingOlder" class="older-hint">loading earlier turns</p>
@@ -439,7 +483,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div v-if="item.kind === 'sent'" class="msg"> <div v-if="item.kind === 'sent'" class="msg">
<div class="avatar user" aria-hidden="true">·</div> <div class="avatar user" aria-hidden="true">·</div>
<div class="msg-body"> <div class="msg-body">
<div class="who">you</div> <div class="who">{{ userLabel }}</div>
<div v-if="item.images.length > 0" class="sent-images"> <div v-if="item.images.length > 0" class="sent-images">
<button <button
v-for="(image, index) in item.images" v-for="(image, index) in item.images"
@@ -453,7 +497,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
</button> </button>
</div> </div>
<div class="reply plain"> <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> <span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
<template v-else>{{ segment.text }}</template> <template v-else>{{ segment.text }}</template>
</template> </template>
@@ -474,7 +518,11 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div <div
v-if="item.turn.outcome" v-if="item.turn.outcome"
class="outcome mono" class="outcome mono"
:class="{ failed: item.turn.outcome === 'failed', steered: item.turn.outcome === 'steered' }" :class="{
failed: item.turn.outcome === 'failed',
steered: item.turn.outcome === 'steered',
aborted: item.turn.outcome === 'aborted',
}"
> >
{{ item.turn.outcome }} {{ item.turn.outcome }}
</div> </div>
@@ -498,12 +546,15 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="who">{{ agentName }}</div> <div class="who">{{ agentName }}</div>
<TurnEntries <TurnEntries
:entries="live.entries" :entries="live.entries"
:open-thinking="true"
@consent-answer="(id, answer) => emit('consentAnswer', id, answer)" @consent-answer="(id, answer) => emit('consentAnswer', id, answer)"
@consent-deny="(id) => emit('consentDeny', id)" @consent-deny="(id) => emit('consentDeny', id)"
@download-attachment="(id, name) => emit('downloadAttachment', id, name)" @download-attachment="(id, name) => emit('downloadAttachment', id, name)"
/> />
<AppMarkdown v-if="live.reply" :text="live.reply" streaming class="reply" /> <AppMarkdown v-if="live.reply" :text="live.reply" streaming class="reply" />
<p v-if="!live.reply" class="working" role="status">
<span class="spinner" aria-hidden="true" />
{{ agentName }} is working…
</p>
</div> </div>
</div> </div>
</div> </div>
@@ -540,8 +591,9 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
{{ imageError }} {{ imageError }}
<button class="chip-x" title="dismiss" @click="imageError = null">×</button> <button class="chip-x" title="dismiss" @click="imageError = null">×</button>
</p> </p>
<div class="input-row"> <p v-if="!canSend" class="read-only">{{ readOnlyNote }}</p>
<button class="ghost attach" title="attach images" :disabled="!canSend" @click="pickImages"> <div v-else class="input-row">
<button class="ghost attach" title="attach images" @click="pickImages">
+ +
</button> </button>
<textarea <textarea
@@ -549,20 +601,15 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
v-model="draft" v-model="draft"
rows="1" rows="1"
:placeholder=" :placeholder="
canSend live ? `Message ${agentName}… sending steers the running turn` : `Message ${agentName}…`
? live
? `Message ${agentName}… sending steers the running turn`
: `Message ${agentName}…`
: 'only interactive:* sessions accept messages'
" "
:disabled="!canSend"
@keydown="onPromptKeydown" @keydown="onPromptKeydown"
@paste="onPaste" @paste="onPaste"
@input="resizePrompt" @input="resizePrompt"
/> />
<button <button
class="primary send" class="primary send"
:disabled="!canSend || busy || draft.trim() === ''" :disabled="busy || draft.trim() === ''"
:title="live ? 'send — interrupts the running turn' : 'send'" :title="live ? 'send — interrupts the running turn' : 'send'"
@click="submit" @click="submit"
> >
@@ -740,6 +787,49 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
color: var(--accent-text); color: var(--accent-text);
} }
/* An aborted turn: stopped from the controls, and nothing replaced
it. Not a failure either — the same warn tone the held badge
carries, which is what an operator's stop is. */
.outcome.aborted {
color: var(--warn);
}
/* While the turn runs but no reply text has landed yet. Tool rows and
the thinking trace never render on this surface, so this line is the
turn's only pulse between its first event and its first delta — the
streaming cursor takes over once text arrives, and the line goes.
Reduced motion gets the static ring. */
.working {
display: flex;
align-items: center;
gap: 8px;
margin: 4px 0 0;
color: var(--text3);
font-size: 12.5px;
}
.spinner {
flex: none;
width: 12px;
height: 12px;
border: 2px solid var(--border-strong);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
/* A consent card: the agent asking its human something — distinct /* A consent card: the agent asking its human something — distinct
from a tool row, toned by its resolution. */ from a tool row, toned by its resolution. */
.consent-card { .consent-card {
@@ -922,6 +1012,13 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
gap: 8px; gap: 8px;
} }
.read-only {
margin: 0;
padding: 2px 0;
color: var(--text3);
font-size: 12.5px;
}
.attach { .attach {
width: 38px; width: 38px;
padding: 0; padding: 0;
+188 -35
View File
@@ -7,6 +7,19 @@
// new key lands in the inventory. The delete button asks nothing itself // new key lands in the inventory. The delete button asks nothing itself
// — the confirmation, which names the transcript that goes with the // — the confirmation, which names the transcript that goes with the
// session, is the shell's. // session, is the shell's.
//
// The non-interactive keys fold under *others*: folded (the default),
// the group shows only how many of them hold a lease, plus the
// more/less toggle; unfolded it lists every row, the whole inventory.
// Every row opens: a resident key streams, and any other key (a forge
// thread, a coding job, a phone topic) opens the read-only snapshot its
// history route serves. The controls beside it act on its dispatch from
// either view.
//
// The controls sit beside the delete button, on hover, one word each:
// hold/run pauses and resumes the key's dispatch, stop aborts — cuts a
// live turn, or drops the key's queued work when none runs. Nothing
// here is destructive beyond the delete, which keeps its own dialog.
import { SESSION_NAME_PATTERN, isResidentKey } from '~/composables/useClaw' import { SESSION_NAME_PATTERN, isResidentKey } from '~/composables/useClaw'
import type { ClawSession } from '~/composables/useClaw' import type { ClawSession } from '~/composables/useClaw'
@@ -23,42 +36,80 @@ const emit = defineEmits<{
refresh: [] refresh: []
create: [name: string] create: [name: string]
delete: [key: string] delete: [key: string]
pause: [key: string]
resume: [key: string]
abort: [key: string]
}>() }>()
interface Group { interface Group {
label: string label: string
rows: { key: string; name: string; session: ClawSession }[] rows: {
key: string
name: string
session: ClawSession
/** Whether abort has anything to act on: a live turn, or queued
* work to drop. */
abortable: boolean
}[]
/** How many rows hold a lease; the others' header shows the count. */
working: number
/** Whether the rows fold away until the toggle says otherwise. */
collapsible: boolean
} }
const groups = computed<Group[]>(() => { const groups = computed<Group[]>(() => {
const byKey = (a: ClawSession, b: ClawSession) => a.key.localeCompare(b.key) const byKey = (a: ClawSession, b: ClawSession) => a.key.localeCompare(b.key)
// Only the resident prefixes are chat sessions: `interactive:` is the // The resident prefixes are the chat sessions: `interactive:` is the
// live chat surface, `task:` a scheduled task's own turn, `calendar:` a // live chat surface, `task:` a scheduled task's own turn, `phone:` the
// reminder's. The rest of the inventory has no transcript to open — // phone client's, `calendar:` a reminder's. The rest of the inventory —
// `phone:<device>:<topic>` is status reporting, `job:<instance>#<id>` // `job:<instance>#<id>`, a forge thread — holds no turn record: its
// is the coding jobs' bookkeeping, a forge key is a thread the handler // handler never streams. Its history route serves the session stash
// reports on — and the daemon's message, event and history routes // instead, so the row still opens, read-only.
// refuse those prefixes, so a row for one is a dead end. The inventory const interactive = props.sessions
// hides them rather than the API narrowing.
const conversable = props.sessions.filter((session) => isResidentKey(session.key))
const interactive = conversable
.filter((session) => session.key.startsWith('interactive:')) .filter((session) => session.key.startsWith('interactive:'))
.sort(byKey) .sort(byKey)
const others = conversable const others = props.sessions
.filter((session) => !session.key.startsWith('interactive:')) .filter((session) => !session.key.startsWith('interactive:'))
.sort(byKey) .sort(byKey)
const row = (session: ClawSession) => ({ const row = (session: ClawSession) => ({
key: session.key, key: session.key,
name: session.key.replace(/^interactive:/, ''), name: session.key.replace(/^interactive:/, ''),
session, session,
abortable: session.state === 'leased' || session.inbox_depth > 0,
}) })
const working = (sessions: ClawSession[]) =>
sessions.filter((session) => session.state === 'leased').length
const groups: Group[] = [] const groups: Group[] = []
if (interactive.length > 0) if (interactive.length > 0)
groups.push({ label: 'interactive', rows: interactive.map(row) }) groups.push({
if (others.length > 0) groups.push({ label: 'other keys', rows: others.map(row) }) label: 'interactive',
rows: interactive.map(row),
working: working(interactive),
collapsible: false,
})
if (others.length > 0)
groups.push({
label: 'others',
rows: others.map(row),
working: working(others),
collapsible: true,
})
return groups return groups
}) })
/** Whether the others group is folded out; it starts folded, and opens
* when the chat opens a row that lives in it — otherwise the selection
* would be invisible. */
const othersOpen = ref(false)
watch(
() => props.activeKey,
(key) => {
if (key !== '' && !isResidentKey(key)) othersOpen.value = true
},
{ immediate: true },
)
const shownCount = computed(() => const shownCount = computed(() =>
groups.value.reduce((total, group) => total + group.rows.length, 0), groups.value.reduce((total, group) => total + group.rows.length, 0),
) )
@@ -159,30 +210,76 @@ watch(
</p> </p>
<div v-for="group in groups" :key="group.label" class="group"> <div v-for="group in groups" :key="group.label" class="group">
<span class="label">{{ group.label }}</span> <div class="group-head">
<div <span class="label">{{ group.label }}</span>
v-for="row in group.rows" <span v-if="group.collapsible" class="working" :class="{ live: group.working > 0 }">
:key="row.key" {{ group.working }} working
class="row" </span>
:class="{ active: row.key === activeKey }"
:title="row.key"
>
<button class="entry" @click="$emit('select', row.key)">
<StatusDot :tone="stateTone(row.session.state)" />
<span class="name">{{ row.name }}</span>
<span v-if="row.session.inbox_depth > 0" class="depth" title="inbox depth">
{{ row.session.inbox_depth }}
</span>
</button>
<button <button
class="ghost remove" v-if="group.collapsible"
aria-label="delete session" class="ghost toggle"
:title="`delete ${row.key}`" :title="othersOpen ? 'fold the other keys away' : 'show every other key'"
@click.stop="$emit('delete', row.key)" @click="othersOpen = !othersOpen"
> >
× {{ othersOpen ? 'less' : 'more' }}
</button> </button>
</div> </div>
<template v-if="!group.collapsible || othersOpen">
<div
v-for="row in group.rows"
:key="row.key"
class="row"
:class="{ active: row.key === activeKey }"
:title="row.key"
>
<button class="entry" @click="$emit('select', row.key)">
<StatusDot :tone="stateTone(row.session.state)" />
<span class="name">{{ row.name }}</span>
<span
v-if="row.session.paused"
class="held"
title="dispatch held: nothing runs until resume"
>
held
</span>
<span v-if="row.session.inbox_depth > 0" class="depth" title="inbox depth">
{{ row.session.inbox_depth }}
</span>
</button>
<button
v-if="row.session.paused"
class="ghost act"
:title="`resume ${row.key}`"
@click.stop="$emit('resume', row.key)"
>
run
</button>
<button
v-else
class="ghost act"
:title="`pause ${row.key}`"
@click.stop="$emit('pause', row.key)"
>
hold
</button>
<button
class="ghost act stop"
:disabled="!row.abortable"
:title="`abort ${row.key}`"
@click.stop="$emit('abort', row.key)"
>
stop
</button>
<button
class="ghost remove"
aria-label="delete session"
:title="`delete ${row.key}`"
@click.stop="$emit('delete', row.key)"
>
×
</button>
</div>
</template>
</div> </div>
</aside> </aside>
</template> </template>
@@ -287,10 +384,32 @@ watch(
margin-bottom: 14px; margin-bottom: 14px;
} }
.group .label { .group-head {
display: flex;
align-items: center;
gap: 8px;
padding: 0 8px 4px; padding: 0 8px 4px;
} }
.group-head .working {
flex: 1;
min-width: 0;
text-align: right;
font-family: var(--mono);
font-size: 11px;
color: var(--text3);
}
.group-head .working.live {
color: var(--ok);
}
.group-head .toggle {
flex: none;
padding: 0 6px;
font-size: 11px;
}
/* The row owns the hover and active surface: the select button fills it /* The row owns the hover and active surface: the select button fills it
and the delete button sits beside it, so neither has to nest in the and the delete button sits beside it, so neither has to nest in the
other. */ other. */
@@ -329,6 +448,27 @@ watch(
font-weight: inherit; font-weight: inherit;
} }
.row .act {
flex: none;
padding: 0 4px;
font-size: 11px;
font-family: var(--mono);
opacity: 0;
}
.row .act.stop {
color: var(--error);
}
.row .act:disabled {
color: var(--text3);
cursor: default;
}
.entry:disabled {
cursor: default;
}
.row .remove { .row .remove {
flex: none; flex: none;
padding: 0 5px; padding: 0 5px;
@@ -336,12 +476,25 @@ watch(
opacity: 0; opacity: 0;
} }
.row:hover .act,
.row:hover .remove, .row:hover .remove,
.row:focus-within .act,
.row:focus-within .remove, .row:focus-within .remove,
.row.active .act,
.row.active .remove { .row.active .remove {
opacity: 1; opacity: 1;
} }
.held {
flex: none;
font-size: 10px;
font-family: var(--mono);
color: var(--warn);
border: 1px solid var(--border-strong);
border-radius: 999px;
padding: 0 5px;
}
.name { .name {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@@ -1,7 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
// The agent handing a file over: a head row naming it, the image (when // The agent handing a file over: a head row naming it, the image (when
// there is one) under it, capped so a screenshot cannot take the // there is one) under it, capped so a screenshot cannot take the
// stream; code and file download on click. // stream. Every card downloads, images included: a picture the browser
// cannot paint, an SVG, or bytes that failed to fetch must still come
// out of the store.
import type { AttachmentCard } from '~/composables/useTranscript' import type { AttachmentCard } from '~/composables/useTranscript'
defineProps<{ attachment: AttachmentCard }>() defineProps<{ attachment: AttachmentCard }>()
@@ -35,7 +37,6 @@ function formatBytes(size: number): string {
<span class="attachment-name mono">{{ attachment.name }}</span> <span class="attachment-name mono">{{ attachment.name }}</span>
<span class="attachment-size mono">{{ formatBytes(attachment.size) }}</span> <span class="attachment-size mono">{{ formatBytes(attachment.size) }}</span>
<button <button
v-if="attachment.media !== 'image'"
class="ghost" class="ghost"
:title="`download ${attachment.name}`" :title="`download ${attachment.name}`"
@click="emit('download', attachment.id, attachment.name)" @click="emit('download', attachment.id, attachment.name)"
+16 -39
View File
@@ -1,17 +1,22 @@
<script setup lang="ts"> <script setup lang="ts">
// A turn's stream-ordered middle: tool rows, pieces of the thinking // The turn's middle, as the web surface shows it: the agent's asks
// trace, the agent's asks, its handovers — each at the position the // (consent cards) and its handovers (attachment cards), each at the
// stream delivered it, so an ask sits at the tool call that raised it // position the stream delivered it. Tool calls and the thinking trace
// and thinking sits between the calls it precedes. // 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 { TurnEntry } from '~/composables/useTranscript'
import type { ConsentAnswer } from '~/composables/useClaw' import type { ConsentAnswer } from '~/composables/useClaw'
defineProps<{ const props = defineProps<{
entries: TurnEntry[] 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<{ const emit = defineEmits<{
consentAnswer: [id: string, answer: ConsentAnswer] consentAnswer: [id: string, answer: ConsentAnswer]
consentDeny: [id: string] consentDeny: [id: string]
@@ -20,21 +25,16 @@ const emit = defineEmits<{
</script> </script>
<template> <template>
<div v-if="entries.length > 0" class="entries"> <div v-if="cards.length > 0" class="entries">
<template v-for="(entry, index) in entries" :key="index"> <template v-for="(entry, index) in cards" :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>
<TurnConsentCard <TurnConsentCard
v-else-if="entry.kind === 'consent'" v-if="entry.kind === 'consent'"
:consent="entry.consent" :consent="entry.consent"
@answer="(id, answer) => emit('consentAnswer', id, answer)" @answer="(id, answer) => emit('consentAnswer', id, answer)"
@deny="(id) => emit('consentDeny', id)" @deny="(id) => emit('consentDeny', id)"
/> />
<TurnAttachmentCard <TurnAttachmentCard
v-else v-else-if="entry.kind === 'attachment'"
:attachment="entry.attachment" :attachment="entry.attachment"
@download="(id, name) => emit('downloadAttachment', id, name)" @download="(id, name) => emit('downloadAttachment', id, name)"
/> />
@@ -49,27 +49,4 @@ const emit = defineEmits<{
gap: 4px; gap: 4px;
margin-bottom: 10px; 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> </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>
@@ -14,6 +14,9 @@ const routes = [
{ method: 'GET', path: '/v1/sessions', note: 'the dispatch-key inventory' }, { method: 'GET', path: '/v1/sessions', note: 'the dispatch-key inventory' },
{ method: 'POST', path: '/v1/sessions', note: 'create an interactive session from a name' }, { method: 'POST', path: '/v1/sessions', note: 'create an interactive session from a name' },
{ method: 'DELETE', path: '/v1/sessions/{key}', note: 'delete a session and its turn history' }, { method: 'DELETE', path: '/v1/sessions/{key}', note: 'delete a session and its turn history' },
{ method: 'POST', path: '/v1/sessions/{key}/pause', note: "hold a key's dispatch" },
{ method: 'POST', path: '/v1/sessions/{key}/resume', note: 'lift the hold' },
{ method: 'POST', path: '/v1/sessions/{key}/abort', note: 'cut the live turn, or drop the queue' },
{ method: 'POST', path: '/v1/sessions/{key}/messages', note: 'message ingest, 202 + stream' }, { method: 'POST', path: '/v1/sessions/{key}/messages', note: 'message ingest, 202 + stream' },
{ method: 'GET', path: '/v1/sessions/{key}/events', note: 'the turn-event stream (SSE)' }, { method: 'GET', path: '/v1/sessions/{key}/events', note: 'the turn-event stream (SSE)' },
{ method: 'POST', path: '/v1/consents/{id}', note: 'answer a consent (a secret or a grant)' }, { method: 'POST', path: '/v1/consents/{id}', note: 'answer a consent (a secret or a grant)' },
@@ -24,6 +24,7 @@ const emit = defineEmits<{
// The draft: '' means "clear this field", matching the wire. // The draft: '' means "clear this field", matching the wire.
const draft = ref<IdentityTexts>({ const draft = ref<IdentityTexts>({
name: '', name: '',
email: '',
mark: '', mark: '',
initials: '', initials: '',
tagline: '', tagline: '',
@@ -35,6 +36,7 @@ const dirty = computed(() => {
if (!identity) return false if (!identity) return false
return ( return (
draft.value.name !== (identity.name ?? '') || draft.value.name !== (identity.name ?? '') ||
draft.value.email !== (identity.email ?? '') ||
draft.value.mark !== (identity.mark ?? '') || draft.value.mark !== (identity.mark ?? '') ||
draft.value.initials !== (identity.initials ?? '') || draft.value.initials !== (identity.initials ?? '') ||
draft.value.tagline !== (identity.tagline ?? '') || draft.value.tagline !== (identity.tagline ?? '') ||
@@ -47,6 +49,7 @@ function discard(): void {
if (!identity) return if (!identity) return
draft.value = { draft.value = {
name: identity.name ?? '', name: identity.name ?? '',
email: identity.email ?? '',
mark: identity.mark ?? '', mark: identity.mark ?? '',
initials: identity.initials ?? '', initials: identity.initials ?? '',
tagline: identity.tagline ?? '', tagline: identity.tagline ?? '',
@@ -66,6 +69,7 @@ watch(
initialized.value = true initialized.value = true
draft.value = { draft.value = {
name: identity.name ?? '', name: identity.name ?? '',
email: identity.email ?? '',
mark: identity.mark ?? '', mark: identity.mark ?? '',
initials: identity.initials ?? '', initials: identity.initials ?? '',
tagline: identity.tagline ?? '', tagline: identity.tagline ?? '',
@@ -97,6 +101,7 @@ function onImageChosen(kind: AgentImageKind, event: Event): void {
const CAPS: Record<keyof IdentityTexts, number> = { const CAPS: Record<keyof IdentityTexts, number> = {
name: 64, name: 64,
email: 120,
mark: 8, mark: 8,
initials: 4, initials: 4,
tagline: 120, tagline: 120,
@@ -142,7 +147,7 @@ const CAPS: Record<keyof IdentityTexts, number> = {
<SettingCard v-if="identity" title="Agent identity"> <SettingCard v-if="identity" title="Agent identity">
<SettingRow <SettingRow
title="Display name" title="Display name"
description="Shown as the author of messages, in the window title, and in notifications." description="Shown as the author of messages, in the window title, in notifications, and as the author name on commits in workspaces."
> >
<input <input
v-model="draft.name" v-model="draft.name"
@@ -153,6 +158,19 @@ const CAPS: Record<keyof IdentityTexts, number> = {
:disabled="saving" :disabled="saving"
/> />
</SettingRow> </SettingRow>
<SettingRow
title="Email"
description="The author address on commits the agent makes in its workspaces."
>
<input
v-model="draft.email"
type="email"
:maxlength="CAPS.email"
placeholder="claw@example.net"
autocomplete="off"
:disabled="saving"
/>
</SettingRow>
<SettingRow <SettingRow
title="Mark" title="Mark"
description="The glyph or emoji in the rail and the empty states. Defaults to ῥ." description="The glyph or emoji in the rail and the empty states. Defaults to ῥ."
@@ -0,0 +1,375 @@
<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 host = ref('')
const workspace = ref('')
const privateKey = ref('')
const clearPrivateKey = ref(false)
const dirty = computed(() => {
const state = props.state
if (!state) return false
if (kind.value !== state.kind) return true
if (kind.value === 'http') {
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
}
if (kind.value === 'ssh') {
if (host.value.trim() !== (state.host ?? '')) return true
if (workspace.value.trim() !== (state.ssh_workspace ?? '')) return true
return privateKey.value.trim() !== '' || clearPrivateKey.value
}
return false
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const hostValid = computed(
() => host.value.trim() !== '' && !host.value.trim().includes(' '),
)
const ready = computed(() => {
if (kind.value === 'http') return urlValid.value
if (kind.value === 'ssh') return hostValid.value
return true
})
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.',
)
const hostHint = computed(() =>
host.value.trim() && !hostValid.value
? 'One destination, no spaces: an alias or user@host your ssh config resolves.'
: 'An alias or user@host your ssh config resolves.',
)
function sync(): void {
const state = props.state
if (!state) return
kind.value = state.kind
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? ''
privateKey.value = ''
clearPrivateKey.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
}
}
if (kind.value === 'ssh') {
choice.host = host.value.trim()
choice.workspace = workspace.value.trim()
if (privateKey.value.trim() !== '') {
choice.private_key = privateKey.value
} else if (clearPrivateKey.value) {
choice.clear_private_key = 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 ''
if (kind.value === 'local') return state.local_workspace
if (kind.value === 'http') return state.remote_workspace
return state.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>
<label class="option" :class="{ selected: kind === 'ssh' }">
<input v-model="kind" type="radio" value="ssh" :disabled="saving" />
<span class="option-text">
<span class="option-title">
SSH host
<span v-if="state.kind === 'ssh'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a box the claw reaches with ssh, nothing installed on the far end.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'ssh'" title="SSH host">
<SettingRow title="Destination" :description="hostHint">
<input
v-model="host"
type="text"
class="mono"
placeholder="me@box.example"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Workspace base"
description="The remote directory the claw's workspaces live under. Defaults to /root."
>
<input
v-model="workspace"
type="text"
class="mono"
placeholder="/root"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Private key"
:description="state.private_key_set
? 'A key is stored. Leave this blank to keep it, or paste a replacement.'
: 'The key text itself (OpenSSH or PEM), not a path: the claw stores it, it stages no file. Leave blank to authenticate through an agent or the default key files.'"
>
<textarea
v-model="privateKey"
class="mono key-input"
rows="3"
:placeholder="state.private_key_set ? 'stored' : '-----BEGIN OPENSSH PRIVATE KEY-----'"
autocomplete="off"
spellcheck="false"
:disabled="saving || clearPrivateKey"
/>
</SettingRow>
<SettingRow
v-if="state.private_key_set"
title="Stored key"
:description="clearPrivateKey
? 'The stored key is removed when you save.'
: 'The key stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearPrivateKey = !clearPrivateKey">
{{ clearPrivateKey ? 'Keep key' : 'Forget key' }}
</button>
</SettingRow>
</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 !== 'local'" 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;
}
.key-input {
width: 100%;
min-width: 0;
resize: vertical;
font-size: 12px;
word-break: break-all;
}
</style>
+214 -22
View File
@@ -56,9 +56,20 @@ export interface UserImage {
media_type: string 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). */ /** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
export type TurnEvent = 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: 'thinking_delta'; text: string }
| { type: 'text_delta'; text: string } | { type: 'text_delta'; text: string }
| { type: 'tool_start'; name: string } | { type: 'tool_start'; name: string }
@@ -84,6 +95,17 @@ export interface ClawSession {
revision: number revision: number
inbox_depth: number inbox_depth: number
last_outcome: string | null last_outcome: string | null
/** Whether the pause gate holds the key: queued work waits, nothing
* dispatches, until resume lifts the hold. */
paused: boolean
}
/** The `POST /v1/sessions/{key}/abort` answer: `cut` when a live turn
* was signalled, `dropped` the queued items the route drained. */
export interface AbortResult {
key: string
cut: boolean
dropped: number
} }
/** One watch (config.rs `Watch`, as the watches routes accept and return it). */ /** One watch (config.rs `Watch`, as the watches routes accept and return it). */
@@ -181,6 +203,7 @@ export interface ProvidersState {
* unset text fields read as null, the images report presence. */ * unset text fields read as null, the images report presence. */
export interface AgentIdentity { export interface AgentIdentity {
name: string | null name: string | null
email: string | null
mark: string | null mark: string | null
initials: string | null initials: string | null
tagline: string | null tagline: string | null
@@ -193,6 +216,7 @@ export interface AgentIdentity {
* string clears the field. */ * string clears the field. */
export interface IdentityTexts { export interface IdentityTexts {
name: string name: string
email: string
mark: string mark: string
initials: string initials: string
tagline: string tagline: string
@@ -220,6 +244,51 @@ export interface ActiveBackend {
active: { provider: string; model: string } active: { provider: string; model: string }
} }
/** Where the agent's `bash` runs: this host, a daemon speaking the
* sandbox protocol over HTTP, or an ssh login on a far box. */
export type SandboxKind = 'local' | 'http' | 'ssh'
/** 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
/** Whether an ssh private key is stored; the key itself never
* rides the wire. */
private_key_set: boolean
/** The ssh destination, an alias or `user@host` the local ssh
* config resolves. */
host: string | null
/** The ssh workspace base the workspaces sit under, `null` for the
* default. */
ssh_workspace: string | null
/** 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
host?: string
/** The ssh private key text (no file): the store-held credential.
* Write-only, like the token. */
private_key?: string
clear_private_key?: boolean
/** The ssh workspace base; the per-workspace directories land under
* it. An omitted value keeps the current one. */
workspace?: string
}
/** A failed API call: the status plus the claw's `error` string when it sent one. */ /** A failed API call: the status plus the claw's `error` string when it sent one. */
export class ClawError extends Error { export class ClawError extends Error {
/** HTTP status; 0 when the claw was unreachable at all. */ /** HTTP status; 0 when the claw was unreachable at all. */
@@ -240,7 +309,9 @@ const INTERACTIVE_PREFIX = 'interactive:'
* connection and reconnects: the claw sends a keep-alive comment every * connection and reconnects: the claw sends a keep-alive comment every
* fifteen seconds (hub.rs), so three missed ones means the path is * 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 * 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 const STREAM_SILENCE_TIMEOUT_MS = 45000
/** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */ /** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */
@@ -248,12 +319,13 @@ export function isInteractive(key: string): boolean {
return key.startsWith(INTERACTIVE_PREFIX) return key.startsWith(INTERACTIVE_PREFIX)
} }
/** The prefixes the chat surface answers for: the daemon's /** The prefixes the daemon's resident context owns: its
* `is_resident_key` (`crates/rhema-claw/src/interactive.rs`). Every other * `is_resident_key` (`crates/rhema-claw/src/interactive.rs`). A resident
* key in the inventory — `phone:` status reporting, `job:<instance>#<id>`, * key has a live turn record the event stream follows. Every other key
* a forge thread — has no transcript: the message, event and history * in the inventory — a forge thread, a coding job — answers no stream
* routes 400 on it. */ * and takes no message: its history route serves the snapshot the
const RESIDENT_PREFIXES = ['interactive:', 'task:', 'calendar:'] * engine checkpointed, and the panel renders it read-only. */
const RESIDENT_PREFIXES = ['interactive:', 'task:', 'phone:', 'calendar:']
/** Whether `key` is one the transcript surface can open. */ /** Whether `key` is one the transcript surface can open. */
export function isResidentKey(key: string): boolean { export function isResidentKey(key: string): boolean {
@@ -343,6 +415,9 @@ export interface StreamHandlers {
export interface HistoryPage { export interface HistoryPage {
events: { seq: number; event: TurnEvent }[] events: { seq: number; event: TurnEvent }[]
more: boolean more: boolean
/** The page is a snapshot of a key the daemon cannot take messages
* for: the chat surface renders it and hides the composer. */
readOnly: boolean
} }
export interface ClawApi { export interface ClawApi {
@@ -356,6 +431,14 @@ export interface ClawApi {
* same name starts empty. 409 while a turn holds the key, 404 when it is * same name starts empty. 409 while a turn holds the key, 404 when it is
* already gone. */ * already gone. */
deleteSession(key: string): Promise<void> deleteSession(key: string): Promise<void>
/** `POST /v1/sessions/{key}/pause` — hold the key's dispatch. 404
* when the inventory has no such key. */
pauseSession(key: string): Promise<void>
/** `POST /v1/sessions/{key}/resume` — lift the hold. */
resumeSession(key: string): Promise<void>
/** `POST /v1/sessions/{key}/abort` — cut the live turn, or drop the
* queued work when none runs. */
abortSession(key: string): Promise<AbortResult>
/** `GET /v1/consents` — the pending consents, oldest first. */ /** `GET /v1/consents` — the pending consents, oldest first. */
listConsents(): Promise<ConsentRequest[]> listConsents(): Promise<ConsentRequest[]>
/** `POST /v1/consents/{id}` — answer one consent; 409 when already /** `POST /v1/consents/{id}` — answer one consent; 409 when already
@@ -368,8 +451,8 @@ export interface ClawApi {
* a plain src will not do). Cached per id: attachments are immutable, * a plain src will not do). Cached per id: attachments are immutable,
* so a replayed event never refetches. */ * so a replayed event never refetches. */
attachmentUrl(id: string): Promise<string> 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. */ /** `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, images?: OutboundImage[]): Promise<void> sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
/** `GET /v1/providers` — the constructible backends and the active pair. */ /** `GET /v1/providers` — the constructible backends and the active pair. */
providers(): Promise<ProvidersState> providers(): Promise<ProvidersState>
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */ /** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
@@ -383,6 +466,11 @@ export interface ClawApi {
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers /** `DELETE /v1/providers/{id}` — remove a backend instance; answers
* the new providers state. The last backend is refused claw-side. */ * the new providers state. The last backend is refused claw-side. */
removeProvider(id: string): Promise<ProvidersState> 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. */ /** `GET /v1/accounts` — the stored accounts, redacted. */
accounts(): Promise<ClawAccount[]> accounts(): Promise<ClawAccount[]>
/** `POST /v1/accounts` — store an account (the secret is write-only), /** `POST /v1/accounts` — store an account (the secret is write-only),
@@ -427,6 +515,7 @@ export interface ClawApi {
* `GET /v1/sessions/{key}/history` — one page of whole turns ending * `GET /v1/sessions/{key}/history` — one page of whole turns ending
* at `before` (absent: the newest). Pages stack: the next call passes * at `before` (absent: the newest). Pages stack: the next call passes
* the seq of the oldest event held, and stops when `more` is false. * the seq of the oldest event held, and stops when `more` is false.
* A non-resident key answers a read-only snapshot here.
*/ */
history(key: string, before?: number | null, limit?: number): Promise<HistoryPage> history(key: string, before?: number | null, limit?: number): Promise<HistoryPage>
} }
@@ -478,6 +567,27 @@ export function useClaw(token: Ref<string | null>): ClawApi {
}) })
} }
async function pauseSession(key: string): Promise<void> {
await send(`/v1/sessions/${encodeURIComponent(key)}/pause`, {
method: 'POST',
headers: authHeaders(token.value),
})
}
async function resumeSession(key: string): Promise<void> {
await send(`/v1/sessions/${encodeURIComponent(key)}/resume`, {
method: 'POST',
headers: authHeaders(token.value),
})
}
async function abortSession(key: string): Promise<AbortResult> {
return (await send(`/v1/sessions/${encodeURIComponent(key)}/abort`, {
method: 'POST',
headers: authHeaders(token.value),
})) as AbortResult
}
async function listConsents(): Promise<ConsentRequest[]> { async function listConsents(): Promise<ConsentRequest[]> {
const body = (await get('/v1/consents', token.value)) as { consents: ConsentRequest[] } const body = (await get('/v1/consents', token.value)) as { consents: ConsentRequest[] }
return body.consents return body.consents
@@ -498,11 +608,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`, { await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) }, headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(images?.length ? { text, images } : { text }), body: JSON.stringify(body),
}) })
} }
@@ -518,7 +636,11 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const body = (await get( const body = (await get(
`/v1/sessions/${encodeURIComponent(key)}/history${query}`, `/v1/sessions/${encodeURIComponent(key)}/history${query}`,
token.value, token.value,
)) as { events?: { seq?: unknown; event?: unknown }[]; more?: unknown } )) as {
events?: { seq?: unknown; event?: unknown }[]
more?: unknown
read_only?: unknown
}
// The wire shape is trusted only as far as it parses: an event the // The wire shape is trusted only as far as it parses: an event the
// parser does not know is dropped, and its seq with it — the page // parser does not know is dropped, and its seq with it — the page
// still renders what it could read. // still renders what it could read.
@@ -526,7 +648,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const event = parseTurnEvent(JSON.stringify(entry.event)) const event = parseTurnEvent(JSON.stringify(entry.event))
return event && typeof entry.seq === 'number' ? [{ seq: entry.seq, event }] : [] return event && typeof entry.seq === 'number' ? [{ seq: entry.seq, event }] : []
}) })
return { events, more: body.more === true } return { events, more: body.more === true, readOnly: body.read_only === true }
} }
async function providers(): Promise<ProvidersState> { async function providers(): Promise<ProvidersState> {
@@ -563,6 +685,18 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})) as ProvidersState })) 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[]> { async function accounts(): Promise<ClawAccount[]> {
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] } const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
return body.accounts return body.accounts
@@ -639,11 +773,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
* notice says so instead of naming an opaque abort error. */ * notice says so instead of naming an opaque abort error. */
let timedOut = false let timedOut = false
let silence: ReturnType<typeof setTimeout> | null = null 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 => { const rearmSilence = (): void => {
if (silence !== null) clearTimeout(silence) if (silence !== null) clearTimeout(silence)
silence = null
if (closed || isHidden()) return
silence = setTimeout(() => { silence = setTimeout(() => {
if (closed) return if (closed || isHidden()) return
timedOut = true timedOut = true
current?.abort() current?.abort()
}, STREAM_SILENCE_TIMEOUT_MS) }, STREAM_SILENCE_TIMEOUT_MS)
@@ -652,6 +794,23 @@ export function useClaw(token: Ref<string | null>): ClawApi {
if (silence !== null) clearTimeout(silence) if (silence !== null) clearTimeout(silence)
silence = null 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) => { const status = (next: StreamStatus) => {
if (!closed) handlers.onStatus?.(next) if (!closed) handlers.onStatus?.(next)
@@ -663,6 +822,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const controller = new AbortController() const controller = new AbortController()
current = controller current = controller
timedOut = false timedOut = false
hiddenDuringAttempt = isHidden()
rearmSilence() rearmSilence()
try { try {
const resume = cursor === null ? '' : `?since=${cursor}` const resume = cursor === null ? '' : `?since=${cursor}`
@@ -684,7 +844,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
await readFrames( await readFrames(
response.body, response.body,
(data, id) => { (data, id) => {
rearmSilence() noteActivity()
const event = parseTurnEvent(data) const event = parseTurnEvent(data)
if (!event) return if (!event) return
const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null
@@ -694,7 +854,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
(comment) => { (comment) => {
// Keep-alives come through here too; each one proves the // Keep-alives come through here too; each one proves the
// path alive. // path alive.
rearmSilence() noteActivity()
// The record lost what this mirror holds: drop the cursor // The record lost what this mirror holds: drop the cursor
// so the next open asks for the tail, and let the consumer // so the next open asks for the tail, and let the consumer
// drop its items before the tail that already followed // drop its items before the tail that already followed
@@ -720,11 +880,16 @@ export function useClaw(token: Ref<string | null>): ClawApi {
// Backoff caps at 15s: a live stream of a running turn is the // 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. // UI's whole job, so retries stay eager but not tight-looped.
const backoff = Math.min(15000, 1000 * 2 ** attempt++) const backoff = Math.min(15000, 1000 * 2 ** attempt++)
handlers.onNotice?.( // A connection that crossed a hidden tab reconnects quietly:
timedOut // the browser held it while the page was in the background,
? `the event stream went quiet (no keep-alive for ${STREAM_SILENCE_TIMEOUT_MS / 1000}s); reconnecting in ${backoff / 1000}s` // and the operator did not just lose a live stream.
: `event stream dropped (${cause instanceof Error ? cause.message : String(cause)}); retrying in ${backoff / 1000}s`, 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') status('reconnecting')
await new Promise((resolve) => setTimeout(resolve, backoff)) await new Promise((resolve) => setTimeout(resolve, backoff))
} finally { } finally {
@@ -738,6 +903,9 @@ export function useClaw(token: Ref<string | null>): ClawApi {
close() { close() {
closed = true closed = true
stopSilence() stopSilence()
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', visibility)
}
current?.abort() current?.abort()
}, },
} }
@@ -747,6 +915,9 @@ export function useClaw(token: Ref<string | null>): ClawApi {
sessions, sessions,
createSession, createSession,
deleteSession, deleteSession,
pauseSession,
resumeSession,
abortSession,
listConsents, listConsents,
resolveConsent, resolveConsent,
denyConsent, denyConsent,
@@ -757,6 +928,8 @@ export function useClaw(token: Ref<string | null>): ClawApi {
models, models,
setCredentials, setCredentials,
removeProvider, removeProvider,
sandbox,
setSandbox,
accounts, accounts,
addAccount, addAccount,
removeAccount, removeAccount,
@@ -836,6 +1009,24 @@ function parseUserImages(raw: unknown): UserImage[] {
return images 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. */ /** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
function parseTurnEvent(data: string): TurnEvent | null { function parseTurnEvent(data: string): TurnEvent | null {
try { try {
@@ -846,6 +1037,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'user_message', type: 'user_message',
text: String(raw.text ?? ''), text: String(raw.text ?? ''),
images: parseUserImages(raw.images), images: parseUserImages(raw.images),
pastes: parseUserPastes(raw.pastes),
} }
case 'thinking_delta': case 'thinking_delta':
case 'text_delta': case 'text_delta':
+79 -48
View File
@@ -6,7 +6,7 @@
// mirror when the stream reopens and folds what arrives, never the other // mirror when the stream reopens and folds what arrives, never the other
// way around. // way around.
import { ref } from 'vue' 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. */ /** One tool call inside a turn: started, then completed by its result. */
export interface ToolRow { 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. */ /** A transcript line: a message the local user sent, or one streamed turn. */
export type TranscriptItem = 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: 'turn'; id: number; turn: TurnBlock }
| { kind: 'consent'; id: number; consent: ConsentCard } | { kind: 'consent'; id: number; consent: ConsentCard }
| { kind: 'attachment'; id: number; attachment: AttachmentCard } | { kind: 'attachment'; id: number; attachment: AttachmentCard }
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
return lines.length return lines.length
} }
/** A chip's label: `▣1 5L` — the anchor's one-based id and the /** A chip's label from its line count: `▣1 5L` — the chip's
* payload's line count (the TUI's chip_label). */ * one-based id and the payload's line count (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string { export function chipLinesLabel(lines: number, index: number): string {
return `▣${index + 1} ${lineCount(paste)}L` return `▣${index + 1} ${lines}L`
} }
/** Appends each paste as one MARK-payload-MARK embed, in order — the /** A chip's label from its payload (the TUI's chip_label). */
* session's record of the prompt (paste::embed; a web draft holds no export function chipLabel(paste: string, index: number): string {
* anchors, so every payload lands at the end). */ return chipLinesLabel(lineCount(paste), index)
export function embedPastes(draft: string, pastes: string[]): string { }
return (
draft + /** The modern record the wire carries: each paste a byte span in the
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('') * 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. */ /** One scanned piece of embedded-form text. */
@@ -244,6 +277,7 @@ export function useTranscript() {
id: nextId++, id: nextId++,
text: event.text, text: event.text,
images: event.images.map((image) => ({ ...image, url: null, name: null })), images: event.images.map((image) => ({ ...image, url: null, name: null })),
pastes: event.pastes,
}) })
break break
} }
@@ -356,10 +390,10 @@ export function useTranscript() {
* Its images render from the staged previews — the claw stores them * Its images render from the staged previews — the claw stores them
* and the stream's echo dedupes against this row. Returns the row's * and the stream's echo dedupes against this row. Returns the row's
* id, so a failed POST can retract it. */ * 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++ const id = nextId++
pendingSent.push({ text, images: images.length, itemId: id }) 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 return id
} }
@@ -375,41 +409,42 @@ export function useTranscript() {
if (pending !== -1) pendingSent.splice(pending, 1) if (pending !== -1) pendingSent.splice(pending, 1)
} }
/** A consent card resolved: flipped in place, or ignored when no /** The cards on the mirror, at either depth. A card lands in the open
* card carries the id. The in-flight turn's entries hold the cards a * turn's entries and rides into the finished turn with it, so a scan
* running turn asked for; finished turns keep their own copies. */ * of the top-level rows alone misses everything a turn handed over.
function resolveConsent(id: string, granted: boolean): void { * The returned objects are the mirror's own, not copies: flipping one
if (live.value) { * flips what the panel renders. */
for (const entry of live.value.entries) { function cards(): TurnEntry[] {
if (entry.kind === 'consent' && entry.consent.id === id) { const found: TurnEntry[] = [...(live.value?.entries ?? [])]
entry.consent.granted = granted for (const item of items.value) {
return if (item.kind === 'consent' || item.kind === 'attachment') {
} found.push(item)
} else if (item.kind === 'turn') {
found.push(...item.turn.entries)
} }
} }
for (const item of items.value) { return found
if (item.kind === 'consent' && item.consent.id === id) { }
item.consent.granted = granted
/** A consent card resolved: flipped in place, or ignored when no
* card carries the id. */
function resolveConsent(id: string, granted: boolean): void {
for (const card of cards()) {
if (card.kind === 'consent' && card.consent.id === id) {
card.consent.granted = granted
return return
} }
} }
} }
/** An attachment's object URL landed; stored on its card. The useClaw /** An attachment's object URL landed; stored on every card that names
* the id. Two cards can hold one id when a page's open tail is dropped
* and re-read, so the loop does not stop at the first. The useClaw
* cache keeps a reconnect's replay from refetching the bytes. */ * cache keeps a reconnect's replay from refetching the bytes. */
function setAttachmentUrl(id: string, url: string): void { function setAttachmentUrl(id: string, url: string): void {
if (live.value) { for (const card of cards()) {
for (const entry of live.value.entries) { if (card.kind === 'attachment' && card.attachment.id === id) {
if (entry.kind === 'attachment' && entry.attachment.id === id) { card.attachment.url = url
entry.attachment.url = url
return
}
}
}
for (const item of items.value) {
if (item.kind === 'attachment' && item.attachment.id === id) {
item.attachment.url = url
return
} }
} }
} }
@@ -432,16 +467,12 @@ export function useTranscript() {
/** Whether a card for this consent id is already on the mirror — a /** Whether a card for this consent id is already on the mirror — a
* replayed request never stacks a second card beside the first. */ * replayed request never stacks a second card beside the first. */
function findConsent(id: string): boolean { function findConsent(id: string): boolean {
if (live.value?.entries.some((e) => e.kind === 'consent' && e.consent.id === id)) return true return cards().some((card) => card.kind === 'consent' && card.consent.id === id)
return items.value.some((item) => item.kind === 'consent' && item.consent.id === id)
} }
/** Whether a card for this attachment id is already on the mirror. */ /** Whether a card for this attachment id is already on the mirror. */
function findAttachment(id: string): boolean { function findAttachment(id: string): boolean {
if (live.value?.entries.some((e) => e.kind === 'attachment' && e.attachment.id === id)) { return cards().some((card) => card.kind === 'attachment' && card.attachment.id === id)
return true
}
return items.value.some((item) => item.kind === 'attachment' && item.attachment.id === id)
} }
/** Reads one page of older turns (whole turns, oldest first) and /** Reads one page of older turns (whole turns, oldest first) and
+1117 -1922
View File
File diff suppressed because it is too large. Load diff