Compare commits

..
20 Commits
Author SHA1 Message Date
Kosmos b114049591 fix(forge): consume a decided account notification
android / release (pull_request) Skipped
ci / checks (pull_request) Successful in 1m6s
ci / test (pull_request) Successful in 40s
ci / docker (pull_request) Successful in 1m32s
ci / chart (pull_request) Successful in 5s
ci / web (pull_request) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
android / debug (pull_request) Successful in 2m19s
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:09:22 +00:00
kosmos c65f7fe962 fix(forge): read a GitHub notification id as a string or a number
ci / web (pull_request) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
android / debug (push) Successful in 2m34s
android / release (push) Successful in 2m4s
ci / checks (push) Successful in 1m4s
ci / web (push) Successful in 13s
ci / test (push) Successful in 1m5s
ci / chart (push) Successful in 5s
ci / docker (push) Successful in 1m28s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m33s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
ci / publish-edge-chart (push) Successful in 3s
android / release (pull_request) Skipped
ci / test (pull_request) Successful in 38s
ci / chart (pull_request) Successful in 5s
ci / checks (pull_request) Successful in 1m3s
ci / docker (pull_request) Successful in 1m28s
android / debug (pull_request) Successful in 2m25s
The notifications feed sends `id` as a JSON string (`"27210544329"`),
unlike every other row this adapter decodes, so `WireNotification`'s
`Option<i64>` refused one real row and failed the whole page. The account
watch has been stuck on 'error decoding response body' since the first
notification arrived (82 consecutive failures at the time of writing).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    malformed forge response: comment issue_url without a thread number:

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

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

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

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

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

No files matched your search

-1
View File
@@ -1,2 +1 @@
/target/
.rhema/
Generated
+133 -1533
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/*"]
[workspace.package]
version = "0.4.1"
version = "0.4.0"
edition = "2024"
rust-version = "1.89"
license = "MIT"
@@ -261,7 +261,6 @@ data class CommandResult(val ok: Boolean, val detail: String? = null)
@Serializable
data class AgentIdentity(
val name: String? = null,
val email: String? = null,
val mark: String? = null,
val initials: String? = null,
val tagline: String? = null,
+20 -24
View File
@@ -29,37 +29,33 @@ mock = ["rhema-core/mock"]
# shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.2"
rhema-prompt = "0.4.2"
rhema-host-agent = "0.4.2"
rhema-autonomous-agent = "0.4.2"
rhema-config = "0.4.2"
rhema-core = "0.4.2"
rhema-bash = "0.4.0"
rhema-prompt = "0.4.0"
rhema-host-agent = "0.4.0"
rhema-autonomous-agent = "0.4.0"
rhema-config = "0.4.0"
rhema-core = "0.4.0"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.4.2"
rhema-transcript = "0.4.0"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat
rhema-identity = "0.4.2"
rhema-rsd = "0.4.2"
# The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box.
# The choice carries an ssh private key as text, so a store-held
# credential has no file to stage; that is the seam the 0.4.2 line adds,
# and the family moves to it together.
rhema-sandbox = "0.4.2"
rhema-sandbox-http = "0.4.2"
rhema-sandbox-ssh = "0.4.2"
rhema-identity = "0.4.0"
rhema-rsd = "0.4.0"
# The sandbox seam: where `bash` runs, local process or a daemon speaking
# the wire protocol over HTTP
rhema-sandbox = "0.4.0"
rhema-sandbox-http = "0.4.0"
# The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain
rhema-memory = "0.4.2"
rhema-memory = "0.4.0"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.4.2"
rhema-provider-registry = "0.4.2"
rhema-provider = "0.4.0"
rhema-provider-registry = "0.4.0"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -83,20 +79,20 @@ rusqlite = { version = "0.40", features = ["bundled"] }
time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.23"
rhema-mcp = "0.4.2"
base64 = "0.22"
rhema-mcp = "0.4.0"
[dev-dependencies]
tempfile = "3"
# In-process HTTP mocks for the offline e2e: zero network
wiremock = "0.6"
# The HTTP client for the surface tests, SSE bodies included
reqwest = { version = "0.13", features = ["json", "stream"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
# Naming the SSE chunks' type in the surface tests
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.4.2", features = ["mock"] }
rhema-core = { version = "0.4.0", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+1 -2
View File
@@ -8,8 +8,7 @@ questions, spread across turns.
Write SOUL.md (your name, tone, purpose) and USER.md (who the user
is) with the bootstrap_save tool as facts arrive; incrementally is
fine. Set what you learn about your own presentation with the
identity_set tool as well — your name, a mark or initials, a tagline, an
email to commit as.
identity_set tool as well — your name, a mark or initials, a tagline.
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
hunting one down. Never invent facts the user did not give.
+24 -53
View File
@@ -70,11 +70,9 @@ token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: ssh # local (default), http, or ssh
host: me@box.example # the ssh destination: an alias or user@host
workspace: /srv/claw # ssh only: the workspace base, default /root
# http instead speaks the sandbox protocol (rhema-sandboxd):
# kind: http, url: https://box.example:7600, token: sandbox-secret
kind: http # local (default) or http
url: https://box.example:7600 # the sandboxd base URL
token: sandbox-secret # the daemon's shared secret, if it has one
poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty
@@ -105,15 +103,10 @@ conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. `kind: ssh` runs commands on a login the local `ssh`
config resolves (`host`, any alias or `user@host`), nothing installed
on the far end; `workspace` names the remote directory the claw's
workspaces live under, `/root` by default, one directory per claw
workspace under it. The settings screen writes the same choice to the
optional `token`. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
workspace root. Later edits stay there; the claw does not copy them
back.
`/workspace`. Later edits stay there; the claw does not copy them back.
The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer
@@ -146,9 +139,6 @@ 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}/history one page of older turns: ?before=<seq>&limit=<n>
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/bootstrap {"soul": bool, "user": bool}
POST /v1/ingest {"source","key","payload"} -> 202
@@ -160,7 +150,7 @@ GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?,"host"?,"workspace"?}, switch and persist
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
@@ -204,26 +194,14 @@ 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
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
exactly the gap. With no cursor the replay is the tail: the newest 400
events, cut back to the first turn boundary in them. The window widens
by doubling while it sits inside one turn, because a long agent turn
streams hundreds of deltas and a reload that opened mid-reply would
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
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
session paints its latest turn at once instead of replaying everything;
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;`
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
whenever the stream (re)opens, letting the replay rebuild it; the daemon
owns the conversation, so the client mirrors the stream rather than
@@ -358,26 +336,19 @@ same host serves both: the browser gets the web UI on `/`, the daemon
answers `/v1` and `/healthz`; one address for the browser and the
phone app, no CORS anywhere.
The image is the daemon plus what the agent's shell needs: `bash` and
`git` (the shell is load-bearing, the agent clones in its workspaces),
`curl` for a turn that fetches a URL, and `gob` for a command that
outlives the turn. The agent starts a build or a dev server with `gob
add` and reads its logs and ports on a later one. The chart runs
exactly one replica, the claw is single-node by design: one SQLite
store, one dispatcher. Single-node is what makes restarts instant: at
boot the daemon releases every lease the previous process left —
outright, not at the dead lease's TTL — so a turn an update cut
mid-flight answers its next message instead of stalling behind a ghost
(the committed tool call revives at the top of that next dispatch). The
cut turn is released as superseded on the way, so a thread it never
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 image is the daemon plus `bash` and `git` (the agent's shell is
load-bearing); the chart runs exactly one replica, the claw is
single-node by design: one SQLite store, one dispatcher. Single-node
is what makes restarts instant: at boot the daemon releases every
lease the previous process left — outright, not at the dead lease's
TTL — so a turn an update cut mid-flight answers its next message
instead of stalling behind a ghost (the committed tool call revives
at the top of that next dispatch). 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`
proxies to a local claw, `npm run build` emits the static bundle an
+4 -33
View File
@@ -1,15 +1,8 @@
You are the resident agent on this machine. This session's key is {{ session }}.
Your shell runs in the workspace at {{ workspace }}.
Keep replies concrete. Do the work with tools instead of narrating it.
{% if surface == 'forge' %}
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 %}
You answer chat here. Your shell runs in the workspace at {{ workspace }}.
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
it, is the reply the user sees.
## Soul
@@ -43,27 +36,6 @@ what it is for. The arguments are the JSON schema a call must satisfy.
{{ vision }}
{% 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
You keep persistent memory across sessions. memory_save stores what is
@@ -71,7 +43,6 @@ worth remembering: decisions, conventions, corrections, pointers.
memory_search recalls it; search before asking the user for something
they have likely said before. memory_forget removes a record on
request. Never save secrets into memory.
{% endif %}
{% if onboarding %}
{{ onboarding }}
-175
View File
@@ -1,175 +0,0 @@
//! 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"));
}
}
+10 -8
View File
@@ -29,8 +29,7 @@ use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::{ToolCall, ToolContext, ToolResolver, ToolResult, ToolSpec};
use rhema_identity::{Account, AccountDraft, IdentityStore, Secret, SecretKind};
use serde::Deserialize;
@@ -284,7 +283,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// The identity tool set over the account store and the watch table —
/// specs from the embedded manifests, operations compiled here.
pub fn registry(accounts: Arc<dyn IdentityStore>, watches: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(accounts, watches));
assert!(
skipped.is_empty(),
"the identity tool manifests must all load: {skipped:?}"
@@ -582,7 +582,7 @@ impl ToolResolver for IdentityExec {
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::ToolOp;
use rhema_autonomous_agent::ToolOp;
fn parts() -> (Arc<dyn IdentityStore>, Arc<ClawStore>) {
(
@@ -598,13 +598,15 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin_and_serves_the_registry() {
let (accounts, watches) = parts();
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(accounts, watches),
);
assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 3);
let (accounts, watches) = parts();
let resolver =
registry(accounts, watches).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = registry(accounts, watches)
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("identity_list"),
rhema_core::ReplaySafety::Safe
+6 -5
View File
@@ -17,8 +17,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -310,8 +309,10 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into(), hub, key));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, workspace.into(), hub, key),
);
assert!(
skipped.is_empty(),
"the attach_file tool manifest must load: {skipped:?}"
@@ -326,7 +327,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+10 -148
View File
@@ -26,8 +26,7 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json};
@@ -198,32 +197,15 @@ fn section(header: &str, content: Option<&str>, stub: &str) -> String {
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
/// toolkit's Jinja renderer: `{{ workspace }}` and the three file
/// sections from the live store, `tools` from the dispatch's own
/// resolver specs, `{{ session }}` — the dispatching key, the address
/// the model schedules its own wakes to — and `onboarding`, the offer
/// the template's `{% if %}` shows only while a file is unwritten, and
/// only on a chat surface: a forge dispatch is nobody's first
/// conversation. `mcp` renders the wired servers' section, empty on a
/// 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")]
/// the template's `{% if %}` shows only while a file is unwritten.
/// 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.
pub fn render_system(
template: &str,
session: &str,
@@ -231,18 +213,15 @@ pub fn render_system(
bootstrap: &Bootstrap,
tools: &[ToolSpec],
vision: Option<&str>,
mcp: &[rhema_config::mcp::McpServerLine],
surface: Surface,
) -> Result<String, BootstrapError> {
let soul = bootstrap.load(BootstrapKind::Soul)?;
let user = bootstrap.load(BootstrapKind::User)?;
let environment = bootstrap.load(BootstrapKind::Environment)?;
let onboarding = if surface == Surface::Chat && (soul.is_none() || user.is_none()) {
let onboarding = if soul.is_none() || user.is_none() {
ONBOARDING_MD
} else {
""
};
let memory = tools.iter().any(|spec| spec.name == "memory_save");
let context = json!({
"session": session,
"workspace": workspace.display().to_string(),
@@ -252,12 +231,6 @@ pub fn render_system(
"onboarding": onboarding,
"tools": tools,
"vision": vision,
"mcp": mcp,
"memory": memory,
"surface": match surface {
Surface::Chat => "chat",
Surface::Forge => "forge",
},
});
render_template(template, &context).map_err(|err| {
let line = err
@@ -313,7 +286,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// interactive resolver chain composes — its spec from the embedded
/// manifest, the operation compiled here.
pub fn registry(bootstrap: Arc<Bootstrap>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(bootstrap));
assert!(
skipped.is_empty(),
"the bootstrap tool manifest must load: {skipped:?}"
@@ -444,7 +418,7 @@ mod tests {
let tools = registry(Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}))
.resolver_for(&crate::toolkit::Allowlist::permissive())
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive())
.specs();
let prompt = render_system(
DEFAULT_SYSTEM_MD,
@@ -453,8 +427,6 @@ mod tests {
&bootstrap,
&tools,
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(prompt.contains("## SOUL"), "{prompt}");
@@ -467,110 +439,6 @@ mod tests {
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]
fn the_full_house_renders_each_file_and_drops_the_onboarding_section() {
let (_dir, bootstrap) = store();
@@ -588,8 +456,6 @@ mod tests {
&bootstrap,
&[],
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(
@@ -618,8 +484,6 @@ mod tests {
&bootstrap,
&[],
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(prompt.contains(content), "{prompt}");
@@ -652,8 +516,6 @@ mod tests {
&bootstrap,
&tools,
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(prompt.contains("- my_tool | {"), "{prompt}");
@@ -666,7 +528,7 @@ mod tests {
#[tokio::test]
async fn the_tool_writes_through_the_store_and_answers_one_line() {
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
use rhema_core::{ToolCall, ToolContext};
let (_dir, bootstrap) = store();
+4 -92
View File
@@ -178,33 +178,10 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still
/// ingest.
pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, a
/// `rhema-sandboxd` over HTTP, or an ssh login on a far box (`kind:
/// ssh`, a `host` destination, and optionally the `private_key`
/// text itself, not a path, the credential stays in this file or
/// the store that holds it). The settings store owns the live
/// Where the agent's `bash` runs: this host when unset, or a
/// `rhema-sandboxd` over HTTP. The settings store owns the live
/// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>,
/// 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 {
@@ -233,7 +210,6 @@ impl Default for ClawConfig {
ingest_token: None,
transcript: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -468,9 +444,6 @@ sandbox:
kind: http
url: https://box.example:7600
token: sandbox-secret
git:
name: Bot
email: bot@example.net
";
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
assert_eq!(config.poll_interval_secs, 30);
@@ -491,18 +464,6 @@ git:
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
let git = config.git.expect("the git identity parses");
assert_eq!(git.name.as_deref(), Some("Bot"));
assert_eq!(git.email.as_deref(), Some("bot@example.net"));
let config: ClawConfig = serde_yaml::from_str(
"sandbox:\n kind: ssh\n host: me@box.example\n workspace: /srv/claw\n",
)
.expect("the ssh sandbox parses");
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Ssh);
assert_eq!(sandbox.host.as_deref(), Some("me@box.example"));
assert_eq!(sandbox.workspace.as_deref(), Some("/srv/claw"));
}
#[test]
@@ -511,7 +472,7 @@ git:
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
..crate::sandbox::SandboxChoice::default()
token: None,
}),
..ClawConfig::default()
};
@@ -523,62 +484,13 @@ git:
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
..crate::sandbox::SandboxChoice::default()
token: None,
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
fn an_ssh_sandbox_needs_a_host_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"an ssh sandbox without a host is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
host: Some("me@box.example".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a bare login is all ssh needs");
}
#[test]
fn the_git_section_rejects_a_typo_and_carries_partial_identity() {
let err = serde_yaml::from_str::<ClawConfig>(
"git:
nmae: Bot
",
)
.expect_err("a typo inside the section must not read as its default");
assert!(
err.to_string().contains("nmae"),
"the error names the key: {err}"
);
// One field alone is legal: the other falls through to the
// identity store, then defaults.
let config: ClawConfig = serde_yaml::from_str(
"git:
email: bot@example.net
",
)
.expect("parses");
let git = config.git.expect("the section parses");
assert_eq!(git.email.as_deref(), Some("bot@example.net"));
assert_eq!(git.name, None);
}
#[test]
fn an_unknown_key_is_rejected_and_named() {
let err = serde_yaml::from_str::<ClawConfig>("listne: 127.0.0.1:7799\n")
+6 -5
View File
@@ -21,8 +21,7 @@ use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -510,8 +509,10 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(consents, bridge, hub, key));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(consents, bridge, hub, key),
);
assert!(
skipped.is_empty(),
"the ask_secret tool manifest must load: {skipped:?}"
@@ -526,7 +527,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+34 -315
View File
@@ -22,7 +22,6 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use rhema_autonomous_agent::{Driver, Source, SourceError};
@@ -127,83 +126,6 @@ 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 task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface.
@@ -220,10 +142,6 @@ pub struct Daemon {
forge_driver: Arc<Driver>,
interactive_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,
listen: String,
http: ClawState,
@@ -236,8 +154,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// with `--once` zeroing the debounce.
/// the forge dispatcher's timing — the resident loop uses the
/// defaults, `--once` zeroes the debounce.
pub fn build(
config: &ClawConfig,
backends: Arc<BackendRegistry>,
@@ -360,45 +278,26 @@ impl Daemon {
.map(|url| format!(" ({url})"))
.unwrap_or_default(),
);
// The bootstrap store, before both handlers: the chat renders
// its files per dispatch, and so does the forge one now — the
// persona is shared, the workspaces are not. The environment
// report lands in the store's directory at boot, below.
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
// The pause gate: the keys the drivers hold, loaded from the
// settings table, shared with the HTTP surface's pause route.
let pause = Arc::new(crate::pause::PauseSet::load(settings.clone())?);
// The abort registry: the per-key cut the handlers listen on,
// shared with the HTTP surface's abort route.
let abort = Arc::new(crate::abort::AbortRegistry::new());
let forge_handler = ClawHandler::new(
backends.clone(),
workspace_root,
watches.clone(),
accounts.clone(),
bootstrap.clone(),
config.transcript_enabled(),
tool_env.clone(),
)
.with_sandbox(sandbox.clone())
.with_abort(abort.clone());
.with_sandbox(sandbox.clone());
// Three drivers over one store admit from the same table, so
// each owns its slice of the key space: a forge pass must never
// pick up a resident or job event (it would fail it, and
// consume it), and the others likewise. Paused keys belong to
// no driver: every predicate declines them, pass after pass,
// until resume lifts the hold.
// consume it), and the others likewise.
let forge_driver = Arc::new(
Driver::new(forge_dispatcher.clone(), Arc::new(forge_handler))
.with_holder("rhema-claw")
.owning({
let pause = pause.clone();
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())
})
}),
.owning(Arc::new(|key: &ResourceKey| {
!crate::interactive::is_resident_key(key.as_str())
&& !crate::jobs::is_job_key(key.as_str())
})),
);
// The consent table and its wake bridge: the `ask_secret` tool
@@ -419,6 +318,7 @@ impl Daemon {
// `phone` tool queues behind a consent.
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
// The identity store shares the settings table and keeps its
// images beside the database.
let identity = Arc::new(crate::identity::IdentityStore::new(
@@ -488,7 +388,6 @@ impl Daemon {
config.transcript_enabled(),
)
.with_steer(steer.clone())
.with_abort(abort.clone())
.with_sandbox(sandbox.clone());
let interactive_driver = Arc::new(
Driver::new(
@@ -496,13 +395,9 @@ impl Daemon {
Arc::new(interactive_handler),
)
.with_holder("rhema-claw-interactive")
.owning({
let pause = pause.clone();
Arc::new(move |key: &ResourceKey| {
crate::interactive::is_resident_key(key.as_str())
&& !pause.is_paused(key.as_str())
})
}),
.owning(Arc::new(|key: &ResourceKey| {
crate::interactive::is_resident_key(key.as_str())
})),
);
// The coding jobs: one handler, one driver, one source. The
// final text of a job's turn notifies the user's device, so the
@@ -514,17 +409,13 @@ impl Daemon {
config.max_turn_steps,
config.transcript_enabled(),
)
.with_sandbox(sandbox.clone())
.with_abort(abort.clone());
.with_sandbox(sandbox.clone());
let jobs_driver = Arc::new(
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
.with_holder("rhema-claw-jobs")
.owning({
let pause = pause.clone();
Arc::new(move |key: &ResourceKey| {
crate::jobs::is_job_key(key.as_str()) && !pause.is_paused(key.as_str())
})
}),
.owning(Arc::new(|key: &ResourceKey| {
crate::jobs::is_job_key(key.as_str())
})),
);
crate::interactive::register_user(&interactive_dispatcher);
@@ -539,9 +430,6 @@ impl Daemon {
bootstrap,
hub,
steer,
pause,
abort,
jobs,
backends.clone(),
settings.clone(),
identity,
@@ -565,8 +453,6 @@ impl Daemon {
forge_driver,
interactive_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
// forge API; one second is the floor.
poll_interval: Duration::from_secs(config.poll_interval_secs.max(1)),
@@ -606,52 +492,25 @@ impl Daemon {
// is failed interrupted before anything re-runs, and a
// still-queued row is re-armed with a fresh dedup id.
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.jobs_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(())
}
/// One pass, awaited to the end: every source detects (due tasks
/// first — a reminder is the user-facing clock), the forge driver
/// runs every key the debounce released, and the interactive driver
/// drains as a backstop. The shape a `--once` run and the tests
/// 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.
/// One pass: every source detects (due tasks first — a reminder is
/// the user-facing clock), the forge driver runs every key the
/// debounce released, and the interactive driver drains as a
/// backstop — a message delivered live into a running turn waits at
/// the key for a pass like this one.
pub async fn tick(&self) -> Result<TickReport, ClawError> {
let detected = self.detect().await?;
// The tick only detects — every timer here drives
// 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
// thing someone just asked for.
if let Err(err) = self.jobs_driver.run_once().await {
@@ -671,50 +530,6 @@ impl Daemon {
"[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 {
Ok(runs) if !runs.is_empty() => {
eprintln!("[claw] interactive: {} queued run(s) drained", runs.len());
@@ -722,13 +537,13 @@ impl Daemon {
Ok(_) => {}
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
/// talked to), then detect, hand the long lanes to their own tasks,
/// sleep, until ctrl-c. A failed pass is logged, not fatal — a forge
/// outage or a dead backend must not end a daemon whose next pass may
/// simply succeed.
/// talked to), then detect, run, sleep, until ctrl-c. A failed pass
/// is logged, not fatal — a forge outage or a dead backend must not
/// end a daemon whose next pass may simply succeed.
pub async fn run(&self) -> Result<(), ClawError> {
self.bootstrap().await?;
let listener = tokio::net::TcpListener::bind(&self.listen).await?;
@@ -741,7 +556,7 @@ impl Daemon {
});
eprintln!("[claw] http listening on {addr}");
loop {
if let Err(err) = self.resident_tick().await {
if let Err(err) = self.tick().await {
eprintln!("[claw] warning: pass failed: {err}");
}
tokio::select! {
@@ -765,7 +580,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig {
debounce_window_millis: 0,
..forge_dispatch()
..DispatcherConfig::default()
};
let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?;
@@ -776,102 +591,6 @@ pub async fn run_once(
mod tests {
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]
fn the_interactive_dispatcher_dispatches_now_and_leases_long() {
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`
/// command, else a stand-in — the file is not portable and the command
/// is not guaranteed, so absence is a report line.
pub(crate) fn hostname() -> String {
fn hostname() -> String {
if let Ok(raw) = std::fs::read_to_string("/etc/hostname") {
let name = bound(&raw);
if !name.is_empty() {
+4 -5
View File
@@ -32,18 +32,17 @@
use std::path::PathBuf;
use std::sync::Arc;
use rhema_autonomous_agent::Source;
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_autonomous_agent::{Allowlist, Source, ToolRegistry};
use rhema_core::ToolResolver;
use rhema_forge_integration::ForgeKind;
use rhema_rsd::{Dispatcher, ResourceKey, SystemClock};
use crate::consents::WaitBridge;
use crate::daemon::ClawError;
use crate::forge::ForgeSource;
use crate::hub::EventHub;
use crate::toolkit::{Allowlist, ToolRegistry};
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_forge_integration::ForgeKind;
/// The store handles the standard set is assembled over. One struct,
/// so a new extension is a field plus a constructor line, not another
+22 -114
View File
@@ -219,6 +219,8 @@ pub struct ForgeSource {
/// The device-notification queue a [`Triage::Surface`] lands in.
notifications: Arc<crate::notifications::NotificationStore>,
clients: Mutex<HashMap<ClientKey, Arc<dyn Forge>>>,
/// One notifications cursor per account id.
account_cursors: Mutex<HashMap<String, rhema_forge_integration::Timestamp>>,
}
impl ForgeSource {
@@ -243,6 +245,7 @@ impl ForgeSource {
accounts,
notifications,
clients: Mutex::new(HashMap::new()),
account_cursors: Mutex::new(HashMap::new()),
}
}
@@ -498,18 +501,12 @@ impl ForgeSource {
};
let client = record_client(kind, watch.host.as_deref(), &credential);
// The cursor this poll asks from: the durable one when the watch
// has one, absent on its first pass — an unread feed is news. An
// unreadable row reads as absent, like a repo watch's: a
// corrupted cursor must not fire a backlog. The map that used to
// hold it was per-process, so every restart asked from nothing
// 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 since = self
.account_cursors
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&watch.account_id)
.cloned();
let page = client
.notifications(since.as_ref())
.await
@@ -570,11 +567,11 @@ impl ForgeSource {
}
// The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning
// it, and the durable cursor is what stops the poll asking
// for it again. Deciding without consuming is a loop: a row
// the forge still considers unread comes back every pass —
// re-decided and re-dispatched as a fresh turn for a thread
// that already has one — until the cursor passes it.
// it. Deciding without consuming is a loop: the poll's cursor
// never passes a row the forge still considers unread, so
// every pass re-decides it and re-dispatches a turn for a
// thread that already has one, and a restart (the cursor is
// in memory) replays the whole unread feed.
//
// Best-effort: an unread row costs a repeat, never a lost
// event, so a failed call is logged and the poll carries on.
@@ -585,15 +582,11 @@ 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 {
self.store
.set_cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id, cursor.raw())
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
self.account_cursors
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(watch.account_id.clone(), cursor);
}
Ok(fed)
}
@@ -714,9 +707,10 @@ mod tests {
/// The account poll consumes what it decides. The feed is
/// at-least-once — the cursor never passes a row the forge still
/// considers unread, so a row that is triaged but not marked read
/// comes back with the same dedup id on the next pass, and every
/// pass dispatches a fresh turn for a thread that already has one.
/// considers unread, and a restart asks for the whole unread feed
/// again — so a row that is triaged but not marked read comes back
/// with the same dedup id on the next pass, and every pass dispatches
/// a fresh turn for a thread that already has one.
#[tokio::test]
async fn a_triaged_account_notification_is_marked_read() {
let server = MockServer::start().await;
@@ -770,92 +764,6 @@ mod tests {
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.
fn test_parts(
store: Arc<ClawStore>,
-472
View File
@@ -1,472 +0,0 @@
//! 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")
);
}
}
+39 -263
View File
@@ -23,7 +23,6 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
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::watch_store::ClawStore;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
@@ -50,25 +49,14 @@ use crate::sandbox::SandboxState;
/// [`Role`] is the seam it hangs on, a reviewer dispatch deserving a
/// narrower policy than an implementer's — and a policy that refuses the
/// shell refuses the run (see [`ClawHandler::dispatch`]).
fn allowlist() -> crate::toolkit::Allowlist {
crate::toolkit::Allowlist::permissive()
fn allowlist() -> rhema_autonomous_agent::Allowlist {
rhema_autonomous_agent::Allowlist::permissive()
}
/// The coding agent over one watch: a provider, a model, a workspace
/// root, and the watch table the dispatch keys resolve through — live,
/// 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 {
/// 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.
backends: Arc<BackendRegistry>,
/// Whether the sessions run the bounded request view (the config's
@@ -87,13 +75,6 @@ pub struct ClawHandler {
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per dispatch.
sandbox: Option<Arc<SandboxState>>,
/// The abort registry the sessions' abort route signals: a live
/// turn cut at its await stashes what it committed and ends the
/// dispatch as superseded, its comment never posted (see
/// [`crate::abort`]). Private by default — a handler nobody shared
/// a registry with never receives a signal — and shared through
/// [`ClawHandler::with_abort`].
abort: Arc<crate::abort::AbortRegistry>,
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
}
@@ -105,7 +86,6 @@ impl ClawHandler {
workspace_root: impl Into<PathBuf>,
watches: Arc<ClawStore>,
accounts: Arc<dyn IdentityStore>,
bootstrap: Arc<Bootstrap>,
transcript: bool,
tool_env: std::collections::BTreeMap<String, String>,
) -> Self {
@@ -115,10 +95,8 @@ impl ClawHandler {
workspace_root: workspace_root.into(),
watches,
accounts,
bootstrap,
tool_env,
sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
clients: Mutex::new(HashMap::new()),
}
}
@@ -130,14 +108,6 @@ impl ClawHandler {
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:
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
/// table at dispatch time — the table is the source of truth, not a
@@ -324,28 +294,10 @@ impl ClawHandler {
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
let mut sink = TurnSink;
// The abort listener rides the turn: a signal drops the future
// at its current await — a streaming request, or a running
// shell command, whose child dies with the drop. What the turn
// 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);
}
};
let output = agent
.turn(prompt, &mut sink)
.await
.map_err(|err| format!("turn for {key} failed: {err}"))?;
// Stash before posting: the turn's work survives a failed comment.
ctx.session.core.driver_state = serde_json::to_value(agent.session())
@@ -392,7 +344,7 @@ impl ClawHandler {
key: &str,
) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current();
let config = self.agent_config(provider, &model, workspace, key)?;
let config = self.agent_config(provider, &model, workspace);
let agent = match &ctx.session.core.driver_state {
// A never-dispatched key carries no stash: start clean.
serde_json::Value::Null => HostAgent::new(config),
@@ -405,20 +357,17 @@ impl ClawHandler {
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
}
/// The config one dispatch's agent runs on: the resident's own
/// prompt — the bootstrap template rendered per dispatch over the
/// thread's workspace, SOUL.md and USER.md live — with the bounded
/// request view when the config has it on and a remote shell when
/// the sandbox choice says so. A forge thread answers for as long
/// as the thread lives; without the view its history would ride
/// whole on every step.
/// The config one dispatch's agent runs on: the default coding
/// agent's, with the bounded request view when the config has it on
/// and a remote shell when the sandbox choice says so.
/// A forge thread answers for as long as the thread lives; without
/// the view its history would ride whole on every step.
fn agent_config(
&self,
provider: Arc<dyn rhema_core::ModelProvider>,
model: &str,
workspace: &Path,
key: &str,
) -> Result<HostAgentConfig, String> {
) -> HostAgentConfig {
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(workspace),
None => workspace.to_path_buf(),
@@ -430,47 +379,19 @@ impl ClawHandler {
.transcript
.then(rhema_transcript::TranscriptSettings::default);
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 {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display.clone(),
display,
sandbox.executor(workspace.to_path_buf()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
vision = config.vision.clone();
mcp = config.mcp_servers.clone();
}
}
let mut specs = ShellTools::builtin_specs();
if config.transcript.is_some() {
specs.push(rhema_transcript::Zoom::spec());
}
config.system = Some(
crate::bootstrap::render_system(
DEFAULT_SYSTEM_MD,
key,
&display,
&self.bootstrap,
&specs,
vision.as_deref(),
&mcp,
Surface::Forge,
)
.map_err(|err| format!("cannot render the forge system prompt for {key}: {err}"))?,
);
Ok(config)
config
}
/// The per-thread workspace: one directory under the root, created on
@@ -705,31 +626,30 @@ fn dominant_role(news: &[InboxNews]) -> Option<Role> {
}
}
/// The task framing a dispatched role opens the prompt with. Who is
/// 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
/// The persona framing a dispatched role opens the prompt with. The key
/// stays the thread, so a role change across dispatches is the session's
/// continuity, not a new conversation.
fn task_text(role: Role) -> &'static str {
fn persona_text(role: Role) -> &'static str {
match role {
Role::Reviewer => {
"This dispatch is a review request. Check the change out in the \
workspace when you can, read the diff, and judge it: correctness, tests, \
edge cases, fit with the surrounding code. Make the reply the review — \
findings first, ordered by severity, concrete and actionable; if there is \
nothing to fix, say so plainly and say what you checked."
"You are acting as this pull request's reviewer. Check the change \
out in the workspace when you can, read the diff, and judge it: correctness, \
tests, edge cases, fit with the surrounding code. Your final reply is the \
review — findings first, ordered by severity, concrete and actionable; if \
there is nothing to fix, say so plainly and say what you checked."
}
Role::Implementer => {
"This dispatch asks for work. Address the review feedback or the \
assigned issue by changing the code in the workspace — build and test what \
you change. Make the reply a short report of what you changed and why, or, \
when the whole change does not fit one turn, what landed now and the \
concrete plan for the rest."
"You are acting as this thread's implementer. Do the work the new \
activity asks for: address the review feedback or the assigned issue by \
changing the code in the workspace — build and test what you change. Your \
final reply is a short report of what you changed and why, or, when the \
whole change does not fit one turn, what landed now and the concrete plan \
for the rest."
}
}
}
/// The agent's prompt for one dispatch: the task framing (when the
/// The agent's prompt for one dispatch: the persona framing (when the
/// triage dispatched a role), the thread's standing state, the new news,
/// and the posting contract. The final assistant message is the comment
/// — everything else is orientation for the investigation.
@@ -742,7 +662,7 @@ fn build_prompt(
) -> String {
let mut prompt = String::new();
if let Some(role) = role {
prompt.push_str(task_text(role));
prompt.push_str(persona_text(role));
prompt.push_str("\n\n");
}
prompt.push_str(&format!(
@@ -1164,12 +1084,8 @@ mod tests {
Some(Role::Reviewer),
);
assert!(
prompt.contains("This dispatch is a review request"),
"task: {prompt}"
);
assert!(
!prompt.contains("You are acting as"),
"who answers is the system prompt's to say, not the task text's: {prompt}"
prompt.contains("acting as this pull request's reviewer"),
"persona: {prompt}"
);
assert!(
prompt.contains("notification (review_requested) on pull request #142"),
@@ -1201,14 +1117,6 @@ mod tests {
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]
fn a_key_resolves_to_its_watch_entry_live_from_the_table() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
@@ -1225,13 +1133,11 @@ mod tests {
)
.expect("constructs"),
);
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
true,
std::collections::BTreeMap::new(),
);
@@ -1292,13 +1198,11 @@ mod tests {
)
.expect("constructs"),
);
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
accounts,
bootstrap,
true,
std::collections::BTreeMap::new(),
);
@@ -1353,13 +1257,11 @@ mod tests {
);
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0;
let (_dir, bootstrap) = bootstrap();
let on = ClawHandler::new(
registry.clone(),
"/tmp/w",
watches.clone(),
accounts.clone(),
bootstrap.clone(),
true,
std::collections::BTreeMap::new(),
);
@@ -1368,144 +1270,18 @@ mod tests {
"/tmp/w",
watches,
accounts,
bootstrap,
false,
std::collections::BTreeMap::new(),
);
assert!(
on.agent_config(
provider.clone(),
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7"
)
.expect("renders")
.transcript
.is_some()
on.agent_config(provider.clone(), "m", Path::new("/tmp/w"))
.transcript
.is_some()
);
assert!(
off.agent_config(
provider,
"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}"
off.agent_config(provider, "m", Path::new("/tmp/w"))
.transcript
.is_none()
);
}
+39 -328
View File
@@ -47,7 +47,7 @@ use rhema_claw_tools_contract::CONTRACT_HEADER;
use rhema_claw_tools_contract::CONTRACT_VERSION;
use rhema_core::ImageMediaType;
use rhema_rsd::{
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, Outcome, ResourceKey,
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, ResourceKey,
SqliteStore, Store,
};
use serde::{Deserialize, Deserializer};
@@ -55,13 +55,11 @@ use serde_json::{Value, json};
use tokio::sync::broadcast::error::RecvError;
use tokio_stream::wrappers::ReceiverStream;
use crate::abort::AbortRegistry;
use crate::backends::BackendRegistry;
use crate::bootstrap::Bootstrap;
use crate::hub::{EventHub, TurnEvent};
use crate::interactive::WireImage;
use crate::notifications::NotificationStore;
use crate::pause::PauseSet;
use crate::steer::SteerRegistry;
use crate::task_store::TaskStore;
use crate::watch_store::{ClawStore, validate_watch};
@@ -108,17 +106,6 @@ pub struct ClawState {
/// a chat message into a key whose turn is live cuts that turn
/// short (see [`crate::steer`]).
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>,
settings: Arc<crate::settings::SettingsStore>,
identity: Arc<crate::identity::IdentityStore>,
@@ -175,9 +162,6 @@ impl ClawState {
bootstrap: Arc<Bootstrap>,
hub: Arc<EventHub>,
steer: Arc<SteerRegistry>,
pause: Arc<PauseSet>,
abort: Arc<AbortRegistry>,
jobs: Arc<crate::job_store::CodingJobStore>,
backends: Arc<BackendRegistry>,
settings: Arc<crate::settings::SettingsStore>,
identity: Arc<crate::identity::IdentityStore>,
@@ -202,9 +186,6 @@ impl ClawState {
bootstrap,
hub,
steer,
pause,
abort,
jobs,
backends,
settings,
identity,
@@ -222,8 +203,7 @@ impl ClawState {
}
/// Every dispatch key with a record — interactive and forge alike,
/// both dispatchers share one store — with its status and whether
/// the pause gate holds it.
/// both dispatchers share one store — with its status.
pub fn sessions(&self) -> Result<Vec<Value>, DispatchError> {
let mut sessions = Vec::new();
for key in self.store.keys()? {
@@ -234,7 +214,6 @@ impl ClawState {
"revision": status.revision,
"inbox_depth": status.inbox_depth,
"last_outcome": status.last_outcome,
"paused": self.pause.is_paused(status.key.as_str()),
}));
}
Ok(sessions)
@@ -255,12 +234,6 @@ impl ClawState {
// 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.
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,
// where a record already gone left the transcript behind. Deleting
// that transcript is the repair: a retried DELETE finishes a half-done
@@ -290,17 +263,6 @@ impl ClawState {
&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 backend registry: the provider list and the active pair.
pub fn backends(&self) -> &BackendRegistry {
@@ -345,9 +307,6 @@ pub fn router(state: ClawState) -> Router {
let v1 = Router::new()
.route("/sessions", get(sessions).post(sessions_create))
.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(
"/sessions/{key}/messages",
post(messages).layer(axum::extract::DefaultBodyLimit::max(MAX_MESSAGE_BODY_BYTES)),
@@ -674,201 +633,6 @@ 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
/// UI badges first-run setup from it while the onboarding offer is
/// still open.
@@ -1095,14 +859,19 @@ async fn events(
let key = ResourceKey::from(key);
let (replay, mut receiver) = match query.since {
Some(cursor) => state.hub.replay_after(&key, cursor, 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),
None => state.hub.replay_tail(&key, TAIL_WINDOW),
};
let stale = replay.stale;
let history = replay.events;
// A tail window can open mid-turn (the oldest events in it belong
// 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
// client's disconnect closes the body, which fails the send, which
// ends the pump. The stream never ends on its own — a chat UI
@@ -1250,6 +1019,21 @@ 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
/// oldest event the client holds; absent reads from the newest), and
/// `limit` is the most events it may hold before the page is widened
@@ -1267,30 +1051,24 @@ struct HistoryQuery {
/// through a session's history. The page starts on a turn boundary and
/// ends exactly at `before`, so pages stack without gaps or overlaps.
/// The response's `more` says whether anything precedes it: `false`
/// 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.
/// means the client has reached the session's first event.
async fn session_history(
State(state): State<ClawState>,
Path(key): Path<String>,
Query(query): Query<HistoryQuery>,
) -> 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 limit = query
.limit
.unwrap_or(HISTORY_PAGE)
.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);
// Whether anything sits below the page: a lookup, not a read.
let more = match page.first().map(|(seq, _)| *seq) {
@@ -1301,48 +1079,7 @@ async fn session_history(
.into_iter()
.map(|(seq, event)| json!({"seq": seq, "event": event}))
.collect();
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()
Json(json!({"events": events, "more": more})).into_response()
}
async fn watches_list(State(state): State<ClawState>) -> Result<Json<Value>, (StatusCode, String)> {
@@ -2279,12 +2016,6 @@ fn sandbox_json(state: &ClawState) -> Value {
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"private_key_set": choice
.private_key
.as_deref()
.is_some_and(|key| !key.is_empty()),
"host": choice.host,
"ssh_workspace": choice.workspace,
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
@@ -2292,9 +2023,8 @@ fn sandbox_json(state: &ClawState) -> Value {
}
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` and `private_key` are write-only;
/// `clear_token` and `clear_private_key` drop the stored ones. The
/// choice applies on the next turn, no restart.
/// persist the choice. `token` is write-only; `clear_token` drops the
/// stored one. The choice applies on the next turn, no restart.
async fn sandbox_put(
State(state): State<ClawState>,
Json(body): Json<Value>,
@@ -2314,15 +2044,6 @@ async fn sandbox_put(
.map(str::to_owned)
.or_else(|| current.token.clone())
};
let clear_private_key = body["clear_private_key"].as_bool().unwrap_or(false);
let private_key = if clear_private_key {
None
} else {
body["private_key"]
.as_str()
.map(str::to_owned)
.or_else(|| current.private_key.clone())
};
let choice = crate::sandbox::SandboxChoice {
kind,
url: body["url"]
@@ -2330,15 +2051,6 @@ async fn sandbox_put(
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
host: body["host"]
.as_str()
.map(str::to_owned)
.or_else(|| current.host.clone()),
workspace: body["workspace"]
.as_str()
.map(str::to_owned)
.or_else(|| current.workspace.clone()),
private_key,
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
@@ -2585,7 +2297,6 @@ async fn agent_put(
};
let texts = crate::identity::IdentityTexts {
name: field(body["name"].as_str(), &current.name),
email: field(body["email"].as_str(), &current.email),
mark: field(body["mark"].as_str(), &current.mark),
initials: field(body["initials"].as_str(), &current.initials),
tagline: field(body["tagline"].as_str(), &current.tagline),
+2 -110
View File
@@ -28,11 +28,11 @@
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};
use rhema_core::paste::PasteSpan;
use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
use crate::paste::PasteSpan;
use crate::turn_store::{TurnStore, TurnStoreError};
/// How many events a subscriber may trail by before the oldest drop.
@@ -129,8 +129,7 @@ pub enum TurnEvent {
/// The turn's final assistant text, when it produced one.
reply: Option<String>,
/// `handled` or `failed` — or `steered`, when a chat message
/// cut the turn short and a next turn runs instead of it — or
/// `aborted`, when the operator cut it and nothing follows.
/// cut the turn short and a next turn runs instead of it.
outcome: String,
},
/// The agent asked the human something only they can answer: a
@@ -331,42 +330,6 @@ 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
/// newest), ending exactly at `before` and starting at a turn's
/// first event — the page a client walking backward asks for, so a
@@ -952,77 +915,6 @@ mod tests {
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
/// on a turn boundary, so a transcript stacks pages without gaps,
/// overlaps, or a fragment at its top.
+7 -24
View File
@@ -14,8 +14,7 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -45,13 +44,9 @@ pub const MAX_IMAGE_BYTES: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentIdentity {
/// The agent's display name: message author, window title,
/// notifications, and the commit author name in workspaces.
/// notifications.
#[serde(default, skip_serializing_if = "Option::is_none")]
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.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mark: Option<String>,
@@ -74,7 +69,6 @@ pub struct AgentIdentity {
#[derive(Debug, Clone, Default)]
pub struct IdentityTexts {
pub name: Option<String>,
pub email: Option<String>,
pub mark: Option<String>,
pub initials: Option<String>,
pub tagline: Option<String>,
@@ -126,7 +120,6 @@ impl IdentityStore {
pub fn get(&self) -> Result<AgentIdentity, IdentityError> {
Ok(AgentIdentity {
name: self.text("name")?,
email: self.text("email")?,
mark: self.text("mark")?,
initials: self.text("initials")?,
tagline: self.text("tagline")?,
@@ -142,7 +135,6 @@ impl IdentityStore {
pub fn set_texts(&self, texts: &IdentityTexts) -> Result<AgentIdentity, IdentityError> {
let fields = [
("name", &texts.name, 64usize),
("email", &texts.email, 120),
("mark", &texts.mark, 8),
("initials", &texts.initials, 4),
("tagline", &texts.tagline, 120),
@@ -271,7 +263,6 @@ impl ToolOp for IdentitySet {
};
let texts = IdentityTexts {
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()),
initials: field(args["initials"].as_str(), current.initials.as_deref()),
tagline: field(args["tagline"].as_str(), current.tagline.as_deref()),
@@ -354,8 +345,10 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The identity tool set over `store`: `identity_set` — its spec from
/// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into()));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, workspace.into()),
);
assert!(
skipped.is_empty(),
"the identity_set tool manifest must load: {skipped:?}"
@@ -370,7 +363,7 @@ pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> Too
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
@@ -400,7 +393,6 @@ mod tests {
let saved = store
.set_texts(&IdentityTexts {
name: Some(" Kosmos ".to_owned()),
email: Some("kosmos@example.net".to_owned()),
mark: Some("✦".to_owned()),
initials: None,
tagline: Some("order".to_owned()),
@@ -408,7 +400,6 @@ mod tests {
})
.expect("the texts save");
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.initials, None);
assert_eq!(saved.signoff, None, "an empty string clears");
@@ -418,7 +409,6 @@ mod tests {
.set_texts(&IdentityTexts::default())
.expect("the clear saves");
assert_eq!(cleared.name, None);
assert_eq!(cleared.email, None);
}
#[test]
@@ -495,7 +485,6 @@ mod tests {
let answer = tool
.invoke(json!({
"name": "Kosmos",
"email": "kosmos@example.net",
"mark": "✦",
"avatar": "face.png",
}))
@@ -504,7 +493,6 @@ mod tests {
let answer: Value = serde_json::from_str(&answer).expect("parses");
assert_eq!(answer["saved"], true);
assert_eq!(answer["identity"]["name"], "Kosmos");
assert_eq!(answer["identity"]["email"], "kosmos@example.net");
assert_eq!(answer["identity"]["avatar"], true);
let (bytes, content_type) = store
.image(ImageKind::Avatar)
@@ -518,11 +506,6 @@ mod tests {
.expect("saves");
let identity = store.get().expect("reads");
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!(identity.avatar, "untouched by a text-only save");
}
+24 -218
View File
@@ -62,14 +62,6 @@
//! the conversation shows the question, the cut, and the answer that
//! replaced the rest of the interrupted work, exactly the shape
//! 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::num::NonZeroU32;
@@ -78,8 +70,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use rhema_autonomous_agent::{Handler, SessionContext};
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
@@ -90,14 +81,12 @@ use rhema_memory::{MemoryResolver, MemoryStore, Scope};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use serde_json::{Value, json};
use crate::abort::{AbortGuard, AbortRegistry};
use crate::backends::BackendRegistry;
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
use crate::hub::{EventHub, TurnEvent, UserImage};
use crate::notifications::NotificationStore;
use crate::sandbox::SandboxState;
use crate::steer::{SteerGuard, SteerRegistry};
use crate::toolkit::{Allowlist, ResolverChain};
/// The key prefixes of the resident context (see the module docs):
/// `interactive:`, `task:`, `phone:`, and `calendar:`. Forge keys —
@@ -249,12 +238,6 @@ pub struct InteractiveHandler {
/// registry with never receives a signal — and shared with the
/// HTTP surface through [`InteractiveHandler::with_steer`].
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
/// non-interactive replies auto-notify through it.
notifications: Arc<NotificationStore>,
@@ -324,7 +307,6 @@ impl InteractiveHandler {
bootstrap_resolver,
hub,
steer: Arc::new(SteerRegistry::new()),
abort: Arc::new(AbortRegistry::new()),
notifications,
attachments,
max_turn_steps,
@@ -383,8 +365,6 @@ impl InteractiveHandler {
&self.bootstrap,
&resolver.specs(),
vision,
&[],
crate::bootstrap::Surface::Chat,
)
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
Agent::builder()
@@ -405,15 +385,6 @@ impl InteractiveHandler {
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
/// sandbox root when commands run elsewhere.
fn workspace(&self) -> PathBuf {
@@ -459,16 +430,13 @@ impl InteractiveHandler {
}
/// One round: drain, restore, turn, stash, reply. The turn runs
/// under the steer/abort select, so a round that was interrupted
/// comes back as [`Round::Steered`] or [`Round::Aborted`] with the
/// session stashed and the dangling calls closed — steered, the
/// caller owes the inbox another round; aborted, the caller ends
/// the chain.
/// under the steer select, so a round that was interrupted comes
/// back as [`Round::Steered`] with the session stashed and the
/// dangling calls closed.
async fn dispatch(
&self,
ctx: &mut SessionContext,
steer: &mut SteerGuard,
abort: &mut AbortGuard,
round: usize,
) -> Result<Round, String> {
let key = ctx.key.as_str().to_owned();
@@ -499,8 +467,8 @@ impl InteractiveHandler {
// plain either way before the join, its span
// measured where it lands.
let mut message = [Message::text(Role::User, text.to_owned())];
crate::paste::migrate(&mut message);
let mut spans = crate::paste::spans(&message[0]);
rhema_core::paste::migrate(&mut message);
let mut spans = rhema_core::paste::spans(&message[0]);
let mut composed = match &message[0].content[0] {
Content::Text(text) => text.clone(),
_ => unreachable!("the message was built with one text block"),
@@ -511,9 +479,9 @@ impl InteractiveHandler {
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(crate::paste::normalize)
.map(rhema_core::paste::normalize)
{
let span = crate::paste::PasteSpan {
let span = rhema_core::paste::PasteSpan {
start: composed.len(),
end: composed.len() + paste.len(),
lines: paste.lines().count(),
@@ -540,7 +508,7 @@ impl InteractiveHandler {
}
let base = input.len();
input.push_str(&text);
pastes.extend(spans.into_iter().map(|span| crate::paste::PasteSpan {
pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan {
start: span.start + base,
end: span.end + base,
lines: span.lines,
@@ -671,14 +639,14 @@ impl InteractiveHandler {
let framed_len = input.len();
let pastes = pastes
.iter()
.map(|span| crate::paste::PasteSpan {
.map(|span| rhema_core::paste::PasteSpan {
start: span.start + framed_len - recorded_len,
end: span.end + framed_len - recorded_len,
lines: span.lines,
})
.collect::<Vec<_>>();
let mut question = [Message::text_with_images(Role::User, input, core_images)];
crate::paste::annotate(&mut question[0], &pastes);
rhema_core::paste::annotate(&mut question[0], &pastes);
let [turn_input] = question;
let mut turn = Box::pin(run_turn(
&mut agent,
@@ -688,7 +656,6 @@ impl InteractiveHandler {
&tools,
self.max_turn_steps,
));
let mut aborted = false;
let finished = tokio::select! {
result = &mut turn => match steer.take() {
// A message that raced the completion steers the next
@@ -699,13 +666,6 @@ impl InteractiveHandler {
),
},
_ = 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);
// An interrupted turn can leave committed calls without
@@ -722,7 +682,6 @@ impl InteractiveHandler {
match finished {
Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))),
Some(Err(reason)) => Err(reason),
None if aborted => Ok(Round::Aborted),
None => Ok(Round::Steered),
}
}
@@ -732,27 +691,19 @@ impl InteractiveHandler {
impl Handler for InteractiveHandler {
async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
let key = ctx.key.clone();
// The listeners live across the whole chain: one lease, one
// listener each, every steered round under them. `Drop`
// unregisters before the outcome releases the lease, so no
// signal can address a turn that no longer runs.
// The listener lives across the whole chain: one lease, one
// listener, every steered round under it. `Drop` unregisters
// before the outcome releases the lease, so no signal can
// address a turn that no longer runs.
let mut steer = self.steer.listen(key.as_str());
let mut abort = self.abort.listen(key.as_str());
let mut round = 1;
let mut aborted = false;
let finished = loop {
// Stale signals first: the route signals only after its
// ingest, so anything pending here is already in the inbox
// waiting for this round's drain — a signal must never cut
// the round it precedes. An abort is the opposite: it
// carries no inbox message, so a pending one is honored
// here, not cleared.
// the round it precedes.
steer.clear();
if abort.take() {
aborted = true;
break Ok(None);
}
match self.dispatch(ctx, &mut steer, &mut abort, round).await {
match self.dispatch(ctx, &mut steer, round).await {
Ok(Round::Done(reply)) => break reply,
// A steered round that drained nothing: the interrupt
// already happened, the chain just ends instead of
@@ -770,29 +721,10 @@ impl Handler for InteractiveHandler {
);
round += 1;
}
Ok(Round::Aborted) => {
aborted = true;
break Ok(None);
}
Err(reason) => break Err(reason),
}
};
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 {
Ok(reply) => {
self.auto_notify(&key, reply.as_deref());
@@ -843,17 +775,14 @@ impl InteractiveHandler {
}
}
/// One dispatch round's shape. A steered or aborted round ended in an
/// interrupt: the session stashed, the dangling calls closed — steered,
/// One dispatch round's shape. A steered round ended in an interrupt:
/// the caller owes the inbox another round on the same lease, same
/// session, same stream; aborted, the caller ends the chain.
/// session, same stream.
enum Round {
/// The turn ran to its end; the final reply text.
Done(Result<Option<String>, String>),
/// A steered message cut the turn short.
Steered,
/// The operator's abort cut the turn short.
Aborted,
/// A steered round whose inbox drained empty — the belt-and-braces
/// exit for a signal whose message raced the previous round's
/// drain: end the chain quietly, fail nothing.
@@ -873,7 +802,7 @@ fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
// embedded form in its prompts; the provider must never see
// a mark. One rewrite on the way in, chips survive as the
// span note — the same pass the driver's from_session runs.
crate::paste::migrate(&mut session.history);
rhema_core::paste::migrate(&mut session.history);
Ok(session)
}
}
@@ -897,7 +826,7 @@ fn final_text(message: &Message) -> Option<String> {
/// A tool result's bounded summary for the stream: the first line, cut
/// at 72 characters like the daemon's own log lines.
pub(crate) fn snippet(content: &str) -> String {
fn snippet(content: &str) -> String {
let line = content.lines().next().unwrap_or("");
let mut cut = line.chars().take(72).collect::<String>();
if line.chars().count() > 72 {
@@ -925,7 +854,7 @@ struct HubSink {
/// arguments JSON. A call whose args never streamed, or that parses to
/// something without a string `command`, renders without one — the TUI's
/// transcript makes the same bargain with the same deltas.
pub(crate) fn shell_command(args: Option<&str>) -> Option<String> {
fn shell_command(args: Option<&str>) -> Option<String> {
let parsed = serde_json::from_str::<Value>(args?).ok()?;
parsed.get("command")?.as_str().map(str::to_owned)
}
@@ -1461,8 +1390,6 @@ mod tests {
&handler.bootstrap,
&specs,
None,
&[],
crate::bootstrap::Surface::Chat,
)
.expect("renders");
assert!(
@@ -1756,8 +1683,8 @@ mod tests {
// The chip rides as the span note: one span, over exactly the
// payload's range, and no mark survives the restore.
assert_eq!(
crate::paste::spans(&session.history[0]).as_slice(),
&[crate::paste::PasteSpan {
rhema_core::paste::spans(&session.history[0]).as_slice(),
&[rhema_core::paste::PasteSpan {
start: "review this:".len(),
end: "review this:".len() + payload.len(),
lines: 3,
@@ -2005,127 +1932,6 @@ 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
/// generation's arrival.
struct Gate {
+4 -4
View File
@@ -17,8 +17,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -42,7 +41,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The coding-agent tool set over `store`: one tool, `coding_agent` —
/// its spec from the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<CodingJobStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"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)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+4 -113
View File
@@ -147,12 +147,6 @@ pub struct CodingJobHandler {
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>,
/// The abort registry the sessions' abort route signals: a live job
/// turn cut at its await stashes the conversation and lands the row
/// as failed with `aborted` (see [`crate::abort`]). Private by
/// default — a handler nobody shared a registry with never receives
/// a signal — and shared through [`CodingJobHandler::with_abort`].
abort: Arc<crate::abort::AbortRegistry>,
}
impl CodingJobHandler {
@@ -173,7 +167,6 @@ impl CodingJobHandler {
max_turn_steps,
transcript,
sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
}
}
@@ -184,24 +177,10 @@ impl CodingJobHandler {
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
/// lands in the job row before it lands in the outcome, so the
/// model's `status` read and the user's notification agree.
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
// what closes the dispatch. A job key carries exactly one kind of
// item, the row's own delivery, and those items are drained and
@@ -302,37 +281,16 @@ impl CodingJobHandler {
agent.set_commit_hook(Some(ctx.commit_hook()));
let mut sink = JobSink;
// The abort listener rides the turn: a signal drops the future
// at its current await — a streaming request, or a running
// shell command, whose child dies with the drop. Armed at
// 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;
let output = match agent.turn(&job.prompt, &mut sink).await {
Ok(output) => output,
Err(err) => {
let reason = format!("the coding turn for {instance_name:?} failed: {err}");
// The conversation up to the failure is still the
// instance's: saved, so a follow-up run continues it.
self.save_session(&instance_name, &agent);
self.fail(job_id, &instance_name, &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);
let reply = final_text(&output.message).ok_or_else(|| {
@@ -439,73 +397,6 @@ 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 {
ModelOutput {
message: CoreMessage::text(Role::Assistant, text),
+4 -14
View File
@@ -32,13 +32,9 @@
//! - [`turn_store`] — the turn-history table: what each key's stream
//! streamed, appended per event, replayed whole after a restart
//! - [`hub`] — the event hub: per-key record and broadcast of turn events
//! - [`identity`] — the agent's presentation identity: name, email,
//! mark, images, served over `/v1/agent` and settable by the agent
//! 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
//! - [`identity`] — the agent's presentation identity: name, mark,
//! images, served over `/v1/agent` and settable by the agent itself
//! through the `identity_set` tool
//! - [`consents`] — the consent table and wake bridge: a running turn
//! asks the human (a secret to store, permission to act) and waits;
//! the chat surface answers through the consent routes
@@ -70,7 +66,6 @@
#![forbid(unsafe_code)]
pub mod abort;
pub mod accounts_tools;
pub mod attachments;
pub mod backends;
@@ -81,7 +76,6 @@ pub mod daemon;
pub mod environment;
pub mod extension;
pub mod forge;
pub mod git_identity;
pub mod handler;
pub mod http;
pub mod hub;
@@ -96,8 +90,6 @@ pub mod mock;
pub mod notifications;
pub mod notify_tools;
pub mod openai;
pub mod paste;
pub mod pause;
pub mod phone;
pub mod sandbox;
pub mod settings;
@@ -105,8 +97,6 @@ pub mod steer;
pub mod task_source;
pub mod task_store;
pub mod task_tools;
pub mod thread;
pub mod toolkit;
pub mod turn_store;
pub(crate) mod vision;
pub mod watch_store;
@@ -118,7 +108,7 @@ pub use bootstrap::{
render_system,
};
pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
pub use daemon::{ClawError, Daemon, TickReport, run_once};
pub use environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource;
+3 -8
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::Outcome;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once};
use rhema_rsd::{DispatcherConfig, Outcome};
/// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)]
@@ -100,11 +100,6 @@ async fn run(args: Args) -> Result<(), ClawError> {
} else {
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!(
"[claw] active {}/{}, db {}, http {}",
backends.active().0,
@@ -140,7 +135,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on.
config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts");
let daemon = Daemon::build(&config, backends, forge_dispatch())?;
let daemon = Daemon::build(&config, backends, DispatcherConfig::default())?;
daemon.run().await
}
}
+8 -6
View File
@@ -12,8 +12,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -34,7 +33,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[("notify", include_str!("../tools/notif
/// The notification tool set over `store`: `notify` — its spec from
/// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<NotificationStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the notify tool manifest must load: {skipped:?}"
@@ -102,7 +102,7 @@ mod tests {
async fn call(store: &Arc<NotificationStore>, args: Value) -> rhema_core::ToolResult {
let resolver =
registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
resolver
.resolve(
rhema_core::ToolCall {
@@ -118,11 +118,13 @@ mod tests {
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_spec() {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "notify");
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("notify"),
rhema_core::ReplaySafety::Unsafe,
-215
View File
@@ -1,215 +0,0 @@
//! 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
@@ -1,160 +0,0 @@
//! 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);
}
}
+6 -5
View File
@@ -49,8 +49,7 @@ use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -722,8 +721,10 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, consents, bridge, hub, key));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, consents, bridge, hub, key),
);
assert!(
skipped.is_empty(),
"the phone tool manifest must load: {skipped:?}"
@@ -738,7 +739,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+57 -304
View File
@@ -1,20 +1,16 @@
//! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP, or an ssh login on a far
//! box.
//! Where the claw's `bash` runs: this host's processes, or a daemon
//! speaking the sandbox protocol over HTTP.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end; its private key rides the
//! choice as key text, the settings table is the store, so a
//! credential held in config or a store has no file to stage. The
//! tool spec, approval gate, output caps, and error shaping stay in
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
//! and gives the handlers a `ShellSandbox` executor over it. The tool
//! spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes the workspace root and, when it is
//! empty, sends the host workspace as a tarball through the seed
//! workspace, the executor probes `/workspace` and, when it is empty,
//! sends the host workspace as a tarball through the protocol's seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
@@ -26,11 +22,9 @@ use std::time::Duration;
use async_trait::async_trait;
use base64::Engine as _;
use rhema_bash::exec::{RunOutcome, ShellError, ShellExecutor, default_executor_with};
use rhema_core::{OutputOnly, ToolProgress};
use rhema_sandbox::{RunRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore;
@@ -38,15 +32,10 @@ use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path the http sandbox exposes: one root per session,
/// The workspace path a remote sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The ssh sandbox's default workspace base: the remote login's own
/// home, the ssh backend's documented default. One directory per claw
/// workspace lands under it, named by the session hash.
pub const SSH_WORKSPACE_ROOT: &str = "/root";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
@@ -61,8 +50,6 @@ pub enum SandboxKind {
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
}
impl SandboxKind {
@@ -71,7 +58,6 @@ impl SandboxKind {
match self {
Self::Local => "local",
Self::Http => "http",
Self::Ssh => "ssh",
}
}
@@ -81,7 +67,6 @@ impl SandboxKind {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
"ssh" => Some(Self::Ssh),
_ => None,
}
}
@@ -101,22 +86,6 @@ pub struct SandboxChoice {
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// The `ssh` sandbox's destination: any alias or `user@host` the
/// local ssh config resolves, the built-in client's resolution.
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
/// The `ssh` sandbox's workspace base, where the per-workspace
/// directories land. Defaults to [`SSH_WORKSPACE_ROOT`].
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
/// The `ssh` sandbox's private key, the key text itself (OpenSSH
/// or PEM format), not a path: the choice lives in a config file
/// or a store that has no file to stage. Unset, the sandbox
/// hunts like the `ssh` binary would, the agent first, then the
/// default key files. `GET /v1/sandbox` never returns the key,
/// only that one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub private_key: Option<String>,
}
impl SandboxChoice {
@@ -132,36 +101,6 @@ impl SandboxChoice {
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
self.host = self
.host
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty());
self.workspace = self
.workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty());
self.private_key = self
.private_key
.map(|key| key.trim().to_owned())
.filter(|key| !key.is_empty());
if self.kind == SandboxKind::Ssh {
let host = self
.host
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the ssh sandbox needs a host".to_owned()))?;
if host.contains(char::is_whitespace) {
return Err(SandboxError::Invalid(
"the ssh sandbox host is one destination, no spaces".to_owned(),
));
}
if let Some(workspace) = self.workspace.as_deref()
&& !workspace.starts_with('/')
{
return Err(SandboxError::Invalid(
"the ssh sandbox workspace must be an absolute path".to_owned(),
));
}
}
if self.kind == SandboxKind::Http {
let url = self
.url
@@ -178,22 +117,7 @@ impl SandboxChoice {
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind != SandboxKind::Local
}
/// The remote directory one workspace's commands run in: the
/// protocol root for `http`, a directory per host workspace under
/// the configured base for `ssh`.
pub fn remote_root(&self, host: &Path) -> PathBuf {
match self.kind {
SandboxKind::Http => PathBuf::from(REMOTE_WORKSPACE),
SandboxKind::Ssh => PathBuf::from(format!(
"{}/{}",
self.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT),
session_name(host)
)),
SandboxKind::Local => host.to_path_buf(),
}
self.kind == SandboxKind::Http
}
}
@@ -215,7 +139,7 @@ pub struct SandboxState {
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<dyn Sandbox>>>,
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
}
impl SandboxState {
@@ -280,9 +204,13 @@ impl SandboxState {
}
/// The workspace a handler should name and start commands in: the
/// host path locally, the choice's remote root otherwise.
/// host path locally, `/workspace` on a remote sandbox.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
self.choice().remote_root(host)
if self.is_remote() {
PathBuf::from(REMOTE_WORKSPACE)
} else {
host.to_path_buf()
}
}
/// The chat workspace under the current choice, for the settings
@@ -311,14 +239,18 @@ impl SandboxState {
})
}
/// The cached sandbox for one session. The map is cleared whenever
/// the choice changes, so a new URL, token, host, or base builds a
/// new client.
/// The cached HTTP client for one session. The map is cleared
/// whenever the choice changes, so a new URL or token builds a new
/// client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<dyn Sandbox>, ShellError> {
) -> Result<Arc<HttpSandbox>, ShellError> {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
@@ -326,33 +258,8 @@ impl SandboxState {
return Ok(sandbox.clone());
}
}
let sandbox: Arc<dyn Sandbox> =
match choice.kind {
SandboxKind::Http => {
let url = choice.url.as_deref().ok_or_else(|| {
ShellError::Failed("the http sandbox has no url".to_owned())
})?;
let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
}
SandboxKind::Ssh => {
let dest = choice.host.as_deref().ok_or_else(|| {
ShellError::Failed("the ssh sandbox has no host".to_owned())
})?;
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
let mut sandbox = SshSandbox::new(dest.to_owned())
.with_workspace(format!("{base}/{session}"));
if let Some(key) = choice.private_key.as_deref() {
sandbox = sandbox.with_private_key(key);
}
Arc::new(sandbox)
}
SandboxKind::Local => {
return Err(ShellError::Failed(
"the local sandbox needs no remote client".to_owned(),
));
}
};
let token = choice.token.as_deref().unwrap_or("");
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
@@ -373,32 +280,20 @@ struct ClawShell {
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty workspace root gets
/// Seeds the sandbox once per choice. An empty `/workspace` gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox. 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.
/// so a restart never overwrites work done in the sandbox.
async fn seed(
&self,
sandbox: &Arc<dyn Sandbox>,
sandbox: &Arc<HttpSandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = OutputOnly(|_line: &str| {});
let mut sink = |_line: &str| {};
let probe = sandbox
.run(
RunRequest {
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone().into(),
.exec(
ExecRequest {
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
cwd: REMOTE_WORKSPACE.to_owned(),
timeout: PROBE_TIMEOUT,
},
cancelled,
@@ -433,13 +328,18 @@ impl ClawShell {
impl ShellExecutor for ClawShell {
async fn run(
&self,
request: RunRequest,
command: &str,
cwd: &Path,
timeout: Duration,
cancelled: &AtomicBool,
progress: &mut dyn ToolProgress,
) -> Result<RunOutcome, ShellError> {
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
) -> Result<Executed, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self.local.run(request, cancelled, progress).await;
return self
.local
.run(command, cwd, timeout, cancelled, progress)
.await;
}
{
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
@@ -453,14 +353,12 @@ impl ShellExecutor for ClawShell {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let root = choice.remote_root(&self.host_workspace);
let sandbox: Arc<dyn Sandbox> = sandbox;
ShellSandbox::new(sandbox)
.run(
RunRequest {
command: request.command,
cwd: root,
timeout: request.timeout,
},
command,
Path::new(REMOTE_WORKSPACE),
timeout,
cancelled,
progress,
)
@@ -473,7 +371,6 @@ impl ShellExecutor for ClawShell {
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::OutOfMemory => ShellError::OutOfMemory,
rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still
@@ -482,13 +379,6 @@ 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
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
@@ -568,7 +458,7 @@ mod tests {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
..SandboxChoice::default()
token: None,
}
.normalized();
assert!(missing.is_err(), "a URL is required");
@@ -576,90 +466,18 @@ mod tests {
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
..SandboxChoice::default()
token: None,
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn an_ssh_choice_needs_a_host_and_an_absolute_base() {
let missing = SandboxChoice {
kind: SandboxKind::Ssh,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a host is required");
let spaced = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me @box".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(spaced.is_err(), "a destination is one word");
let relative = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("srv/claw".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "the base is an absolute path");
let good = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some(" me@box ".to_owned()),
workspace: Some("/srv/claw/".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(good.host.as_deref(), Some("me@box"));
assert_eq!(good.workspace.as_deref(), Some("/srv/claw"));
assert!(good.is_remote());
assert_eq!(good.kind.as_str(), "ssh");
assert_eq!(
SandboxKind::parse("ssh"),
Some(SandboxKind::Ssh),
"the stored spelling round-trips"
);
}
#[test]
fn the_private_key_trims_and_a_blank_stays_unset() {
let keyed = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" -----BEGIN OPENSSH PRIVATE KEY----- ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(
keyed.private_key.as_deref(),
Some("-----BEGIN OPENSSH PRIVATE KEY-----"),
"the key text is trimmed, not mangled"
);
let blank = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("a blank key is no key, not a rejection");
assert_eq!(blank.private_key, None, "blank keeps the hunt on");
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
..SandboxChoice::default()
token: None,
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
@@ -669,36 +487,6 @@ 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]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
@@ -716,7 +504,6 @@ mod tests {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
@@ -728,38 +515,6 @@ mod tests {
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[test]
fn an_ssh_choice_persists_with_its_host_and_base() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
state
.set(SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Ssh);
assert_eq!(reloaded.choice().host.as_deref(), Some("me@box"));
assert_eq!(reloaded.choice().workspace.as_deref(), Some("/srv/claw"));
assert_eq!(
reloaded.workspace().to_string_lossy(),
format!("/srv/claw/{}", session_name(Path::new("/tmp/ws"))),
"the settings surface reports the session root"
);
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
@@ -801,18 +556,16 @@ mod tests {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
..SandboxChoice::default()
token: None,
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = OutputOnly(|_line: &str| {});
let mut sink = |_line: &str| {};
let executed = executor
.run(
RunRequest {
command: "echo hi".to_owned(),
cwd: Path::new(REMOTE_WORKSPACE).to_path_buf(),
timeout: Duration::from_secs(5),
},
"echo hi",
Path::new(REMOTE_WORKSPACE),
Duration::from_secs(5),
&cancelled,
&mut sink,
)
+13 -10
View File
@@ -15,8 +15,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
@@ -66,7 +65,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `cancel_task` — specs from the embedded manifests, operations
/// compiled here.
pub fn registry(store: Arc<TaskStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"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 {
let resolver =
registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
resolver
.resolve(
rhema_core::ToolCall {
@@ -252,7 +252,8 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!(
@@ -270,7 +271,7 @@ mod tests {
let mut covered = Vec::new();
for (source, raw) in MANIFESTS {
covered.push(
crate::toolkit::parse_manifest(raw)
rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin,
);
@@ -285,11 +286,12 @@ mod tests {
#[test]
fn the_registry_serves_the_manifest_specs() {
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let specs = resolver.specs();
for (name, raw) in MANIFESTS {
let manifest =
crate::toolkit::parse_manifest(raw).unwrap_or_else(|err| panic!("{name}: {err}"));
let manifest = rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{name}: {err}"));
let spec = specs
.iter()
.find(|spec| spec.name == *name)
@@ -308,7 +310,8 @@ mod tests {
#[test]
fn replay_safety_comes_from_the_manifest() {
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("list_tasks"),
rhema_core::ReplaySafety::Safe
-413
View File
@@ -1,413 +0,0 @@
//! 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
@@ -1,680 +0,0 @@
//! 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,13 +395,6 @@ impl ClawStore {
"DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2",
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)
}
@@ -413,11 +406,6 @@ impl ClawStore {
"DELETE FROM account_watches WHERE account_id = ?1",
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)
}
+12 -10
View File
@@ -14,8 +14,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -63,7 +62,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `unwatch_repo`, `list_watches` — specs from the embedded manifests,
/// operations compiled here.
pub fn registry(store: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the watch tool manifests must all load: {skipped:?}"
@@ -197,7 +197,7 @@ mod tests {
fn names(registry: &ToolRegistry) -> Vec<String> {
registry
.resolver_for(&crate::toolkit::Allowlist::permissive())
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive())
.specs()
.into_iter()
.map(|spec| spec.name)
@@ -206,7 +206,8 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!(
@@ -220,7 +221,7 @@ mod tests {
let mut covered = Vec::new();
for (source, raw) in MANIFESTS {
covered.push(
crate::toolkit::parse_manifest(raw)
rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin,
);
@@ -235,7 +236,8 @@ mod tests {
#[test]
fn replay_safety_comes_from_the_manifest() {
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("list_watches"),
rhema_core::ReplaySafety::Safe
@@ -261,7 +263,7 @@ mod tests {
async fn watch_repo_lands_a_row_and_answers_json() {
let store = store();
let tools = registry(store.clone());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let result = resolver
.resolve(
@@ -301,7 +303,7 @@ mod tests {
async fn a_bad_watch_fails_in_band_with_the_reason() {
let store = store();
let tools = registry(store.clone());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| {
resolver.resolve(
@@ -354,7 +356,7 @@ mod tests {
store.add("github", "acme/widgets", None, "").expect("seed");
store.add("gitlab", "group/prop", None, "").expect("seed");
let tools = registry(store.clone());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| {
resolver.resolve(
-1
View File
@@ -94,7 +94,6 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
transcript: None,
ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
-1
View File
@@ -60,7 +60,6 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
transcript: None,
ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+6 -562
View File
@@ -11,7 +11,7 @@ use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use rhema_claw::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
use rhema_claw::watch_tools;
use rhema_claw::{ClawConfig, Daemon};
use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
@@ -67,7 +67,6 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
ingest_token: None,
transcript: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -514,225 +513,6 @@ 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
/// type, non-empty body, decoded size, count), the transcript's
/// user_message card names the stored ids and media types, and each id
@@ -955,10 +735,10 @@ async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
.iter()
.find(|message| message.role == Role::User)
.expect("the question is stashed");
assert_eq!(rhema_claw::paste::spans(ask).len(), 1);
assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_claw::paste::spans(ask)[0].lines, 2);
assert_eq!(rhema_core::paste::spans(ask).len(), 1);
assert_eq!(rhema_core::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_core::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2);
}
/// A turn nobody watched is still replayable: a client arriving after
@@ -2651,132 +2431,6 @@ async fn the_sandbox_choice_is_listed_and_switchable() {
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
/// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type,
@@ -2807,7 +2461,7 @@ async fn the_agent_identity_is_editable_over_the_surface() {
// A save names the fields it touches.
let saved: Value = client
.put(format!("{base}/v1/agent"))
.json(&json!({"name": "Kosmos", "email": "kosmos@example.net", "mark": "✦", "tagline": "order"}))
.json(&json!({"name": "Kosmos", "mark": "✦", "tagline": "order"}))
.send()
.await
.expect("the save posts")
@@ -2816,7 +2470,6 @@ async fn the_agent_identity_is_editable_over_the_surface() {
.expect("the save parses");
assert_eq!(saved["name"], "Kosmos");
assert_eq!(saved["mark"], "✦");
assert_eq!(saved["email"], "kosmos@example.net");
assert_eq!(saved["avatar"], false);
// A partial save leaves the fields it omitted.
@@ -2831,10 +2484,6 @@ async fn the_agent_identity_is_editable_over_the_surface() {
.expect("the partial save parses");
assert_eq!(partial["name"], "Kosmos Prime");
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.
let cleared: Value = client
@@ -3836,29 +3485,6 @@ async fn a_restart_releases_a_dead_lease_and_the_key_answers() {
let base = serve(&daemon).await;
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.
let sessions: Value = client
.get(format!("{base}/v1/sessions"))
@@ -4119,185 +3745,3 @@ async fn a_leased_session_is_not_deletable() {
assert_eq!(sessions[0]["key"], "interactive:web");
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,7 +67,6 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
transcript: None,
ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+5 -11
View File
@@ -3,12 +3,11 @@
name: identity_set
description: >-
Set your own presentation identity: the name, mark, initials,
tagline, and signoff the interfaces render, an email to commit and
write as, and your avatar or logo images. This is how you look, not
who you are — personality lives in SOUL.md. Leave a field out to
keep what is set; an empty string clears it. The avatar and logo
take a workspace-relative path to an image file (png, jpeg, gif, or
webp, under 2 MiB — svg is refused).
tagline, and signoff the interfaces render, and your avatar or logo
images. This is how you look, not who you are — personality lives in
SOUL.md. Leave a field out to keep what is set; an empty string
clears it. The avatar and logo take a workspace-relative path to an
image file (png, jpeg, gif, or webp, under 2 MiB — svg is refused).
parameters:
type: object
properties:
@@ -17,11 +16,6 @@ parameters:
description: >-
Display name: message author, window title, notifications. Up
to 64 chars.
email:
type: string
description: >-
The author address on the commits your workspaces make. Up to
120 chars.
mark:
type: string
description: Glyph or emoji for the rail and favicon. Up to 8 chars.
+2 -25
View File
@@ -48,26 +48,9 @@ FROM debian:stable-slim
# bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& 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.
RUN useradd --uid 1000 --user-group --create-home claw \
&& install -d -o 1000 -g 1000 /config /data
@@ -76,14 +59,8 @@ COPY --from=builder /build/target/release/rhema-claw /usr/local/bin/rhema-claw
# The chart passes --config /config/claw.yaml (the ConfigMap mount) and
# 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 \
XDG_STATE_HOME=/data/state \
XDG_RUNTIME_DIR=/tmp/run
XDG_STATE_HOME=/data/state
VOLUME /data
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
# neither).
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+2 -2
View File
@@ -3,5 +3,5 @@ name: rhema-claw
description: "The resident forge-watching agent daemon: forge watches and a
chat HTTP surface over one SQLite store."
type: application
version: 0.4.1
appVersion: "0.4.1"
version: 0.4.0
appVersion: "0.4.0"
-8
View File
@@ -31,14 +31,6 @@ config:
# - forge: github
# repo: acme/widgets
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:
type: ClusterIP
@@ -15,20 +15,20 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's
rhema-autonomous-agent = "0.4.2"
rhema-autonomous-agent = "0.4.0"
# The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's
rhema-rsd = "0.4.2"
rhema-rsd = "0.4.0"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
async-trait = { workspace = true }
# HTTP against the three feed kinds: one bounded request per poll, no
# streaming
reqwest = { version = "0.13", features = ["json", "query"] }
reqwest = { version = "0.12", features = ["json"] }
# The CalDAV adapter reads 207 multistatus bodies; the element set it
# cares about is small enough that a pull parser beats a DOM
quick-xml = "0.42"
quick-xml = "0.41"
# Every wire time (RFC 3339, iCalendar's compact `YYYYMMDDTHHMMSS[Z]`,
# `VALUE=DATE` all-days) normalizes to an OffsetDateTime, and the
# vocabulary's instants round-trip as RFC 3339.
@@ -186,9 +186,10 @@ fn compact_z(at: OffsetDateTime) -> String {
/// namespace URIs the element binds. Matching local names inside a
/// `prop` stat is the pragmatic read every DAV client ships.
fn local_name(name: quick_xml::name::QName<'_>) -> &str {
// The reader was built from a &str, so a borrowed name is valid
// UTF-8 by construction; no decode step can fail here.
name.local_name().into_inner()
// The reader was built from a &str, so every borrowed name is
// UTF-8 already; a decoding failure cannot say anything truer than
// "not the element we were looking for".
std::str::from_utf8(name.local_name().into_inner()).unwrap_or("")
}
/// Pulls every `calendar-data` value out of a 207 multistatus, in
@@ -214,8 +215,10 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
// where the iCalendar needs CRLF, and an unexpanded
// reference would fold the whole object into one line
// and read as quietly empty.
let content = text.xml10_content();
let decoded = unescape(&content)
let decoded = text
.xml10_content()
.map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?;
let decoded = unescape(&decoded)
.map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?;
current.push_str(&decoded);
}
@@ -225,7 +228,9 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
Ok(Some(ch)) => current.push(ch),
// A named entity (`&amp;`): the escape table's.
Ok(None) => {
let raw = reference.xml10_content();
let raw = reference.xml10_content().map_err(|err| {
CalendarError::Parse(format!("multistatus text: {err}"))
})?;
let entity = format!("&{raw};");
let decoded = unescape(&entity).map_err(|err| {
CalendarError::Parse(format!("multistatus text: {err}"))
@@ -238,7 +243,7 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
}
}
Ok(XmlEvent::CData(text)) if capturing => {
current.push_str(&text);
current.push_str(&String::from_utf8_lossy(text.as_ref()));
}
Ok(XmlEvent::End(element)) => {
if capturing && local_name(element.name()) == "calendar-data" {
@@ -13,14 +13,14 @@ publish = false
[dependencies]
# The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = "0.4.2"
rhema-rsd = "0.4.0"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
async-trait = { workspace = true }
# HTTP against the three forge REST APIs: JSON request/response bodies,
# no streaming
reqwest = { version = "0.13", features = ["json", "query"] }
reqwest = { version = "0.12", features = ["json"] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
+13 -41
View File
@@ -60,12 +60,9 @@ Two consequences worth knowing before changing this code:
fire-and-forget (202); the reply streams back on
`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
feed. That turn comes back whole even when it is longer than the
replay window, so a reload never lands mid-reply with the file the
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
feed — 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
is shorter than the screen). So the transcript survives the browser,
not just the claw.
@@ -115,16 +112,11 @@ Two consequences worth knowing before changing this code:
and again on the stream's `consent_resolved` echo; nothing persists
client-side, so a reload rebuilds the cards from the replay.
- **Attachments render inline.** An `attachment` event becomes a card
— media glyph, file name, B/KB/MB size, caption. The media kind comes
from the file extension, decided by the daemon when it stores the
file, so a `.png` renders and a `.patch` downloads without the client
guessing. Images fetch the bearer-guarded bytes
(`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.
— media glyph, file name, B/KB/MB size, caption. Images fetch the
bearer-guarded bytes (`GET /v1/attachments/{id}`, blob → object URL,
like the identity images) and render capped at 240px; code and file
cards download on click. Object URLs cache per id, so a replay never
refetches.
- **Your images ride along.** The composer's `+` — and an image on 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
@@ -136,21 +128,11 @@ Two consequences worth knowing before changing this code:
- **Sessions are created in place.** The sidebar's `+` form posts
`POST /v1/sessions` with a client-validated name
(`[A-Za-z0-9._-]{1,64}`), switches the chat to the new key, and
lets 400/409 land in the error banner. The interactive prefixes
(`interactive:`) list above the fold; *others* holds the whole rest
of the inventory — `task:`, `calendar:`, the phone's keys
(`phone:…`), the coding jobs' `job:<instance>#<id>` keys and forge
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.
lets 400/409 land in the error banner. The inventory lists only the
resident prefixes (`interactive:`, `task:`, `calendar:`) — the ones the
message, event and history routes answer for. The phone's status keys
(`phone:…`), the coding jobs' `job:<instance>#<id>` keys and forge keys
stay out, and the full list stays on the wire.
- **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
turn history goes with it, and `DELETE /v1/sessions/{key}` runs on
@@ -159,16 +141,6 @@ Two consequences worth knowing before changing this code:
error banner like every other refusal, and the chat moves to the
first remaining session, the stream's watcher following the key so
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
+38 -162
View File
@@ -22,7 +22,7 @@ import type {
StreamStatus,
} from '~/composables/useClaw'
import { composeChips, useTranscript } from '~/composables/useTranscript'
import type { AttachmentCard, StagedImage } from '~/composables/useTranscript'
import type { StagedImage } from '~/composables/useTranscript'
const TOKEN_STORE_KEY = 'claw.token'
const ACTIVE_STORE_KEY = 'claw.activeKey'
@@ -121,12 +121,9 @@ const {
// for weeks costs nothing up front and still reaches its first message.
const olderAvailable = ref(true)
// The cards this page already tried to fetch. Keyed by the card object
// rather than the attachment id: a page read, a mirror reset, or a live
// 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>()
// Attachment ids this page already tried to fetch; a failed fetch is
// not retried until the stream resets and clears the set.
const attemptedAttachments = new Set<string>()
// Image cards need their bytes before they can render: fetched as the
// card appears, not on any timer. code/file fetch on download instead.
@@ -134,49 +131,39 @@ let attemptedAttachments = new WeakSet<object>()
// their attachment ids, never the bytes; locally sent rows hold their
// own object URLs.
//
// The cards sit at two depths. One handed over mid-turn lands in the
// open turn's entries and rides into the finished turn with it, so a
// scan of the top-level rows alone would never see it and the card
// 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.
function requestAttachmentImages(): void {
const fetchAttachment = (attachment: AttachmentCard) => {
const { id, media, url } = attachment
if (media !== 'image' || url !== null || attemptedAttachments.has(attachment)) return
attemptedAttachments.add(attachment)
claw
.attachmentUrl(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)
// The watch is deep (rows mutate in place as their bytes land), and it
// fires on every streamed delta, so the scan covers only the items the
// last pass did not see — the transcript only ever appends.
let scannedItems = 0
watch(
transcriptItems,
(items) => {
for (const item of items.slice(scannedItems)) {
if (item.kind === 'attachment') {
const { id, media, url } = item.attachment
if (media !== 'image' || url !== null || attemptedAttachments.has(id)) continue
attemptedAttachments.add(id)
claw
.attachmentUrl(id)
.then((fetched) => transcript.setSentImageUrl(id, fetched))
.then((fetched) => transcript.setAttachmentUrl(id, fetched))
.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))
}
}
}
}
for (const entry of transcript.live.value?.entries ?? []) {
if (entry.kind === 'attachment') fetchAttachment(entry.attachment)
}
}
watch([transcriptItems, transcript.live], requestAttachmentImages, {
deep: true,
immediate: true,
})
scannedItems = items.length
},
{ deep: true },
)
// --- the agent's identity --------------------------------------------
const identity = ref<AgentIdentity | null>(null)
@@ -323,13 +310,6 @@ async function refreshSessions(): Promise<void> {
try {
sessions.value = await claw.sessions()
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) {
noteApiError(err)
} finally {
@@ -397,49 +377,6 @@ 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> {
try {
providersState.value = await claw.providers()
@@ -586,11 +523,7 @@ async function saveSandbox(choice: SandboxSelection): Promise<void> {
try {
sandboxState.value = await claw.setSandbox(choice)
pushNotice(
choice.kind === 'http'
? 'sandbox: remote host'
: choice.kind === 'ssh'
? 'sandbox: ssh host'
: 'sandbox: this machine',
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine',
)
apiError.value = null
} catch (err) {
@@ -665,11 +598,7 @@ async function downloadAttachment(id: string, name: string): Promise<void> {
const anchor = document.createElement('a')
anchor.href = url
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.remove()
} catch (err) {
noteApiError(err)
}
@@ -696,38 +625,18 @@ function saveToken(): void {
// --- the one live subscription ---------------------------------------
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 {
stream?.close()
stream = null
transcript.reset()
olderAvailable.value = true
attemptedAttachments = new WeakSet<object>()
attemptedAttachments.clear()
notices.value = []
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
// stream: subscribing to one would retry a 404 forever.
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, {
onEvent: (event, seq) => transcript.applyEvent(event, seq),
// The record lost what this mirror holds (a wiped or reset
@@ -735,8 +644,8 @@ function resubscribe(): void {
onReset: () => {
transcript.reset()
olderAvailable.value = true
attemptedAttachments = new WeakSet<object>()
requestAttachmentImages()
attemptedAttachments.clear()
scannedItems = 0
},
onStatus: (status) => {
streamStatus.value = status
@@ -745,8 +654,8 @@ function resubscribe(): void {
// is. Only the attachment set is cleared — a fetch that failed
// during the outage should retry against the recovered stream.
if (status === 'reconnecting') {
attemptedAttachments = new WeakSet<object>()
requestAttachmentImages()
attemptedAttachments.clear()
scannedItems = 0
}
if (status === 'open') void refreshSessions()
},
@@ -754,35 +663,6 @@ 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
* it above. Whole turns only, so the page never duplicates or skips:
* the daemon ends it exactly where the mirror begins. */
@@ -886,16 +766,12 @@ onUnmounted(() => {
@refresh="refreshSessions"
@create="createSession"
@delete="askDeleteSession"
@pause="pauseSession"
@resume="resumeSession"
@abort="abortSession"
/>
<ChatPanel
:items="transcriptItems"
:live="liveTurn"
:active-key="activeKey"
:can-send="isInteractive(activeKey)"
:read-only="threadReadOnly"
:busy="busy"
:session="activeSession"
:active-backend="providersState?.active ?? null"
+13 -95
View File
@@ -26,8 +26,6 @@ const props = defineProps<{
activeKey: string
/** Only `interactive:*` keys accept messages (the claw 400s the rest). */
canSend: boolean
/** The daemon answers this key with a snapshot, not a stream. */
readOnly: boolean
busy: boolean
session: ClawSession | null
activeBackend: { provider: string; model: string } | null
@@ -45,27 +43,6 @@ const props = defineProps<{
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
* the staged images, previews included for the optimistic row. */
interface SendPayload {
@@ -451,13 +428,10 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="text">
<h2>{{ displayName }}</h2>
</div>
<span v-if="streaming" class="stream-status" :title="`event stream: ${streamStatus}`">
<span class="stream-status" :title="`event stream: ${streamStatus}`">
<StatusDot :tone="streamTone(streamStatus)" />
{{ streamLabel }}
</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>
</header>
@@ -472,9 +446,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div ref="scroller" class="stream-area" @scroll.passive="onScroll">
<p v-if="items.length === 0 && !live" class="empty">
{{ streaming
? 'nothing streamed yet; messages post to the claw and replies arrive here live'
: 'nothing recorded for this key yet' }}
nothing streamed yet; messages post to the claw and replies arrive here live
</p>
<p v-if="loadingOlder" class="older-hint">loading earlier turns</p>
@@ -483,7 +455,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div v-if="item.kind === 'sent'" class="msg">
<div class="avatar user" aria-hidden="true">·</div>
<div class="msg-body">
<div class="who">{{ userLabel }}</div>
<div class="who">you</div>
<div v-if="item.images.length > 0" class="sent-images">
<button
v-for="(image, index) in item.images"
@@ -518,11 +490,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div
v-if="item.turn.outcome"
class="outcome mono"
:class="{
failed: item.turn.outcome === 'failed',
steered: item.turn.outcome === 'steered',
aborted: item.turn.outcome === 'aborted',
}"
:class="{ failed: item.turn.outcome === 'failed', steered: item.turn.outcome === 'steered' }"
>
{{ item.turn.outcome }}
</div>
@@ -551,10 +519,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
@download-attachment="(id, name) => emit('downloadAttachment', id, name)"
/>
<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>
@@ -591,9 +555,8 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
{{ imageError }}
<button class="chip-x" title="dismiss" @click="imageError = null">×</button>
</p>
<p v-if="!canSend" class="read-only">{{ readOnlyNote }}</p>
<div v-else class="input-row">
<button class="ghost attach" title="attach images" @click="pickImages">
<div class="input-row">
<button class="ghost attach" title="attach images" :disabled="!canSend" @click="pickImages">
+
</button>
<textarea
@@ -601,15 +564,20 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
v-model="draft"
rows="1"
:placeholder="
live ? `Message ${agentName}… sending steers the running turn` : `Message ${agentName}…`
canSend
? live
? `Message ${agentName}… sending steers the running turn`
: `Message ${agentName}…`
: 'only interactive:* sessions accept messages'
"
:disabled="!canSend"
@keydown="onPromptKeydown"
@paste="onPaste"
@input="resizePrompt"
/>
<button
class="primary send"
:disabled="busy || draft.trim() === ''"
:disabled="!canSend || busy || draft.trim() === ''"
:title="live ? 'send — interrupts the running turn' : 'send'"
@click="submit"
>
@@ -787,49 +755,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
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
from a tool row, toned by its resolution. */
.consent-card {
@@ -1012,13 +937,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
gap: 8px;
}
.read-only {
margin: 0;
padding: 2px 0;
color: var(--text3);
font-size: 12.5px;
}
.attach {
width: 38px;
padding: 0;
+35 -188
View File
@@ -7,19 +7,6 @@
// new key lands in the inventory. The delete button asks nothing itself
// — the confirmation, which names the transcript that goes with the
// 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 type { ClawSession } from '~/composables/useClaw'
@@ -36,80 +23,42 @@ const emit = defineEmits<{
refresh: []
create: [name: string]
delete: [key: string]
pause: [key: string]
resume: [key: string]
abort: [key: string]
}>()
interface Group {
label: string
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
rows: { key: string; name: string; session: ClawSession }[]
}
const groups = computed<Group[]>(() => {
const byKey = (a: ClawSession, b: ClawSession) => a.key.localeCompare(b.key)
// The resident prefixes are the chat sessions: `interactive:` is the
// live chat surface, `task:` a scheduled task's own turn, `phone:` the
// phone client's, `calendar:` a reminder's. The rest of the inventory —
// `job:<instance>#<id>`, a forge thread — holds no turn record: its
// handler never streams. Its history route serves the session stash
// instead, so the row still opens, read-only.
const interactive = props.sessions
// Only the resident prefixes are chat sessions: `interactive:` is the
// live chat surface, `task:` a scheduled task's own turn, `calendar:` a
// reminder's. The rest of the inventory has no transcript to open —
// `phone:<device>:<topic>` is status reporting, `job:<instance>#<id>`
// is the coding jobs' bookkeeping, a forge key is a thread the handler
// reports on — and the daemon's message, event and history routes
// refuse those prefixes, so a row for one is a dead end. The inventory
// 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:'))
.sort(byKey)
const others = props.sessions
const others = conversable
.filter((session) => !session.key.startsWith('interactive:'))
.sort(byKey)
const row = (session: ClawSession) => ({
key: session.key,
name: session.key.replace(/^interactive:/, ''),
session,
abortable: session.state === 'leased' || session.inbox_depth > 0,
})
const working = (sessions: ClawSession[]) =>
sessions.filter((session) => session.state === 'leased').length
const groups: Group[] = []
if (interactive.length > 0)
groups.push({
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,
})
groups.push({ label: 'interactive', rows: interactive.map(row) })
if (others.length > 0) groups.push({ label: 'other keys', rows: others.map(row) })
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(() =>
groups.value.reduce((total, group) => total + group.rows.length, 0),
)
@@ -210,76 +159,30 @@ watch(
</p>
<div v-for="group in groups" :key="group.label" class="group">
<div class="group-head">
<span class="label">{{ group.label }}</span>
<span v-if="group.collapsible" class="working" :class="{ live: group.working > 0 }">
{{ group.working }} working
</span>
<span class="label">{{ group.label }}</span>
<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.inbox_depth > 0" class="depth" title="inbox depth">
{{ row.session.inbox_depth }}
</span>
</button>
<button
v-if="group.collapsible"
class="ghost toggle"
:title="othersOpen ? 'fold the other keys away' : 'show every other key'"
@click="othersOpen = !othersOpen"
class="ghost remove"
aria-label="delete session"
:title="`delete ${row.key}`"
@click.stop="$emit('delete', row.key)"
>
{{ othersOpen ? 'less' : 'more' }}
×
</button>
</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>
</aside>
</template>
@@ -384,32 +287,10 @@ watch(
margin-bottom: 14px;
}
.group-head {
display: flex;
align-items: center;
gap: 8px;
.group .label {
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
and the delete button sits beside it, so neither has to nest in the
other. */
@@ -448,27 +329,6 @@ watch(
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 {
flex: none;
padding: 0 5px;
@@ -476,25 +336,12 @@ watch(
opacity: 0;
}
.row:hover .act,
.row:hover .remove,
.row:focus-within .act,
.row:focus-within .remove,
.row.active .act,
.row.active .remove {
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 {
flex: 1;
min-width: 0;
@@ -1,9 +1,7 @@
<script setup lang="ts">
// 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
// 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.
// stream; code and file download on click.
import type { AttachmentCard } from '~/composables/useTranscript'
defineProps<{ attachment: AttachmentCard }>()
@@ -37,6 +35,7 @@ function formatBytes(size: number): string {
<span class="attachment-name mono">{{ attachment.name }}</span>
<span class="attachment-size mono">{{ formatBytes(attachment.size) }}</span>
<button
v-if="attachment.media !== 'image'"
class="ghost"
:title="`download ${attachment.name}`"
@click="emit('download', attachment.id, attachment.name)"
@@ -14,9 +14,6 @@ const routes = [
{ method: 'GET', path: '/v1/sessions', note: 'the dispatch-key inventory' },
{ 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: '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: '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)' },
@@ -24,7 +24,6 @@ const emit = defineEmits<{
// The draft: '' means "clear this field", matching the wire.
const draft = ref<IdentityTexts>({
name: '',
email: '',
mark: '',
initials: '',
tagline: '',
@@ -36,7 +35,6 @@ const dirty = computed(() => {
if (!identity) return false
return (
draft.value.name !== (identity.name ?? '') ||
draft.value.email !== (identity.email ?? '') ||
draft.value.mark !== (identity.mark ?? '') ||
draft.value.initials !== (identity.initials ?? '') ||
draft.value.tagline !== (identity.tagline ?? '') ||
@@ -49,7 +47,6 @@ function discard(): void {
if (!identity) return
draft.value = {
name: identity.name ?? '',
email: identity.email ?? '',
mark: identity.mark ?? '',
initials: identity.initials ?? '',
tagline: identity.tagline ?? '',
@@ -69,7 +66,6 @@ watch(
initialized.value = true
draft.value = {
name: identity.name ?? '',
email: identity.email ?? '',
mark: identity.mark ?? '',
initials: identity.initials ?? '',
tagline: identity.tagline ?? '',
@@ -101,7 +97,6 @@ function onImageChosen(kind: AgentImageKind, event: Event): void {
const CAPS: Record<keyof IdentityTexts, number> = {
name: 64,
email: 120,
mark: 8,
initials: 4,
tagline: 120,
@@ -147,7 +142,7 @@ const CAPS: Record<keyof IdentityTexts, number> = {
<SettingCard v-if="identity" title="Agent identity">
<SettingRow
title="Display name"
description="Shown as the author of messages, in the window title, in notifications, and as the author name on commits in workspaces."
description="Shown as the author of messages, in the window title, and in notifications."
>
<input
v-model="draft.name"
@@ -158,19 +153,6 @@ const CAPS: Record<keyof IdentityTexts, number> = {
:disabled="saving"
/>
</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
title="Mark"
description="The glyph or emoji in the rail and the empty states. Defaults to ῥ."
@@ -18,39 +18,20 @@ const kind = ref<SandboxKind>('local')
const url = ref('')
const token = ref('')
const clearToken = ref(false)
const host = ref('')
const workspace = ref('')
const privateKey = ref('')
const clearPrivateKey = ref(false)
const dirty = computed(() => {
const state = props.state
if (!state) return false
if (kind.value !== state.kind) return true
if (kind.value === 'http') {
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
}
if (kind.value === 'ssh') {
if (host.value.trim() !== (state.host ?? '')) return true
if (workspace.value.trim() !== (state.ssh_workspace ?? '')) return true
return privateKey.value.trim() !== '' || clearPrivateKey.value
}
return false
if (kind.value !== 'http') return false
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const 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 ready = computed(() => kind.value !== 'http' || urlValid.value)
const urlHint = computed(() =>
url.value.trim() && !urlValid.value
@@ -58,12 +39,6 @@ const urlHint = computed(() =>
: 'The sandboxd base URL, for example https://box.example:7600.',
)
const hostHint = computed(() =>
host.value.trim() && !hostValid.value
? 'One destination, no spaces: an alias or user@host your ssh config resolves.'
: 'An alias or user@host your ssh config resolves.',
)
function sync(): void {
const state = props.state
if (!state) return
@@ -71,10 +46,6 @@ function sync(): void {
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? ''
privateKey.value = ''
clearPrivateKey.value = false
}
watch(
@@ -100,15 +71,6 @@ function save(): void {
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)
}
@@ -116,9 +78,7 @@ function save(): void {
const workspacePath = computed(() => {
const state = props.state
if (!state) return ''
if (kind.value === 'local') return state.local_workspace
if (kind.value === 'http') return state.remote_workspace
return state.workspace
return kind.value === 'http' ? state.remote_workspace : state.local_workspace
})
</script>
@@ -163,74 +123,6 @@ const workspacePath = computed(() => {
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'ssh' }">
<input v-model="kind" type="radio" value="ssh" :disabled="saving" />
<span class="option-text">
<span class="option-title">
SSH host
<span v-if="state.kind === 'ssh'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a box the claw reaches with ssh, nothing installed on the far end.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'ssh'" title="SSH host">
<SettingRow title="Destination" :description="hostHint">
<input
v-model="host"
type="text"
class="mono"
placeholder="me@box.example"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Workspace base"
description="The remote directory the claw's workspaces live under. Defaults to /root."
>
<input
v-model="workspace"
type="text"
class="mono"
placeholder="/root"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Private key"
:description="state.private_key_set
? 'A key is stored. Leave this blank to keep it, or paste a replacement.'
: 'The key text itself (OpenSSH or PEM), not a path: the claw stores it, it stages no file. Leave blank to authenticate through an agent or the default key files.'"
>
<textarea
v-model="privateKey"
class="mono key-input"
rows="3"
:placeholder="state.private_key_set ? 'stored' : '-----BEGIN OPENSSH PRIVATE KEY-----'"
autocomplete="off"
spellcheck="false"
:disabled="saving || clearPrivateKey"
/>
</SettingRow>
<SettingRow
v-if="state.private_key_set"
title="Stored key"
:description="clearPrivateKey
? 'The stored key is removed when you save.'
: 'The key stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearPrivateKey = !clearPrivateKey">
{{ clearPrivateKey ? 'Keep key' : 'Forget key' }}
</button>
</SettingRow>
</SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
@@ -275,7 +167,7 @@ const workspacePath = computed(() => {
</SettingRow>
</SettingCard>
<AppCallout v-if="kind !== 'local'" variant="info" title="Remote commands start from a copy">
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy">
On first use the claw sends the local workspace to the sandbox as a tarball.
Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout>
@@ -364,12 +256,4 @@ const workspacePath = computed(() => {
font-size: 12px;
font-weight: 500;
}
.key-input {
width: 100%;
min-width: 0;
resize: vertical;
font-size: 12px;
word-break: break-all;
}
</style>
+11 -82
View File
@@ -95,17 +95,6 @@ export interface ClawSession {
revision: number
inbox_depth: number
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). */
@@ -203,7 +192,6 @@ export interface ProvidersState {
* unset text fields read as null, the images report presence. */
export interface AgentIdentity {
name: string | null
email: string | null
mark: string | null
initials: string | null
tagline: string | null
@@ -216,7 +204,6 @@ export interface AgentIdentity {
* string clears the field. */
export interface IdentityTexts {
name: string
email: string
mark: string
initials: string
tagline: string
@@ -244,9 +231,9 @@ export interface ActiveBackend {
active: { provider: string; model: string }
}
/** Where the agent's `bash` runs: this host, a daemon speaking the
* sandbox protocol over HTTP, or an ssh login on a far box. */
export type SandboxKind = 'local' | 'http' | 'ssh'
/** Where the agent's `bash` runs: this host or a daemon speaking the
* sandbox protocol over HTTP. */
export type SandboxKind = 'local' | 'http'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */
@@ -254,15 +241,6 @@ export interface SandboxState {
kind: SandboxKind
url: string | null
token_set: boolean
/** Whether an ssh private key is stored; the key itself never
* rides the wire. */
private_key_set: boolean
/** The ssh destination, an alias or `user@host` the local ssh
* config resolves. */
host: string | null
/** The ssh workspace base the workspaces sit under, `null` for the
* default. */
ssh_workspace: string | null
/** Where `bash` starts under the current choice. */
workspace: string
/** The daemon's chat workspace, whatever the choice. */
@@ -279,14 +257,6 @@ export interface SandboxSelection {
url?: string
token?: string
clear_token?: boolean
host?: string
/** The ssh private key text (no file): the store-held credential.
* Write-only, like the token. */
private_key?: string
clear_private_key?: boolean
/** The ssh workspace base; the per-workspace directories land under
* it. An omitted value keeps the current one. */
workspace?: string
}
/** A failed API call: the status plus the claw's `error` string when it sent one. */
@@ -319,13 +289,12 @@ export function isInteractive(key: string): boolean {
return key.startsWith(INTERACTIVE_PREFIX)
}
/** The prefixes the daemon's resident context owns: its
* `is_resident_key` (`crates/rhema-claw/src/interactive.rs`). A resident
* key has a live turn record the event stream follows. Every other key
* in the inventory — a forge thread, a coding job — answers no stream
* and takes no message: its history route serves the snapshot the
* engine checkpointed, and the panel renders it read-only. */
const RESIDENT_PREFIXES = ['interactive:', 'task:', 'phone:', 'calendar:']
/** The prefixes the chat surface answers for: the daemon's
* `is_resident_key` (`crates/rhema-claw/src/interactive.rs`). Every other
* key in the inventory — `phone:` status reporting, `job:<instance>#<id>`,
* a forge thread — has no transcript: the message, event and history
* routes 400 on it. */
const RESIDENT_PREFIXES = ['interactive:', 'task:', 'calendar:']
/** Whether `key` is one the transcript surface can open. */
export function isResidentKey(key: string): boolean {
@@ -415,9 +384,6 @@ export interface StreamHandlers {
export interface HistoryPage {
events: { seq: number; event: TurnEvent }[]
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 {
@@ -431,14 +397,6 @@ export interface ClawApi {
* same name starts empty. 409 while a turn holds the key, 404 when it is
* already gone. */
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. */
listConsents(): Promise<ConsentRequest[]>
/** `POST /v1/consents/{id}` — answer one consent; 409 when already
@@ -515,7 +473,6 @@ export interface ClawApi {
* `GET /v1/sessions/{key}/history` — one page of whole turns ending
* at `before` (absent: the newest). Pages stack: the next call passes
* 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>
}
@@ -567,27 +524,6 @@ 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[]> {
const body = (await get('/v1/consents', token.value)) as { consents: ConsentRequest[] }
return body.consents
@@ -636,11 +572,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const body = (await get(
`/v1/sessions/${encodeURIComponent(key)}/history${query}`,
token.value,
)) as {
events?: { seq?: unknown; event?: unknown }[]
more?: unknown
read_only?: unknown
}
)) as { events?: { seq?: unknown; event?: unknown }[]; more?: unknown }
// 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
// still renders what it could read.
@@ -648,7 +580,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const event = parseTurnEvent(JSON.stringify(entry.event))
return event && typeof entry.seq === 'number' ? [{ seq: entry.seq, event }] : []
})
return { events, more: body.more === true, readOnly: body.read_only === true }
return { events, more: body.more === true }
}
async function providers(): Promise<ProvidersState> {
@@ -915,9 +847,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
sessions,
createSession,
deleteSession,
pauseSession,
resumeSession,
abortSession,
listConsents,
resolveConsent,
denyConsent,
+32 -29
View File
@@ -409,42 +409,41 @@ export function useTranscript() {
if (pending !== -1) pendingSent.splice(pending, 1)
}
/** The cards on the mirror, at either depth. A card lands in the open
* turn's entries and rides into the finished turn with it, so a scan
* of the top-level rows alone misses everything a turn handed over.
* The returned objects are the mirror's own, not copies: flipping one
* flips what the panel renders. */
function cards(): TurnEntry[] {
const found: TurnEntry[] = [...(live.value?.entries ?? [])]
for (const item of items.value) {
if (item.kind === 'consent' || item.kind === 'attachment') {
found.push(item)
} else if (item.kind === 'turn') {
found.push(...item.turn.entries)
/** A consent card resolved: flipped in place, or ignored when no
* card carries the id. The in-flight turn's entries hold the cards a
* running turn asked for; finished turns keep their own copies. */
function resolveConsent(id: string, granted: boolean): void {
if (live.value) {
for (const entry of live.value.entries) {
if (entry.kind === 'consent' && entry.consent.id === id) {
entry.consent.granted = granted
return
}
}
}
return found
}
/** 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
for (const item of items.value) {
if (item.kind === 'consent' && item.consent.id === id) {
item.consent.granted = granted
return
}
}
}
/** 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
/** An attachment's object URL landed; stored on its card. The useClaw
* cache keeps a reconnect's replay from refetching the bytes. */
function setAttachmentUrl(id: string, url: string): void {
for (const card of cards()) {
if (card.kind === 'attachment' && card.attachment.id === id) {
card.attachment.url = url
if (live.value) {
for (const entry of live.value.entries) {
if (entry.kind === 'attachment' && entry.attachment.id === id) {
entry.attachment.url = url
return
}
}
}
for (const item of items.value) {
if (item.kind === 'attachment' && item.attachment.id === id) {
item.attachment.url = url
return
}
}
}
@@ -467,12 +466,16 @@ export function useTranscript() {
/** Whether a card for this consent id is already on the mirror — a
* replayed request never stacks a second card beside the first. */
function findConsent(id: string): boolean {
return cards().some((card) => card.kind === 'consent' && card.consent.id === id)
if (live.value?.entries.some((e) => e.kind === 'consent' && e.consent.id === id)) return true
return items.value.some((item) => item.kind === 'consent' && item.consent.id === id)
}
/** Whether a card for this attachment id is already on the mirror. */
function findAttachment(id: string): boolean {
return cards().some((card) => card.kind === 'attachment' && card.attachment.id === id)
if (live.value?.entries.some((e) => e.kind === 'attachment' && e.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
+1923 -1118
View File
File diff suppressed because it is too large. Load diff