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
61 changed files with 8389 additions and 2629 deletions

No files matched your search

+1
View File
@@ -1 +1,2 @@
/target/ /target/
.rhema/
Generated
+1540 -140
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*", "integrations/*"] members = ["crates/*", "integrations/*"]
[workspace.package] [workspace.package]
version = "0.4.0" version = "0.4.1"
edition = "2024" edition = "2024"
rust-version = "1.89" rust-version = "1.89"
license = "MIT" license = "MIT"
@@ -261,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,
+24 -20
View File
@@ -29,33 +29,37 @@ mock = ["rhema-core/mock"]
# shell, the approval seam, and revive-on-resume (rhema-bash), the # shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a # system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent) # provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.0" rhema-bash = "0.4.2"
rhema-prompt = "0.4.0" rhema-prompt = "0.4.2"
rhema-host-agent = "0.4.0" rhema-host-agent = "0.4.2"
rhema-autonomous-agent = "0.4.0" rhema-autonomous-agent = "0.4.2"
rhema-config = "0.4.0" rhema-config = "0.4.2"
rhema-core = "0.4.0" 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 = "0.4.0" 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 = "0.4.0" rhema-identity = "0.4.2"
rhema-rsd = "0.4.0" rhema-rsd = "0.4.2"
# The sandbox seam: where `bash` runs, local process or a daemon speaking # The sandbox seam: where `bash` runs, this host's processes, a daemon
# the wire protocol over HTTP # speaking the wire protocol over HTTP, or an ssh login on a far box.
rhema-sandbox = "0.4.0" # The choice carries an ssh private key as text, so a store-held
rhema-sandbox-http = "0.4.0" # 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 = "0.4.0" 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 = "0.4.0" rhema-provider = "0.4.2"
rhema-provider-registry = "0.4.0" 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 }
@@ -79,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 = "0.4.0" 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 = { version = "0.4.0", 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.
+53 -24
View File
@@ -70,9 +70,11 @@ 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 sandbox: # where bash runs; omit for this host
kind: http # local (default) or http kind: ssh # local (default), http, or ssh
url: https://box.example:7600 # the sandboxd base URL host: me@box.example # the ssh destination: an alias or user@host
token: sandbox-secret # the daemon's shared secret, if it has one 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
@@ -103,10 +105,15 @@ conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local` `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 keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. The settings screen writes the same choice to the 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 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 first use the claw copies the local workspace into the sandbox's
`/workspace`. Later edits stay there; the claw does not copy them back. 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
@@ -139,6 +146,9 @@ POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?}
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
@@ -150,7 +160,7 @@ 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 GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist 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
@@ -194,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
@@ -336,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
+33 -4
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() {
+148 -10
View File
@@ -26,7 +26,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 rhema_core::ToolSpec; use rhema_core::ToolSpec;
use rhema_prompt::render_template; use rhema_prompt::render_template;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -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();
+92 -4
View File
@@ -178,10 +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, or a /// Where the agent's `bash` runs: this host when unset, a
/// `rhema-sandboxd` over HTTP. The settings store owns the live /// `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. /// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>, 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 {
@@ -210,6 +233,7 @@ impl Default for ClawConfig {
ingest_token: None, ingest_token: None,
transcript: None, transcript: None,
sandbox: None, sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
@@ -444,6 +468,9 @@ sandbox:
kind: http kind: http
url: https://box.example:7600 url: https://box.example:7600
token: sandbox-secret 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);
@@ -464,6 +491,18 @@ sandbox:
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http); assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600")); assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret")); 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] #[test]
@@ -472,7 +511,7 @@ sandbox:
sandbox: Some(crate::sandbox::SandboxChoice { sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http, kind: crate::sandbox::SandboxKind::Http,
url: None, url: None,
token: None, ..crate::sandbox::SandboxChoice::default()
}), }),
..ClawConfig::default() ..ClawConfig::default()
}; };
@@ -484,13 +523,62 @@ sandbox:
sandbox: Some(crate::sandbox::SandboxChoice { sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http, kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()), url: Some("https://box.example:7600".to_owned()),
token: None, ..crate::sandbox::SandboxChoice::default()
}), }),
..ClawConfig::default() ..ClawConfig::default()
}; };
assert!(valid.validate().is_ok(), "a complete remote choice passes"); 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]
fn an_unknown_key_is_rejected_and_named() { fn an_unknown_key_is_rejected_and_named() {
let err = serde_yaml::from_str::<ClawConfig>("listne: 127.0.0.1:7799\n") let err = serde_yaml::from_str::<ClawConfig>("listne: 127.0.0.1:7799\n")
+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() {
+315 -34
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};
@@ -126,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.
@@ -142,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,
@@ -154,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>,
@@ -278,26 +360,45 @@ impl Daemon {
.map(|url| format!(" ({url})")) .map(|url| format!(" ({url})"))
.unwrap_or_default(), .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_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
@@ -318,7 +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()?)?);
// 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(
@@ -388,6 +488,7 @@ impl Daemon {
config.transcript_enabled(), config.transcript_enabled(),
) )
.with_steer(steer.clone()) .with_steer(steer.clone())
.with_abort(abort.clone())
.with_sandbox(sandbox.clone()); .with_sandbox(sandbox.clone());
let interactive_driver = Arc::new( let interactive_driver = Arc::new(
Driver::new( Driver::new(
@@ -395,9 +496,13 @@ impl Daemon {
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
@@ -409,13 +514,17 @@ impl Daemon {
config.max_turn_steps, config.max_turn_steps,
config.transcript_enabled(), config.transcript_enabled(),
) )
.with_sandbox(sandbox.clone()); .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);
@@ -430,6 +539,9 @@ impl Daemon {
bootstrap, bootstrap,
hub, hub,
steer, steer,
pause,
abort,
jobs,
backends.clone(), backends.clone(),
settings.clone(), settings.clone(),
identity, identity,
@@ -453,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)),
@@ -492,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 {
@@ -530,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());
@@ -537,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?;
@@ -556,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! {
@@ -580,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?;
@@ -591,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
+124 -34
View File
@@ -219,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 {
@@ -245,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()),
} }
} }
@@ -501,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
@@ -567,11 +570,11 @@ impl ForgeSource {
} }
// The row is decided — dispatched, surfaced, or ignored — so // The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning // consume it: `mark_read` is what stops the feed returning
// it. Deciding without consuming is a loop: the poll's cursor // it, and the durable cursor is what stops the poll asking
// never passes a row the forge still considers unread, so // for it again. Deciding without consuming is a loop: a row
// every pass re-decides it and re-dispatches a turn for a // the forge still considers unread comes back every pass —
// thread that already has one, and a restart (the cursor is // re-decided and re-dispatched as a fresh turn for a thread
// in memory) replays the whole unread feed. // that already has one — until the cursor passes it.
// //
// Best-effort: an unread row costs a repeat, never a lost // Best-effort: an unread row costs a repeat, never a lost
// event, so a failed call is logged and the poll carries on. // event, so a failed call is logged and the poll carries on.
@@ -582,11 +585,15 @@ impl ForgeSource {
); );
} }
} }
// 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)
} }
@@ -707,10 +714,9 @@ mod tests {
/// The account poll consumes what it decides. The feed is /// The account poll consumes what it decides. The feed is
/// at-least-once — the cursor never passes a row the forge still /// at-least-once — the cursor never passes a row the forge still
/// considers unread, and a restart asks for the whole unread feed /// considers unread, so a row that is triaged but not marked read
/// again — so a row that is triaged but not marked read comes back /// comes back with the same dedup id on the next pass, and every
/// with the same dedup id on the next pass, and every pass dispatches /// pass dispatches a fresh turn for a thread that already has one.
/// a fresh turn for a thread that already has one.
#[tokio::test] #[tokio::test]
async fn a_triaged_account_notification_is_marked_read() { async fn a_triaged_account_notification_is_marked_read() {
let server = MockServer::start().await; let server = MockServer::start().await;
@@ -734,20 +740,18 @@ mod tests {
.await; .await;
let store = Arc::new(ClawStore::in_memory().expect("store opens")); let store = Arc::new(ClawStore::in_memory().expect("store opens"));
store
.add_account_watch("github", Some(&server.uri()), "acct-1")
.expect("account watch lands");
let (dispatcher, accounts, notifications) = test_parts(store.clone()); let (dispatcher, accounts, notifications) = test_parts(store.clone());
accounts // The store mints the id; the watch row is what names it.
.put( let account = accounts
rhema_identity::AccountDraft::new( .put(rhema_identity::AccountDraft::new(
"forge bot", "forge bot",
"github", "github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"), rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
) ))
.with_id("acct-1"),
)
.expect("account lands"); .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); let source = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
assert_eq!( assert_eq!(
@@ -766,6 +770,92 @@ mod tests {
assert_eq!(reads[0].url.path(), "/notifications/threads/42188"); 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(
store: Arc<ClawStore>, store: Arc<ClawStore>,
+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")
);
}
}
+263 -39
View File
@@ -23,6 +23,7 @@ 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_autonomous_agent::{Handler, SessionContext, async_trait}; use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
@@ -49,14 +50,25 @@ use crate::sandbox::SandboxState;
/// [`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
@@ -75,6 +87,13 @@ pub struct ClawHandler {
/// Where commands run: this host when absent, a remote sandbox when /// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per dispatch. /// the surface selected one. Read per dispatch.
sandbox: Option<Arc<SandboxState>>, 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>>>, clients: Mutex<HashMap<String, Arc<WatchClient>>>,
} }
@@ -86,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 {
@@ -95,8 +115,10 @@ impl ClawHandler {
workspace_root: workspace_root.into(), workspace_root: workspace_root.into(),
watches, watches,
accounts, accounts,
bootstrap,
tool_env, tool_env,
sandbox: None, sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
clients: Mutex::new(HashMap::new()), clients: Mutex::new(HashMap::new()),
} }
} }
@@ -108,6 +130,14 @@ impl ClawHandler {
self 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
@@ -294,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) // 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())
@@ -344,7 +392,7 @@ impl ClawHandler {
key: &str, key: &str,
) -> Result<HostAgent, String> { ) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current(); let (provider, model) = self.backends.current();
let config = self.agent_config(provider, &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 => HostAgent::new(config), serde_json::Value::Null => HostAgent::new(config),
@@ -357,17 +405,20 @@ impl ClawHandler {
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
/// and a remote shell when the sandbox choice says so. /// thread's workspace, SOUL.md and USER.md live — with the bounded
/// A forge thread answers for as long as the thread lives; without /// request view when the config has it on and a remote shell when
/// the view its history would ride whole on every step. /// the sandbox choice says so. A forge thread answers for as long
/// as the thread lives; without the view its history would ride
/// whole on every step.
fn agent_config( fn agent_config(
&self, &self,
provider: Arc<dyn rhema_core::ModelProvider>, provider: Arc<dyn rhema_core::ModelProvider>,
model: &str, model: &str,
workspace: &Path, workspace: &Path,
) -> HostAgentConfig { key: &str,
) -> Result<HostAgentConfig, String> {
let display = match &self.sandbox { let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(workspace), Some(sandbox) => sandbox.workspace_for(workspace),
None => workspace.to_path_buf(), None => workspace.to_path_buf(),
@@ -379,19 +430,47 @@ impl ClawHandler {
.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();
// The prompt names the workspace the model sees and documents
// exactly what the request advertises: the shell built-ins plus
// 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 { match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => { Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor( config.tools = Some(Arc::new(ShellTools::with_executor(
display, display.clone(),
sandbox.executor(workspace.to_path_buf()), sandbox.executor(workspace.to_path_buf()),
))); )));
} }
_ => { _ => {
crate::vision::apply(&mut config); crate::vision::apply(&mut config);
crate::mcp::apply(&mut config); crate::mcp::apply(&mut config);
vision = config.vision.clone();
mcp = config.mcp_servers.clone();
} }
} }
config 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
@@ -626,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.
@@ -662,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!(
@@ -1084,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"),
@@ -1117,6 +1201,14 @@ mod tests {
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"));
@@ -1133,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(),
); );
@@ -1198,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(),
); );
@@ -1257,11 +1353,13 @@ mod tests {
); );
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new()); let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0; 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(),
); );
@@ -1270,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(provider.clone(), "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(provider, "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}"
); );
} }
+328 -39
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>,
@@ -162,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>,
@@ -186,6 +202,9 @@ impl ClawState {
bootstrap, bootstrap,
hub, hub,
steer, steer,
pause,
abort,
jobs,
backends, backends,
settings, settings,
identity, identity,
@@ -203,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()? {
@@ -214,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)
@@ -234,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
@@ -263,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 {
@@ -307,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)),
@@ -633,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.
@@ -859,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
@@ -1019,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
@@ -1051,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) {
@@ -1079,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)> {
@@ -2016,6 +2279,12 @@ fn sandbox_json(state: &ClawState) -> Value {
"kind": choice.kind.as_str(), "kind": choice.kind.as_str(),
"url": choice.url, "url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()), "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(), "workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(), "local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE, "remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
@@ -2023,8 +2292,9 @@ fn sandbox_json(state: &ClawState) -> Value {
} }
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and /// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` is write-only; `clear_token` drops the /// persist the choice. `token` and `private_key` are write-only;
/// stored one. The choice applies on the next turn, no restart. /// `clear_token` and `clear_private_key` drop the stored ones. The
/// choice applies on the next turn, no restart.
async fn sandbox_put( async fn sandbox_put(
State(state): State<ClawState>, State(state): State<ClawState>,
Json(body): Json<Value>, Json(body): Json<Value>,
@@ -2044,6 +2314,15 @@ async fn sandbox_put(
.map(str::to_owned) .map(str::to_owned)
.or_else(|| current.token.clone()) .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 { let choice = crate::sandbox::SandboxChoice {
kind, kind,
url: body["url"] url: body["url"]
@@ -2051,6 +2330,15 @@ async fn sandbox_put(
.map(str::to_owned) .map(str::to_owned)
.or_else(|| current.url.clone()), .or_else(|| current.url.clone()),
token, 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 { state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err), crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
@@ -2297,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),
+110 -2
View File
@@ -28,11 +28,11 @@
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, PoisonError};
use rhema_core::paste::PasteSpan;
use rhema_rsd::ResourceKey; 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.
@@ -129,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
@@ -330,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
@@ -915,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.
+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");
} }
+218 -24
View File
@@ -62,6 +62,14 @@
//! the conversation shows the question, the cut, and the answer that //! the conversation shows the question, the cut, and the answer that
//! replaced the rest of the interrupted work, exactly the shape //! replaced the rest of the interrupted work, exactly the shape
//! rhema-code's UI draws for a steered turn. //! rhema-code's UI draws for a steered turn.
//!
//! **Aborting** rides the same interrupt and ends instead of looping:
//! a signal from the abort registry ([`crate::abort`]) drops the turn
//! future at its await, the dangling calls close, the session stashes,
//! and the dispatch releases as superseded with the `aborted` outcome
//! on the stream. Unlike a steer signal, an abort carries no inbox
//! message, so a pending abort is honored between rounds, not cleared
//! with the stale steer signals.
use std::collections::HashMap; use std::collections::HashMap;
use std::num::NonZeroU32; use std::num::NonZeroU32;
@@ -70,7 +78,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait}; use async_trait::async_trait;
use rhema_autonomous_agent::{Handler, SessionContext};
use rhema_bash::{AllowAll, ShellTools}; use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{ use rhema_core::{
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message, Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
@@ -81,12 +90,14 @@ use rhema_memory::{MemoryResolver, MemoryStore, Scope};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey}; use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::abort::{AbortGuard, AbortRegistry};
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system}; use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
use crate::hub::{EventHub, TurnEvent, UserImage}; use crate::hub::{EventHub, TurnEvent, UserImage};
use crate::notifications::NotificationStore; use crate::notifications::NotificationStore;
use crate::sandbox::SandboxState; use crate::sandbox::SandboxState;
use crate::steer::{SteerGuard, SteerRegistry}; use crate::steer::{SteerGuard, SteerRegistry};
use crate::toolkit::{Allowlist, ResolverChain};
/// The key prefixes of the resident context (see the module docs): /// The key prefixes of the resident context (see the module docs):
/// `interactive:`, `task:`, `phone:`, and `calendar:`. Forge keys — /// `interactive:`, `task:`, `phone:`, and `calendar:`. Forge keys —
@@ -238,6 +249,12 @@ pub struct InteractiveHandler {
/// registry with never receives a signal — and shared with the /// registry with never receives a signal — and shared with the
/// HTTP surface through [`InteractiveHandler::with_steer`]. /// HTTP surface through [`InteractiveHandler::with_steer`].
steer: Arc<SteerRegistry>, steer: Arc<SteerRegistry>,
/// The abort registry the sessions' abort route signals: a live
/// turn cut at its await ends the dispatch as superseded (see
/// [`crate::abort`]). Built private by
/// [`InteractiveHandler::new`], shared through
/// [`InteractiveHandler::with_abort`].
abort: Arc<AbortRegistry>,
/// The notification table: the `notify` tool writes it, and /// The notification table: the `notify` tool writes it, and
/// non-interactive replies auto-notify through it. /// non-interactive replies auto-notify through it.
notifications: Arc<NotificationStore>, notifications: Arc<NotificationStore>,
@@ -307,6 +324,7 @@ impl InteractiveHandler {
bootstrap_resolver, bootstrap_resolver,
hub, hub,
steer: Arc::new(SteerRegistry::new()), steer: Arc::new(SteerRegistry::new()),
abort: Arc::new(AbortRegistry::new()),
notifications, notifications,
attachments, attachments,
max_turn_steps, max_turn_steps,
@@ -365,6 +383,8 @@ impl InteractiveHandler {
&self.bootstrap, &self.bootstrap,
&resolver.specs(), &resolver.specs(),
vision, vision,
&[],
crate::bootstrap::Surface::Chat,
) )
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?; .map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
Agent::builder() Agent::builder()
@@ -385,6 +405,15 @@ impl InteractiveHandler {
self self
} }
/// Shares `abort` with the HTTP surface: the abort route signals it,
/// and every dispatch chain this handler runs listens on it.
/// Without this call the handler keeps the constructor's private
/// registry, which no route can reach.
pub fn with_abort(mut self, abort: Arc<AbortRegistry>) -> Self {
self.abort = abort;
self
}
/// The workspace the prompt names: the host path locally, the /// The workspace the prompt names: the host path locally, the
/// sandbox root when commands run elsewhere. /// sandbox root when commands run elsewhere.
fn workspace(&self) -> PathBuf { fn workspace(&self) -> PathBuf {
@@ -430,13 +459,16 @@ impl InteractiveHandler {
} }
/// One round: drain, restore, turn, stash, reply. The turn runs /// One round: drain, restore, turn, stash, reply. The turn runs
/// under the steer select, so a round that was interrupted comes /// under the steer/abort select, so a round that was interrupted
/// back as [`Round::Steered`] with the session stashed and the /// comes back as [`Round::Steered`] or [`Round::Aborted`] with the
/// dangling calls closed. /// session stashed and the dangling calls closed — steered, the
/// caller owes the inbox another round; aborted, the caller ends
/// the chain.
async fn dispatch( async fn dispatch(
&self, &self,
ctx: &mut SessionContext, ctx: &mut SessionContext,
steer: &mut SteerGuard, steer: &mut SteerGuard,
abort: &mut AbortGuard,
round: usize, round: usize,
) -> Result<Round, String> { ) -> Result<Round, String> {
let key = ctx.key.as_str().to_owned(); let key = ctx.key.as_str().to_owned();
@@ -467,8 +499,8 @@ impl InteractiveHandler {
// plain either way before the join, its span // plain either way before the join, its span
// measured where it lands. // measured where it lands.
let mut message = [Message::text(Role::User, text.to_owned())]; let mut message = [Message::text(Role::User, text.to_owned())];
rhema_core::paste::migrate(&mut message); crate::paste::migrate(&mut message);
let mut spans = rhema_core::paste::spans(&message[0]); let mut spans = crate::paste::spans(&message[0]);
let mut composed = match &message[0].content[0] { let mut composed = match &message[0].content[0] {
Content::Text(text) => text.clone(), Content::Text(text) => text.clone(),
_ => unreachable!("the message was built with one text block"), _ => unreachable!("the message was built with one text block"),
@@ -479,9 +511,9 @@ impl InteractiveHandler {
.into_iter() .into_iter()
.flatten() .flatten()
.filter_map(Value::as_str) .filter_map(Value::as_str)
.map(rhema_core::paste::normalize) .map(crate::paste::normalize)
{ {
let span = rhema_core::paste::PasteSpan { let span = crate::paste::PasteSpan {
start: composed.len(), start: composed.len(),
end: composed.len() + paste.len(), end: composed.len() + paste.len(),
lines: paste.lines().count(), lines: paste.lines().count(),
@@ -508,7 +540,7 @@ impl InteractiveHandler {
} }
let base = input.len(); let base = input.len();
input.push_str(&text); input.push_str(&text);
pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan { pastes.extend(spans.into_iter().map(|span| crate::paste::PasteSpan {
start: span.start + base, start: span.start + base,
end: span.end + base, end: span.end + base,
lines: span.lines, lines: span.lines,
@@ -639,14 +671,14 @@ impl InteractiveHandler {
let framed_len = input.len(); let framed_len = input.len();
let pastes = pastes let pastes = pastes
.iter() .iter()
.map(|span| rhema_core::paste::PasteSpan { .map(|span| crate::paste::PasteSpan {
start: span.start + framed_len - recorded_len, start: span.start + framed_len - recorded_len,
end: span.end + framed_len - recorded_len, end: span.end + framed_len - recorded_len,
lines: span.lines, lines: span.lines,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut question = [Message::text_with_images(Role::User, input, core_images)]; let mut question = [Message::text_with_images(Role::User, input, core_images)];
rhema_core::paste::annotate(&mut question[0], &pastes); crate::paste::annotate(&mut question[0], &pastes);
let [turn_input] = question; let [turn_input] = question;
let mut turn = Box::pin(run_turn( let mut turn = Box::pin(run_turn(
&mut agent, &mut agent,
@@ -656,6 +688,7 @@ impl InteractiveHandler {
&tools, &tools,
self.max_turn_steps, self.max_turn_steps,
)); ));
let mut aborted = false;
let finished = tokio::select! { let finished = tokio::select! {
result = &mut turn => match steer.take() { result = &mut turn => match steer.take() {
// A message that raced the completion steers the next // A message that raced the completion steers the next
@@ -666,6 +699,13 @@ impl InteractiveHandler {
), ),
}, },
_ = steer.wait() => None, _ = steer.wait() => None,
_ = abort.wait() => {
// The operator cut the turn: no next round's input is
// coming, so the caller ends the chain rather than
// looping.
aborted = true;
None
}
}; };
drop(turn); drop(turn);
// An interrupted turn can leave committed calls without // An interrupted turn can leave committed calls without
@@ -682,6 +722,7 @@ impl InteractiveHandler {
match finished { match finished {
Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))), Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))),
Some(Err(reason)) => Err(reason), Some(Err(reason)) => Err(reason),
None if aborted => Ok(Round::Aborted),
None => Ok(Round::Steered), None => Ok(Round::Steered),
} }
} }
@@ -691,19 +732,27 @@ impl InteractiveHandler {
impl Handler for InteractiveHandler { impl Handler for InteractiveHandler {
async fn handle(&self, ctx: &mut SessionContext) -> Outcome { async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
let key = ctx.key.clone(); let key = ctx.key.clone();
// The listener lives across the whole chain: one lease, one // The listeners live across the whole chain: one lease, one
// listener, every steered round under it. `Drop` unregisters // listener each, every steered round under them. `Drop`
// before the outcome releases the lease, so no signal can // unregisters before the outcome releases the lease, so no
// address a turn that no longer runs. // signal can address a turn that no longer runs.
let mut steer = self.steer.listen(key.as_str()); let mut steer = self.steer.listen(key.as_str());
let mut abort = self.abort.listen(key.as_str());
let mut round = 1; let mut round = 1;
let mut aborted = false;
let finished = loop { let finished = loop {
// Stale signals first: the route signals only after its // Stale signals first: the route signals only after its
// ingest, so anything pending here is already in the inbox // ingest, so anything pending here is already in the inbox
// waiting for this round's drain — a signal must never cut // waiting for this round's drain — a signal must never cut
// the round it precedes. // the round it precedes. An abort is the opposite: it
// carries no inbox message, so a pending one is honored
// here, not cleared.
steer.clear(); steer.clear();
match self.dispatch(ctx, &mut steer, round).await { if abort.take() {
aborted = true;
break Ok(None);
}
match self.dispatch(ctx, &mut steer, &mut abort, round).await {
Ok(Round::Done(reply)) => break reply, Ok(Round::Done(reply)) => break reply,
// A steered round that drained nothing: the interrupt // A steered round that drained nothing: the interrupt
// already happened, the chain just ends instead of // already happened, the chain just ends instead of
@@ -721,10 +770,29 @@ impl Handler for InteractiveHandler {
); );
round += 1; round += 1;
} }
Ok(Round::Aborted) => {
aborted = true;
break Ok(None);
}
Err(reason) => break Err(reason), Err(reason) => break Err(reason),
} }
}; };
drop(steer); drop(steer);
drop(abort);
if aborted {
// The end marker matters most when the run was cut: a
// stream that just goes quiet is indistinguishable from a
// hang. Superseded, not failed — the work is no longer
// wanted, exactly the outcome's own words.
self.hub.emit(
&key,
TurnEvent::TurnDone {
reply: None,
outcome: "aborted".to_owned(),
},
);
return Outcome::Superseded;
}
match finished { match finished {
Ok(reply) => { Ok(reply) => {
self.auto_notify(&key, reply.as_deref()); self.auto_notify(&key, reply.as_deref());
@@ -775,14 +843,17 @@ impl InteractiveHandler {
} }
} }
/// One dispatch round's shape. A steered round ended in an interrupt: /// One dispatch round's shape. A steered or aborted round ended in an
/// interrupt: the session stashed, the dangling calls closed — steered,
/// the caller owes the inbox another round on the same lease, same /// the caller owes the inbox another round on the same lease, same
/// session, same stream. /// session, same stream; aborted, the caller ends the chain.
enum Round { enum Round {
/// The turn ran to its end; the final reply text. /// The turn ran to its end; the final reply text.
Done(Result<Option<String>, String>), Done(Result<Option<String>, String>),
/// A steered message cut the turn short. /// A steered message cut the turn short.
Steered, Steered,
/// The operator's abort cut the turn short.
Aborted,
/// A steered round whose inbox drained empty — the belt-and-braces /// A steered round whose inbox drained empty — the belt-and-braces
/// exit for a signal whose message raced the previous round's /// exit for a signal whose message raced the previous round's
/// drain: end the chain quietly, fail nothing. /// drain: end the chain quietly, fail nothing.
@@ -802,7 +873,7 @@ fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
// embedded form in its prompts; the provider must never see // embedded form in its prompts; the provider must never see
// a mark. One rewrite on the way in, chips survive as the // a mark. One rewrite on the way in, chips survive as the
// span note — the same pass the driver's from_session runs. // span note — the same pass the driver's from_session runs.
rhema_core::paste::migrate(&mut session.history); crate::paste::migrate(&mut session.history);
Ok(session) Ok(session)
} }
} }
@@ -826,7 +897,7 @@ fn final_text(message: &Message) -> Option<String> {
/// A tool result's bounded summary for the stream: the first line, cut /// A tool result's bounded summary for the stream: the first line, cut
/// at 72 characters like the daemon's own log lines. /// at 72 characters like the daemon's own log lines.
fn snippet(content: &str) -> String { pub(crate) fn snippet(content: &str) -> String {
let line = content.lines().next().unwrap_or(""); let line = content.lines().next().unwrap_or("");
let mut cut = line.chars().take(72).collect::<String>(); let mut cut = line.chars().take(72).collect::<String>();
if line.chars().count() > 72 { if line.chars().count() > 72 {
@@ -854,7 +925,7 @@ struct HubSink {
/// arguments JSON. A call whose args never streamed, or that parses to /// arguments JSON. A call whose args never streamed, or that parses to
/// something without a string `command`, renders without one — the TUI's /// something without a string `command`, renders without one — the TUI's
/// transcript makes the same bargain with the same deltas. /// transcript makes the same bargain with the same deltas.
fn shell_command(args: Option<&str>) -> Option<String> { pub(crate) fn shell_command(args: Option<&str>) -> Option<String> {
let parsed = serde_json::from_str::<Value>(args?).ok()?; let parsed = serde_json::from_str::<Value>(args?).ok()?;
parsed.get("command")?.as_str().map(str::to_owned) parsed.get("command")?.as_str().map(str::to_owned)
} }
@@ -1390,6 +1461,8 @@ mod tests {
&handler.bootstrap, &handler.bootstrap,
&specs, &specs,
None, None,
&[],
crate::bootstrap::Surface::Chat,
) )
.expect("renders"); .expect("renders");
assert!( assert!(
@@ -1683,8 +1756,8 @@ mod tests {
// The chip rides as the span note: one span, over exactly the // The chip rides as the span note: one span, over exactly the
// payload's range, and no mark survives the restore. // payload's range, and no mark survives the restore.
assert_eq!( assert_eq!(
rhema_core::paste::spans(&session.history[0]).as_slice(), crate::paste::spans(&session.history[0]).as_slice(),
&[rhema_core::paste::PasteSpan { &[crate::paste::PasteSpan {
start: "review this:".len(), start: "review this:".len(),
end: "review this:".len() + payload.len(), end: "review this:".len() + payload.len(),
lines: 3, lines: 3,
@@ -1932,6 +2005,127 @@ mod tests {
); );
} }
/// An abort signal cuts a live turn and ends the chain: the turn
/// closes on the stream with the `aborted` outcome, the dispatch
/// releases as superseded, and nothing follows — unlike the steer,
/// which loops onto its next round.
#[tokio::test]
async fn an_abort_signal_cuts_the_live_turn_and_ends_the_chain() {
let gate = Arc::new(Gate::default());
let registry = Arc::new(crate::abort::AbortRegistry::new());
let hub = Arc::new(EventHub::default());
let workspace = tempfile::tempdir().expect("tempdir");
let notifications = notifications();
let extensions = test_extensions(
hub.clone(),
Arc::new(ClawStore::in_memory().expect("store opens")),
notifications.clone(),
tasks(),
jobs(),
accounts(),
consents(),
bridge(),
attachments(),
phone(),
identity(),
&workspace.path().join("interactive"),
);
let handler = InteractiveHandler::new(
test_registry(Arc::new(GatedProvider::new(gate.clone()))),
workspace.path().join("interactive"),
Arc::new(rhema_memory::VolatileStore::new()),
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
hub.clone(),
notifications.clone(),
attachments(),
crate::config::DEFAULT_MAX_TURN_STEPS,
extensions,
true,
)
.with_abort(registry.clone());
let volatile = Arc::new(VolatileStore::new());
let dispatcher = Arc::new(Dispatcher::new(
DispatcherConfig {
debounce_window_millis: 0,
..DispatcherConfig::default()
},
Arc::new(rhema_rsd::SystemClock),
volatile.clone(),
));
register_user(&dispatcher);
let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key);
dispatcher
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
// The pass runs off the test task; the generation parks in the
// gate once it is in flight — the turn the abort cuts.
let pass = tokio::spawn(async move { driver.run_once().await });
let mut in_flight = gate.in_flight_rx();
while !*in_flight.borrow_and_update() {
in_flight
.changed()
.await
.expect("the in-flight sender lives");
}
assert!(registry.signal(key.as_str()));
// Superseded, not handled: the work is no longer wanted.
assert_eq!(
pass.await.expect("the pass joins").expect("the pass runs"),
vec![RsdOutcome::Superseded]
);
// Stream order: the question, then the abort, and nothing
// after it — no steered round, no answer.
assert_eq!(
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
receiver.try_recv().unwrap(),
TurnEvent::TurnDone {
reply: None,
outcome: "aborted".into()
}
);
assert!(
receiver.try_recv().is_err(),
"the chain ended: nothing follows the cut"
);
// The key is back to idle with an empty inbox, and the
// conversation keeps the question the turn never answered.
assert_eq!(
dispatcher.status(&key).expect("status reads").state,
KeyState::Idle
);
let record = rhema_rsd::Store::load(volatile.as_ref(), &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 turns: Vec<(CoreRole, &str)> = stashed
.history
.iter()
.filter_map(|message| match &message.content[0] {
Content::Text(text) => Some((message.role, text.as_str())),
_ => None,
})
.collect();
assert_eq!(turns, [(CoreRole::User, "hello")]);
}
/// The steer test's synchronization: the provider announces the /// The steer test's synchronization: the provider announces the
/// generation's arrival. /// generation's arrival.
struct Gate { struct Gate {
+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() {
+113 -4
View File
@@ -147,6 +147,12 @@ pub struct CodingJobHandler {
/// Where commands run: this host when absent, a remote sandbox when /// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job. /// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>, 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 {
@@ -167,6 +173,7 @@ impl CodingJobHandler {
max_turn_steps, max_turn_steps,
transcript, transcript,
sandbox: None, sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
} }
} }
@@ -177,10 +184,24 @@ impl CodingJobHandler {
self 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
@@ -281,16 +302,37 @@ impl CodingJobHandler {
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).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(|| {
@@ -397,6 +439,73 @@ mod tests {
) )
} }
/// 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 {
ModelOutput { ModelOutput {
message: CoreMessage::text(Role::Assistant, text), message: CoreMessage::text(Role::Assistant, text),
+14 -4
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
@@ -66,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;
@@ -76,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;
@@ -90,6 +96,8 @@ 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 sandbox;
pub mod settings; pub mod settings;
@@ -97,6 +105,8 @@ 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;
@@ -108,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;
+8 -3
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)]
@@ -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
} }
} }
+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,
+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() {
+304 -57
View File
@@ -1,16 +1,20 @@
//! Where the claw's `bash` runs: this host's processes, or a daemon //! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP. //! 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 //! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw //! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd` //! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! and gives the handlers a `ShellSandbox` executor over it. The tool //! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! spec, approval gate, output caps, and error shaping stay in //! 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. //! `ShellTools`; only the machine changes.
//! //!
//! A remote sandbox starts empty. On the first command for a //! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes `/workspace` and, when it is empty, //! workspace, the executor probes the workspace root and, when it is
//! sends the host workspace as a tarball through the protocol's seed //! empty, sends the host workspace as a tarball through the seed
//! route. Later edits stay in the sandbox; the claw does not copy them //! route. Later edits stay in the sandbox; the claw does not copy them
//! back. //! back.
@@ -22,9 +26,11 @@ use std::time::Duration;
use async_trait::async_trait; use async_trait::async_trait;
use base64::Engine as _; use base64::Engine as _;
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with}; use rhema_bash::exec::{RunOutcome, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed}; use rhema_core::{OutputOnly, ToolProgress};
use rhema_sandbox::{RunRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox; use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore; use crate::settings::SettingsStore;
@@ -32,10 +38,15 @@ use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under. /// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox"; pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path a remote sandbox exposes: one root per session, /// The workspace path the http sandbox exposes: one root per session,
/// fixed by the protocol. /// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace"; 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 /// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon /// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it. /// fails the turn rather than stalling it.
@@ -50,6 +61,8 @@ pub enum SandboxKind {
Local, Local,
/// A host speaking the sandbox protocol over HTTP. /// A host speaking the sandbox protocol over HTTP.
Http, Http,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
} }
impl SandboxKind { impl SandboxKind {
@@ -58,6 +71,7 @@ impl SandboxKind {
match self { match self {
Self::Local => "local", Self::Local => "local",
Self::Http => "http", Self::Http => "http",
Self::Ssh => "ssh",
} }
} }
@@ -67,6 +81,7 @@ impl SandboxKind {
match value { match value {
"local" => Some(Self::Local), "local" => Some(Self::Local),
"http" => Some(Self::Http), "http" => Some(Self::Http),
"ssh" => Some(Self::Ssh),
_ => None, _ => None,
} }
} }
@@ -86,6 +101,22 @@ pub struct SandboxChoice {
/// The shared secret the daemon checks, when it guards its routes. /// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>, 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 { impl SandboxChoice {
@@ -101,6 +132,36 @@ impl SandboxChoice {
.token .token
.map(|token| token.trim().to_owned()) .map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty()); .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 { if self.kind == SandboxKind::Http {
let url = self let url = self
.url .url
@@ -117,7 +178,22 @@ impl SandboxChoice {
/// Whether commands leave this host. /// Whether commands leave this host.
pub fn is_remote(&self) -> bool { pub fn is_remote(&self) -> bool {
self.kind == SandboxKind::Http 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(),
}
} }
} }
@@ -139,7 +215,7 @@ pub struct SandboxState {
settings: Arc<SettingsStore>, settings: Arc<SettingsStore>,
local_workspace: PathBuf, local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>, local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>, remote: Mutex<HashMap<String, Arc<dyn Sandbox>>>,
} }
impl SandboxState { impl SandboxState {
@@ -204,13 +280,9 @@ impl SandboxState {
} }
/// The workspace a handler should name and start commands in: the /// The workspace a handler should name and start commands in: the
/// host path locally, `/workspace` on a remote sandbox. /// host path locally, the choice's remote root otherwise.
pub fn workspace_for(&self, host: &Path) -> PathBuf { pub fn workspace_for(&self, host: &Path) -> PathBuf {
if self.is_remote() { self.choice().remote_root(host)
PathBuf::from(REMOTE_WORKSPACE)
} else {
host.to_path_buf()
}
} }
/// The chat workspace under the current choice, for the settings /// The chat workspace under the current choice, for the settings
@@ -239,18 +311,14 @@ impl SandboxState {
}) })
} }
/// The cached HTTP client for one session. The map is cleared /// The cached sandbox for one session. The map is cleared whenever
/// whenever the choice changes, so a new URL or token builds a new /// the choice changes, so a new URL, token, host, or base builds a
/// client. /// new client.
fn remote_sandbox( fn remote_sandbox(
&self, &self,
choice: &SandboxChoice, choice: &SandboxChoice,
host: &Path, host: &Path,
) -> Result<Arc<HttpSandbox>, ShellError> { ) -> Result<Arc<dyn Sandbox>, ShellError> {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let session = session_name(host); let session = session_name(host);
{ {
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner); let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
@@ -258,8 +326,33 @@ impl SandboxState {
return Ok(sandbox.clone()); return Ok(sandbox.clone());
} }
} }
let token = choice.token.as_deref().unwrap_or(""); let sandbox: Arc<dyn Sandbox> =
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token)); 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 self.remote
.lock() .lock()
.unwrap_or_else(PoisonError::into_inner) .unwrap_or_else(PoisonError::into_inner)
@@ -280,20 +373,32 @@ struct ClawShell {
} }
impl ClawShell { impl ClawShell {
/// Seeds the sandbox once per choice. An empty `/workspace` gets /// Seeds the sandbox once per choice. An empty workspace root gets
/// the host workspace as a tarball; a non-empty one is left alone /// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox. /// 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( async fn seed(
&self, &self,
sandbox: &Arc<HttpSandbox>, sandbox: &Arc<dyn Sandbox>,
cancelled: &AtomicBool, cancelled: &AtomicBool,
) -> Result<(), ShellError> { ) -> Result<(), ShellError> {
let mut sink = |_line: &str| {}; let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = OutputOnly(|_line: &str| {});
let probe = sandbox let probe = sandbox
.exec( .run(
ExecRequest { RunRequest {
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(), command: format!(
cwd: REMOTE_WORKSPACE.to_owned(), "mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone().into(),
timeout: PROBE_TIMEOUT, timeout: PROBE_TIMEOUT,
}, },
cancelled, cancelled,
@@ -328,18 +433,13 @@ impl ClawShell {
impl ShellExecutor for ClawShell { impl ShellExecutor for ClawShell {
async fn run( async fn run(
&self, &self,
command: &str, request: RunRequest,
cwd: &Path,
timeout: Duration,
cancelled: &AtomicBool, cancelled: &AtomicBool,
progress: &mut (dyn for<'a> FnMut(&'a str) + Send), progress: &mut dyn ToolProgress,
) -> Result<Executed, ShellError> { ) -> Result<RunOutcome, ShellError> {
let choice = self.state.choice(); let choice = self.state.choice();
if !choice.is_remote() { if !choice.is_remote() {
return self return self.local.run(request, cancelled, progress).await;
.local
.run(command, cwd, timeout, cancelled, progress)
.await;
} }
{ {
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
@@ -353,12 +453,14 @@ impl ShellExecutor for ClawShell {
self.seed(&sandbox, cancelled).await?; self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed); self.seeded.store(true, Ordering::Relaxed);
} }
let sandbox: Arc<dyn Sandbox> = sandbox; let root = choice.remote_root(&self.host_workspace);
ShellSandbox::new(sandbox) ShellSandbox::new(sandbox)
.run( .run(
command, RunRequest {
Path::new(REMOTE_WORKSPACE), command: request.command,
timeout, cwd: root,
timeout: request.timeout,
},
cancelled, cancelled,
progress, progress,
) )
@@ -371,6 +473,7 @@ impl ShellExecutor for ClawShell {
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError { fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err { match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs), rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::OutOfMemory => ShellError::OutOfMemory,
rhema_sandbox::SandboxError::Unavailable(message) rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message), | rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still // The error enum is non-exhaustive: an unknown failure is still
@@ -379,6 +482,13 @@ fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
} }
} }
/// 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 /// 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 /// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root. /// and a restart finds the same root.
@@ -458,7 +568,7 @@ mod tests {
let missing = SandboxChoice { let missing = SandboxChoice {
kind: SandboxKind::Http, kind: SandboxKind::Http,
url: None, url: None,
token: None, ..SandboxChoice::default()
} }
.normalized(); .normalized();
assert!(missing.is_err(), "a URL is required"); assert!(missing.is_err(), "a URL is required");
@@ -466,18 +576,90 @@ mod tests {
let relative = SandboxChoice { let relative = SandboxChoice {
kind: SandboxKind::Http, kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()), url: Some("box.example:7600".to_owned()),
token: None, ..SandboxChoice::default()
} }
.normalized(); .normalized();
assert!(relative.is_err(), "a bare host is not a URL"); 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] #[test]
fn the_remote_workspace_is_the_sandbox_root() { fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice { let state = state(SandboxChoice {
kind: SandboxKind::Http, kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()), url: Some("http://box:7600/".to_owned()),
token: None, ..SandboxChoice::default()
}); });
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE)); assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!( assert_eq!(
@@ -487,6 +669,36 @@ mod tests {
); );
} }
#[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] #[test]
fn a_choice_persists_and_reloads() { fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens")); let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
@@ -504,6 +716,7 @@ mod tests {
kind: SandboxKind::Http, kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()), url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()), token: Some("secret".to_owned()),
..SandboxChoice::default()
}) })
.expect("the choice saves"); .expect("the choice saves");
@@ -515,6 +728,38 @@ mod tests {
assert_eq!(reloaded.choice().token.as_deref(), Some("secret")); 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] #[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() { async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await; let server = MockServer::start().await;
@@ -556,16 +801,18 @@ mod tests {
let state = state(SandboxChoice { let state = state(SandboxChoice {
kind: SandboxKind::Http, kind: SandboxKind::Http,
url: Some(server.uri()), url: Some(server.uri()),
token: None, ..SandboxChoice::default()
}); });
let executor = state.executor(dir.path()); let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false); let cancelled = AtomicBool::new(false);
let mut sink = |_line: &str| {}; let mut sink = OutputOnly(|_line: &str| {});
let executed = executor let executed = executor
.run( .run(
"echo hi", RunRequest {
Path::new(REMOTE_WORKSPACE), command: "echo hi".to_owned(),
Duration::from_secs(5), cwd: Path::new(REMOTE_WORKSPACE).to_path_buf(),
timeout: Duration::from_secs(5),
},
&cancelled, &cancelled,
&mut sink, &mut sink,
) )
+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());
}
}
+12
View File
@@ -395,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)
} }
@@ -406,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)
} }
+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(
+1
View File
@@ -94,6 +94,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None, sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
+1
View File
@@ -60,6 +60,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None, sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
+562 -6
View File
@@ -11,7 +11,7 @@ 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};
@@ -67,6 +67,7 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
ingest_token: None, ingest_token: None,
transcript: None, transcript: None,
sandbox: None, sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
@@ -513,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
@@ -735,10 +955,10 @@ async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
.iter() .iter()
.find(|message| message.role == Role::User) .find(|message| message.role == Role::User)
.expect("the question is stashed"); .expect("the question is stashed");
assert_eq!(rhema_core::paste::spans(ask).len(), 1); assert_eq!(rhema_claw::paste::spans(ask).len(), 1);
assert_eq!(rhema_core::paste::spans(ask)[0].start, 12); assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_core::paste::spans(ask)[0].end, 38); assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2); 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
@@ -2431,6 +2651,132 @@ async fn the_sandbox_choice_is_listed_and_switchable() {
assert_eq!(cleared["url"], "https://box.example:7600"); 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,
@@ -2461,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")
@@ -2470,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.
@@ -2484,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
@@ -3485,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"))
@@ -3745,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);
}
+1
View File
@@ -67,6 +67,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None, sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
+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.
+25 -2
View File
@@ -48,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 tar 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
@@ -59,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
+1 -1
View File
@@ -67,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 tar 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.4.0 version: 0.4.1
appVersion: "0.4.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 = "0.4.0" 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 = "0.4.0" 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 = "0.4.0" 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"] }
+41 -13
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.
@@ -112,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
@@ -128,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
@@ -141,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
+162 -38
View File
@@ -22,7 +22,7 @@ import type {
StreamStatus, StreamStatus,
} from '~/composables/useClaw' } from '~/composables/useClaw'
import { composeChips, 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'
@@ -121,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.
@@ -131,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)
@@ -310,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 {
@@ -377,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()
@@ -523,7 +586,11 @@ async function saveSandbox(choice: SandboxSelection): Promise<void> {
try { try {
sandboxState.value = await claw.setSandbox(choice) sandboxState.value = await claw.setSandbox(choice)
pushNotice( pushNotice(
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine', choice.kind === 'http'
? 'sandbox: remote host'
: choice.kind === 'ssh'
? 'sandbox: ssh host'
: 'sandbox: this machine',
) )
apiError.value = null apiError.value = null
} catch (err) { } catch (err) {
@@ -598,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)
} }
@@ -625,18 +696,38 @@ function saveToken(): void {
// --- 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
@@ -644,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
@@ -654,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()
}, },
@@ -663,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. */
@@ -766,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"
+95 -13
View File
@@ -26,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
@@ -43,6 +45,27 @@ 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 {
@@ -428,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>
@@ -446,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>
@@ -455,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"
@@ -490,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>
@@ -519,6 +551,10 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
@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>
@@ -555,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
@@ -564,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"
> >
@@ -755,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 {
@@ -937,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)"
@@ -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 ῥ."
@@ -18,20 +18,39 @@ const kind = ref<SandboxKind>('local')
const url = ref('') const url = ref('')
const token = ref('') const token = ref('')
const clearToken = ref(false) const clearToken = ref(false)
const host = ref('')
const workspace = ref('')
const privateKey = ref('')
const clearPrivateKey = ref(false)
const dirty = computed(() => { const dirty = computed(() => {
const state = props.state const state = props.state
if (!state) return false if (!state) return false
if (kind.value !== state.kind) return true if (kind.value !== state.kind) return true
if (kind.value !== 'http') return false if (kind.value === 'http') {
const normalized = url.value.trim().replace(/\/+$/, '') const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value 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 urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const ready = computed(() => kind.value !== 'http' || urlValid.value) 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(() => const urlHint = computed(() =>
url.value.trim() && !urlValid.value url.value.trim() && !urlValid.value
@@ -39,6 +58,12 @@ const urlHint = computed(() =>
: 'The sandboxd base URL, for example https://box.example:7600.', : '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 { function sync(): void {
const state = props.state const state = props.state
if (!state) return if (!state) return
@@ -46,6 +71,10 @@ function sync(): void {
url.value = state.url ?? '' url.value = state.url ?? ''
token.value = '' token.value = ''
clearToken.value = false clearToken.value = false
host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? ''
privateKey.value = ''
clearPrivateKey.value = false
} }
watch( watch(
@@ -71,6 +100,15 @@ function save(): void {
choice.clear_token = true 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) emit('save', choice)
} }
@@ -78,7 +116,9 @@ function save(): void {
const workspacePath = computed(() => { const workspacePath = computed(() => {
const state = props.state const state = props.state
if (!state) return '' if (!state) return ''
return kind.value === 'http' ? state.remote_workspace : state.local_workspace if (kind.value === 'local') return state.local_workspace
if (kind.value === 'http') return state.remote_workspace
return state.workspace
}) })
</script> </script>
@@ -123,6 +163,74 @@ const workspacePath = computed(() => {
</span> </span>
</span> </span>
</label> </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>
<SettingCard v-if="kind === 'http'" title="Remote sandbox"> <SettingCard v-if="kind === 'http'" title="Remote sandbox">
@@ -167,7 +275,7 @@ const workspacePath = computed(() => {
</SettingRow> </SettingRow>
</SettingCard> </SettingCard>
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy"> <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. 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. Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout> </AppCallout>
@@ -256,4 +364,12 @@ const workspacePath = computed(() => {
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
} }
.key-input {
width: 100%;
min-width: 0;
resize: vertical;
font-size: 12px;
word-break: break-all;
}
</style> </style>
+82 -11
View File
@@ -95,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). */
@@ -192,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
@@ -204,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
@@ -231,9 +244,9 @@ export interface ActiveBackend {
active: { provider: string; model: string } active: { provider: string; model: string }
} }
/** Where the agent's `bash` runs: this host or a daemon speaking the /** Where the agent's `bash` runs: this host, a daemon speaking the
* sandbox protocol over HTTP. */ * sandbox protocol over HTTP, or an ssh login on a far box. */
export type SandboxKind = 'local' | 'http' export type SandboxKind = 'local' | 'http' | 'ssh'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides /** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */ * the wire; `token_set` says whether one is stored. */
@@ -241,6 +254,15 @@ export interface SandboxState {
kind: SandboxKind kind: SandboxKind
url: string | null url: string | null
token_set: boolean 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. */ /** Where `bash` starts under the current choice. */
workspace: string workspace: string
/** The daemon's chat workspace, whatever the choice. */ /** The daemon's chat workspace, whatever the choice. */
@@ -257,6 +279,14 @@ export interface SandboxSelection {
url?: string url?: string
token?: string token?: string
clear_token?: boolean 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. */
@@ -289,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 {
@@ -384,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 {
@@ -397,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
@@ -473,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>
} }
@@ -524,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
@@ -572,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.
@@ -580,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> {
@@ -847,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,
+29 -32
View File
@@ -409,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
} }
} }
} }
@@ -466,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