Author SHA1 Message Date
kosmos ae198c6f26 fix(daemon): run the long lanes off the tick path
`tick` awaited `forge_driver.run_once()` (and the jobs one before it), and
`Driver::run_once` awaits every run it admits. So while a turn was under
way the loop stopped doing everything else: no forge poll, no watch
health, no due task, no calendar reminder, no phone delivery. With a 60s
poll interval and a ten-minute turn, the daemon polled once per turn —
which is why `last_ok_at` sat frozen at 00:35:02 while the turn that
started at 00:35:03 ran. Not a network problem, and not the watch.

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

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

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

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

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

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

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

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

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

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

So consume what the poll decides:

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

Gitea and GitLab keep the no-op: neither has an account watch here yet.
2026-11-22 01:34:11 +00:00
kosmos 78fdec4f49 fix(daemon): lease a forge turn for an hour, not ten minutes
The forge dispatcher was assembled on `DispatcherConfig::default()`,
whose ten-minute lease TTL is the spec's example value, sized for a
single agent step. A forge turn is not a step: it clones the repo, reads
it, and may build and test a fix. Nothing renews the lease once the turn
is under way — `poll_inbox` renews but is called once, at the start, and
the commit hook between tool calls checkpoints, which fails on a lapsed
lease rather than extending it — so the TTL is a hard ceiling on a whole
turn.

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

Give the forge lane its own timing — the library defaults with an
hour-long TTL, the same choice the interactive and jobs lanes already
make — and use it in both shapes (`--once` included).
2026-11-22 01:13:40 +00:00
kosmos c65f7fe962 fix(forge): read a GitHub notification id as a string or a number
The notifications feed sends `id` as a JSON string (`"27210544329"`),
unlike every other row this adapter decodes, so `WireNotification`'s
`Option<i64>` refused one real row and failed the whole page. The account
watch has been stuck on 'error decoding response body' since the first
notification arrived (82 consecutive failures at the time of writing).

`lenient_id` accepts either shape; a non-numeric string is still a loud
parse error rather than a dropped row. The regression test is the row
captured live.
2026-11-22 00:01:01 +00:00
kosmos 9c13455f35 feat(claw): a mention of the daemon is an ask, not a phone buzz
The notifications feed triaged a GitHub `mention` as `Triage::Surface`:
the human hears about it, no agent runs. That verdict is right for a
consumer that only notifies — a mention of somebody else is not an
assignment — but this daemon is the party named. Somebody typed
`@handle` on a thread and is waiting for an answer, which is the same
ask an assignment is.

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

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

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

Verified as CI does (assembleDebug, lintDebug) plus a JVM harness
running the verbatim slicing code against the daemon's own e2e record
numbers, surrogates and seams included.
2026-11-20 01:18:49 +01:00
vhaudiquet c5bf168eed feat: chips travel as span records, not mark embeds
The claw's wire carried chips only as U+FFFC-payload-U+FFFC marks
written into the text — the very encoding 0.4.0's fold migrated at
the provider seam. Now the record rhema-core defined is the wire's
own: a message's pasted payloads ride the POST body's `pastes` array
beside the plain draft, the fold composes the plain form and measures
each chip's PasteSpan, and the `user_message` echo carries text plus
`pastes` — the session annotation's own shape — while the turn's
question carries the span note into the checkpoint, shifted by the
exact bytes any framing prefix adds.

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

The phone is one of those: it parses chips by scanning marks, and
kotlinx ignores the new field, so it reads spans-less rows exactly
as before; adopting span records for its own rows is a follow-up.
2026-11-20 00:41:41 +01:00
vhaudiquet df260fd9a8 build: move the claw to rhema 0.4.0
The framework 0.4.0 split the toolkit: rhema-agent-tools becomes
rhema-bash plus rhema-prompt, and the facade crate is deleted from
the workspace this time, so the 0.3 facades never publish. The
driver changes name with its types: rhema-coding-agent and its
CodingAgent, CodingAgentConfig, and CodingAgentError become
rhema-host-agent with HostAgent, HostAgentConfig, and HostAgentError.
The claw imports the split crates directly, which drops its own
vision once-lock: rhema-bash's wire already caches the process-wide
answer.

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

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

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

fmt, clippy with -D warnings over all features and targets, the
workspace tests, and the doc build pass.
2026-11-19 23:25:16 +01:00
vhaudiquet ed645d1faf fix(web/claw): keep the stream watchdog quiet on a tab switch
A hidden tab throttles timers and can stall the SSE reader. The 45s
silence watchdog kept counting that time, aborted the stream, and pushed
"the event stream went quiet" on every tab switch even though the
connection was fine.

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

Tested in headless Chromium against the dev mock: 50s hidden, then
visible, no notice, and the stream went back to live.
2026-11-18 23:59:01 +01:00
vhaudiquet 51456f5b4c build: bump the chart base version past the 0.2.3 release
CI publishes every main push as a timestamped pre-release of the chart's
base version. The base stayed at 0.1.0 through the 0.3.0 framework move,
but the package repository also holds a 0.2.3 chart from the old release
line. SemVer ranks 0.2.3 above every 0.1.0 pre-release, so a HelmRelease
with `>=0.1.0-0` resolves to 0.2.3 and never sees a newer edge chart.

The base is 0.3.0 now, matching the workspace version. Edge charts sort
above 0.2.3 again, and the release tag check already expects 0.3.0.
2026-11-18 21:54:19 +01:00
vhaudiquet ea4810a576 feat(claw): choose where bash runs, this host or a remote sandbox
The daemon's `bash` always ran on its own host. A deployment that wants
the shell isolated, or on a machine with the project's toolchain, had no
way to say so, and the web settings had no surface for it.

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

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

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

Tests: the sandbox state and config validation, the HTTP route round
trip, and a remote turn that seeds a fresh sandbox and runs its shell
there. fmt, clippy with -D warnings, the workspace tests, and the web
typecheck and build pass.
2026-11-18 21:00:50 +01:00
vhaudiquet 68671c76ce build: move the claw to rhema 0.3.0
The framework releases 0.3.0, so every rhema dependency moves with it: the workspace version, the daemon's crates, and the two integrations. The only new transitive package is webpki-roots, pulled by the provider crates' TLS stack.

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

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

fmt, clippy with -D warnings, the workspace tests, and a locked check pass.
2026-11-18 20:25:22 +01:00
vhaudiquet c56f544993 feat(web/claw): render the reply, not the tool calls or the thinking
The web transcript was built to mirror the TUI: every tool call as a
shell line or a glyph row, the thinking trace between them, each at the
position the stream delivered it. That is the right shape for a
terminal session you sit and watch. On the web it reads as machinery in
front of the answer, and the answer is what the page is for.

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

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

`TurnToolRow` had no other caller and goes with it.
2026-11-17 23:37:27 +01:00
vhaudiquet 268917646e docs: add the tools spec, carried from the rhema repository
The spec describes this tree now: ClawExtension, the tools/ project
(contract, common, notify), the daemon's axum router. It stayed
behind when the claw cut loose, and a design record belongs beside
its subject.
2026-11-17 23:16:41 +01:00
53 changed files with 4012 additions and 494 deletions

No files matched your search

+1
View File
@@ -1 +1,2 @@
/target/
.rhema/
Generated
+356 -85
View File
@@ -411,6 +411,23 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core 0.10.1",
]
[[package]]
name = "cipher"
version = "0.5.2"
@@ -893,8 +910,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
@@ -904,8 +923,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi",
"rand_core 0.10.1",
"wasm-bindgen",
]
[[package]]
@@ -1079,6 +1101,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]]
@@ -1338,6 +1361,12 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "lru-slab"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "matchit"
version = "0.8.4"
@@ -1672,6 +1701,62 @@ dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2",
"thiserror",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
dependencies = [
"bytes",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.4",
"rand_pcg",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -1695,7 +1780,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"chacha20",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
[[package]]
@@ -1705,7 +1801,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -1717,6 +1813,21 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_pcg"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "regex"
version = "1.13.1"
@@ -1771,6 +1882,8 @@ dependencies = [
"native-tls",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
@@ -1778,6 +1891,7 @@ dependencies = [
"sync_wrapper",
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -1787,30 +1901,14 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
]
[[package]]
name = "rhema-agent-tools"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "839fa542e680de80f25876d6f54ea45dbace72a89d5f63f52c4423e54f048f82"
dependencies = [
"async-trait",
"base64 0.22.1",
"minijinja",
"rhema-core",
"serde",
"serde_json",
"serde_yaml",
"thiserror",
"tokio",
"webpki-roots",
]
[[package]]
name = "rhema-autonomous-agent"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e3ee50c812fa93f31be669557cb642ed8d03154613234b2090fa9567374516e"
checksum = "46677fb855ebb628da602111fa2595ad363401c7101c07f07a602dbc86a1dd8a"
dependencies = [
"async-trait",
"rhema-core",
@@ -1822,9 +1920,25 @@ dependencies = [
"tokio",
]
[[package]]
name = "rhema-bash"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0aacc9aac461f674ec7f72dc321b11edc4c7868d3c635c2b1c58dbd9256c80"
dependencies = [
"async-trait",
"base64 0.22.1",
"rhema-core",
"rhema-submissions",
"serde",
"serde_json",
"thiserror",
"tokio",
]
[[package]]
name = "rhema-calendar-integration"
version = "0.2.3"
version = "0.4.0"
dependencies = [
"async-trait",
"quick-xml",
@@ -1843,27 +1957,32 @@ dependencies = [
[[package]]
name = "rhema-claw"
version = "0.2.3"
version = "0.4.0"
dependencies = [
"async-trait",
"axum",
"base64 0.22.1",
"bytes",
"clap",
"reqwest",
"rhema-agent-tools",
"rhema-autonomous-agent",
"rhema-bash",
"rhema-calendar-integration",
"rhema-claw-tools-contract",
"rhema-coding-agent",
"rhema-config",
"rhema-core",
"rhema-forge-integration",
"rhema-host-agent",
"rhema-identity",
"rhema-mcp",
"rhema-memory",
"rhema-prompt",
"rhema-provider",
"rhema-provider-registry",
"rhema-rsd",
"rhema-sandbox",
"rhema-sandbox-http",
"rhema-sandbox-ssh",
"rhema-transcript",
"rusqlite",
"serde",
@@ -1879,7 +1998,7 @@ dependencies = [
[[package]]
name = "rhema-claw-tools-contract"
version = "0.2.3"
version = "0.4.0"
dependencies = [
"serde",
"serde_json",
@@ -1887,40 +2006,24 @@ dependencies = [
]
[[package]]
name = "rhema-coding-agent"
version = "0.2.3"
name = "rhema-config"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b5ef3b970ced4f05b4d18b9df56ca6a46bb488af7579f8d3c4a10788ca47761"
checksum = "0a05d1d30472d7ea03685806b69e0e9984744b0349cc7c7ad53497916b6c2be1"
dependencies = [
"minijinja",
"rhema-agent-tools",
"rhema-config",
"keyring",
"rhema-core",
"rhema-transcript",
"serde",
"serde_json",
"serde_yaml",
"thiserror",
]
[[package]]
name = "rhema-config"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efd98e6c5dd53a6e30367ae4c259ea03e5d214962aae9c1d66ab03f464487988"
dependencies = [
"keyring",
"rhema-core",
"serde",
"serde_yaml",
"thiserror",
]
[[package]]
name = "rhema-core"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b399005d398dd0dca791415a07f6280bacebc0aedfa84f9d3a29640f45f91144"
checksum = "de9d3c12019209170cbf82fa75dcad4ec10c3c712f7235d9f9a60f165cab5d8c"
dependencies = [
"async-trait",
"serde",
@@ -1930,7 +2033,7 @@ dependencies = [
[[package]]
name = "rhema-forge-integration"
version = "0.2.3"
version = "0.4.0"
dependencies = [
"async-trait",
"reqwest",
@@ -1943,10 +2046,30 @@ dependencies = [
]
[[package]]
name = "rhema-identity"
version = "0.2.3"
name = "rhema-host-agent"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f9355d075f5ff5800f9b6b4216e65ba087f681716bc0faf69986852eb13be26"
checksum = "973dc8ee54a24065c7996b23e0cfd2eba715687394a248583582faca3d7a5c4c"
dependencies = [
"minijinja",
"rhema-bash",
"rhema-config",
"rhema-core",
"rhema-prompt",
"rhema-session-store",
"rhema-session-store-file",
"rhema-transcript",
"serde",
"serde_json",
"serde_yaml",
"thiserror",
]
[[package]]
name = "rhema-identity"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3188f0fec1338df315c76034909e8ff7c1314a84ff6dd0ac11793d605d655b5b"
dependencies = [
"rusqlite",
"serde",
@@ -1955,9 +2078,9 @@ dependencies = [
[[package]]
name = "rhema-mcp"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efb7dff3b33b3931c9da4ea6577e55f41c820cf5b2b880b06b8581f15673e06e"
checksum = "0dd8f9ee0b0699c09efb303dfc17ed3049aabc8a7b3e01d211de283c43c8c19b"
dependencies = [
"async-stream",
"axum",
@@ -1967,10 +2090,12 @@ dependencies = [
"futures-util",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"mcp-to-cli",
"rhema-agent-tools",
"rhema-bash",
"rhema-config",
"rhema-prompt",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1980,9 +2105,9 @@ dependencies = [
[[package]]
name = "rhema-memory"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5a0f161c473ae19dc161a1ad898603150ec6be081f24262182e15ea348db3b5"
checksum = "abdfee3e709305e86cedc3e60ca59776af512b2bf520ab87d7da1d184f01d560"
dependencies = [
"async-trait",
"rhema-core",
@@ -1993,13 +2118,27 @@ dependencies = [
]
[[package]]
name = "rhema-provider"
version = "0.2.3"
name = "rhema-prompt"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d178053a9d5400cf001109670f2294e427ded6cb895b235b4f4ffc2bc20f2f09"
checksum = "2ecbf1ae5d134d110c8f3b4c47ad2331f703bd7bb1ad6d53b4108787d894c8bd"
dependencies = [
"minijinja",
"rhema-core",
"serde",
"serde_json",
"serde_yaml",
]
[[package]]
name = "rhema-provider"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15855c3fa2d858622cd55bd6323d4a7533066e52a74e3dc440ffe69c12ed1263"
dependencies = [
"async-trait",
"futures-core",
"reqwest",
"rhema-core",
"serde",
"serde_json",
@@ -2009,9 +2148,9 @@ dependencies = [
[[package]]
name = "rhema-provider-anthropic"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc26ff01350bab0fb10a53fc11665dca939c3fda2ec1a3df93912a39b3fc8b0c"
checksum = "223a60c52ce2e548f72a9f2cce6f7a48be954bd3e5b959ff70d308b3d42d6425"
dependencies = [
"async-trait",
"futures-util",
@@ -2025,14 +2164,14 @@ dependencies = [
[[package]]
name = "rhema-provider-chatgpt"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb807b39e95c49d2a5e8c101220ac34a9d6770aece6bece1eebcf8113b1811a2"
checksum = "ec84f3f5601e8ca6e69f92a291480842058352bb580b985ec23db713505b8f5d"
dependencies = [
"async-trait",
"base64 0.22.1",
"futures-util",
"rand",
"rand 0.8.8",
"reqwest",
"rhema-core",
"rhema-provider",
@@ -2044,15 +2183,16 @@ dependencies = [
[[package]]
name = "rhema-provider-copilot"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98cc6f041cb328de999c17abc34d3e050d586a2390d32ec9ae5fa543bd177fa0"
checksum = "c6685a56017c7de21d17384d25f941f2733526d581dfafc5cd7371d4f6e82096"
dependencies = [
"async-trait",
"futures-util",
"reqwest",
"rhema-core",
"rhema-provider",
"rhema-provider-anthropic",
"rhema-provider-openai-compatible",
"serde",
"serde_json",
@@ -2062,9 +2202,9 @@ dependencies = [
[[package]]
name = "rhema-provider-google"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99cbbb477a94d995b09a3154288a0f5f10aee22fd35bc1d1145bbffee27ea388"
checksum = "749f27fcf2ad1c7745cabc85e56d05e116bce30b6be317910f0c455ba4147ff9"
dependencies = [
"async-trait",
"futures-util",
@@ -2078,9 +2218,9 @@ dependencies = [
[[package]]
name = "rhema-provider-llama-cpp"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e3491fcb305e448492868473c6a146575174bdbb7ab328c85bf43a698052f56"
checksum = "bf5d26ec681baac6b8c6fc752470a78205acb11f763987bf571fa54be1195e2a"
dependencies = [
"async-trait",
"futures-util",
@@ -2094,10 +2234,29 @@ dependencies = [
]
[[package]]
name = "rhema-provider-openai-compatible"
version = "0.2.3"
name = "rhema-provider-mistral"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98976f2fd5f8f09e5838405f53e2b9f113a5e9d2ed3823a80117f4919f0249a6"
checksum = "4d8ae3c2c924202d3614987b6b7c4930d84a19ebb2264747bb5100f1f67db7ff"
dependencies = [
"async-trait",
"base64 0.22.1",
"rand 0.8.8",
"reqwest",
"rhema-core",
"rhema-provider",
"rhema-provider-openai-compatible",
"serde",
"serde_json",
"sha2 0.10.9",
"tokio",
]
[[package]]
name = "rhema-provider-openai-compatible"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aab0c24d2d558d66de1f002c250d05c25d9c52038e4fa1890f6c40644c4f9702"
dependencies = [
"async-trait",
"futures-util",
@@ -2111,9 +2270,9 @@ dependencies = [
[[package]]
name = "rhema-provider-opencode"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f6cc7db60525e63712ec2b66881cd57f3bb7b7b8c14001eebf86f64030302a"
checksum = "3eb4c641b7997ba5cab41bede6c4b7331baa9a9b2298d5bb0ffbc8844df6dbf3"
dependencies = [
"async-trait",
"reqwest",
@@ -2126,9 +2285,9 @@ dependencies = [
[[package]]
name = "rhema-provider-openrouter"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ca68e90f9627c58e0908e52e010bd7c47e498290c40358c2ff326e95a9a20cc"
checksum = "7170cef8b456c8f1df1b565d16ad3c61c4b252e521fff16718eacca5d7d98605"
dependencies = [
"async-trait",
"futures-util",
@@ -2142,9 +2301,9 @@ dependencies = [
[[package]]
name = "rhema-provider-registry"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8f6b0b10943f6fa4272490acc3c33040944d85490971a8a1acc8515d704bfc2"
checksum = "c93ceacbe2332f122b23a11de11ddf4a502a96baaa8c95f33882c5c589581dce"
dependencies = [
"rhema-core",
"rhema-provider",
@@ -2153,6 +2312,7 @@ dependencies = [
"rhema-provider-copilot",
"rhema-provider-google",
"rhema-provider-llama-cpp",
"rhema-provider-mistral",
"rhema-provider-openai-compatible",
"rhema-provider-opencode",
"rhema-provider-openrouter",
@@ -2161,9 +2321,9 @@ dependencies = [
[[package]]
name = "rhema-rsd"
version = "0.2.3"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1e05417b86144a2a0dbad3018a73c0b2376b5fec378676aea6b912678b059f6"
checksum = "8e97a9d363b432147220a0646a158ea7a08d6012efa1bedf169fd973721dd745"
dependencies = [
"rhema-core",
"rusqlite",
@@ -2173,10 +2333,88 @@ dependencies = [
]
[[package]]
name = "rhema-transcript"
version = "0.2.3"
name = "rhema-sandbox"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b00234b8879bd894f0a45a1fd804c94c7cc3d31ea9f5361609041cb42587a719"
checksum = "3d5aaa76f2400989439f325754a29593669c1275485796150e19b04277ea54fb"
dependencies = [
"async-trait",
"rhema-bash",
"rhema-core",
"serde",
"serde_json",
"thiserror",
"tokio",
]
[[package]]
name = "rhema-sandbox-http"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f4cbb9f2238961082a8b406da460c84ced75f4d6bb9e52a79b41dc17065b601"
dependencies = [
"async-trait",
"base64 0.22.1",
"reqwest",
"rhema-sandbox",
"serde",
"serde_json",
]
[[package]]
name = "rhema-sandbox-ssh"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578252c65b6e8047b8f013d2d0a0bd867991b50ed31a530cdfa1304d158a6e65"
dependencies = [
"async-trait",
"base64 0.22.1",
"rhema-sandbox",
"tokio",
]
[[package]]
name = "rhema-session-store"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00548f40bf2ec40381d4f9d60a1e136c66d7c4c334097a5eebafe21169915f5c"
dependencies = [
"rhema-core",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "rhema-session-store-file"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df75d21d1ad25b16cb72fc3747d435415e7423872b51fa3751094a5a6e380543"
dependencies = [
"rhema-config",
"rhema-core",
"rhema-session-store",
"serde_json",
]
[[package]]
name = "rhema-submissions"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dba11599010c7537800bee275dd9d414162dd57806b1d75c54ef98f126eb9f65"
dependencies = [
"rhema-core",
"rhema-session-store",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "rhema-transcript"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "592b80da0bf1c84e4da814639383dc33c5d2eeee522db5bd93bb779bf0e34e10"
dependencies = [
"async-trait",
"rhema-core",
@@ -2224,6 +2462,12 @@ dependencies = [
"sqlite-wasm-rs",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustix"
version = "1.1.6"
@@ -2244,6 +2488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
@@ -2256,6 +2501,7 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"web-time",
"zeroize",
]
@@ -2661,6 +2907,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
version = "1.54.1"
@@ -3032,6 +3284,25 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "windows-link"
version = "0.2.1"
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*", "integrations/*"]
[workspace.package]
version = "0.2.3"
version = "0.4.0"
edition = "2024"
rust-version = "1.89"
license = "MIT"
+1 -1
View File
@@ -11,7 +11,7 @@ surface over HTTP — native routes plus an OpenAI-compatible shim,
with a web UI and an Android client talking to it.
The framework it embeds (the crates under `crates/` it pulls from
crates.io: `rhema-autonomous-agent`, `rhema-coding-agent`,
crates.io: `rhema-autonomous-agent`, `rhema-host-agent`,
`rhema-rsd`, and friends) lives in the
[rhema repository](https://git.vhaudiquet.fr/vhaudiquet/rhema).
+5 -2
View File
@@ -77,8 +77,11 @@ manages the device fleet the claw keeps.
**subscribe first, then POST**, the reply arrives on the stream. Thinking
deltas render dim and collapsible, tool rows show name/summary with error
coloring (bash-like tools render as shell lines instead: dim `$` prefix,
the command line, and an exit-code badge), pasted payloads embedded in a
message as paired `U+FFFC` marks render as compact `▣N 5L` chips, and
the command line, and an exit-code badge), a message's paste chips render
as compact `▣N 5L` labels sliced from the span record its
`user_message` carries beside the plain text (rows recorded before
spans rode the stream still scan the legacy paired-`U+FFFC` form in
the text), and
`attachment` events render as cards: file name, size, caption, an inline
preview for small (≤ 2 MB) images, and a download-and-open row (bytes
from `GET /v1/attachments/{id}` land in the app cache and open through a
@@ -11,6 +11,7 @@ import rs.rhema.phone.net.ClawApi
import rs.rhema.phone.net.ClawEvent
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.OutboundImage
import rs.rhema.phone.net.PasteSpan
import rs.rhema.phone.net.SseFrame
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -61,6 +62,10 @@ class ChatController(
override val id: Long,
val text: String,
val images: List<SentImage> = emptyList(),
// The chip record this surface's rows never carry (its
// composer sends plain text) but a replayed row — a web user's
// chips in this conversation — does; the render slices on it.
val pastes: List<PasteSpan> = emptyList(),
) : Item
data class Thinking(override val id: Long, val text: String) : Item
data class ToolCall(
@@ -355,14 +360,15 @@ class ChatController(
is ClawEvent.UserMessage -> {
// The recorded question — replayed on reload, echoed live
// for a message this surface just sent. An identical last
// row — same text, same image count — is that echo's
// stand-in; skip it, previews and all.
// row — same text, same image count, same chip record —
// is that echo's stand-in; skip it, previews and all.
val last = list.lastOrNull()
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size)) {
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size && last.pastes == event.pastes)) {
list = list + UserMessage(
newId(),
event.text,
event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) },
event.pastes,
)
}
}
@@ -117,6 +117,13 @@ data class RhemaNotification(
@Serializable
data class UserImage(val id: String, @SerialName("media_type") val mediaType: String)
// One paste chip a user_message records: the byte span (UTF-8) of the
// payload in the message's plain text, plus the payload's line count
// — the session annotation's own shape (rhema-core `PasteSpan`), so a
// chip renders from the record instead of rebuilding the wire form.
@Serializable
data class PasteSpan(val start: Int = 0, val end: Int = 0, val lines: Int = 0)
// One event of GET /v1/sessions/{key}/history: the record's seq for it,
// beside the event itself. Seq order is the wire order.
@Serializable
@@ -138,11 +145,13 @@ data class HistoryPage(val events: List<HistoryEvent> = emptyList(), val more: B
sealed interface ClawEvent {
@Serializable
@SerialName("user_message")
// Rows recorded before images rode the stream carry no field at
// all; absent folds to none, never a guessed shape.
// Rows recorded before images — and then before chips — rode the
// stream carry no field at all; absent folds to none, never a
// guessed shape.
data class UserMessage(
val text: String = "",
val images: List<UserImage> = emptyList(),
val pastes: List<PasteSpan> = emptyList(),
) : ClawEvent
@Serializable
@@ -82,6 +82,7 @@ import rs.rhema.phone.chat.MAX_STAGED_IMAGES
import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PasteSpan
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
@@ -438,6 +439,7 @@ private sealed interface TurnGroup {
val id: Long,
val text: String,
val images: List<ChatController.SentImage>,
val pastes: List<PasteSpan> = emptyList(),
) : TurnGroup {
override val key: String = "u$id"
}
@@ -451,7 +453,7 @@ private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
val groups = mutableListOf<TurnGroup>()
for (item in items) {
when (item) {
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images)
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images, item.pastes)
else -> {
val last = groups.lastOrNull()
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item))
@@ -501,10 +503,13 @@ private fun TurnGroupRow(
}
}
}
// Embedded pastes render as chips, not payloads; the
// text around them stays verbatim.
// Chips render as chips, not payloads; the text
// around them stays verbatim. The row's chip record
// slices them out of the plain text; a row from
// before the record rode the stream carries none
// and still scans the mark form in the text.
var chip = 0
pasteParts(group.text).forEach { part ->
messageParts(group.text, group.pastes).forEach { part ->
when (part) {
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
is PastePart.Paste -> {
@@ -740,20 +745,67 @@ private fun PasteChip(label: String) {
)
}
// --- embedded pastes --------------------------------------------------
// The wire form a long paste travels in: MARK, payload, MARK — one
// logical unit inside otherwise plain text (rhema-core's paste module
// is the definition; these are its client-side shape). A mark with no
// partner is literal text.
// --- paste chips ------------------------------------------------------
// A long paste rides as a chip the render stands in for its payload.
// The record is the span list a user_message carries (the session
// annotation's own shape); the marks in the text are the record's
// legacy spelling, kept for rows that predate it — a mark with no
// partner is literal text (rhema-core's paste module is the
// definition; these are its client-side shape).
private const val PASTE_MARK = '\uFFFC'
/** One scanned piece of embedded-form text. */
/** One piece of a rendered message: literal text, or a chip standing
* for its payload. */
private sealed interface PastePart {
data class Text(val text: String) : PastePart
data class Paste(val payload: String) : PastePart
}
/** A message's parts. The chip record is the modern form — each span
* names the payload's byte range in the plain text — and rows recorded
* before it rode the stream carry none; those still scan the legacy
* mark form in the text itself. */
private fun messageParts(text: String, pastes: List<PasteSpan> = emptyList()): List<PastePart> =
if (pastes.isEmpty()) pasteParts(text) else spanParts(text, pastes)
/** Splits a record-carrying message into its parts, left to right. The
* spans' offsets are UTF-8 bytes, the plain form the fold measured —
* every character boundary is mapped in one walk, and a span that
* splits a character maps to none: the render skips it rather than cut
* one in half. Malformed input never throws. */
private fun spanParts(text: String, pastes: List<PasteSpan>): List<PastePart> {
var bytes = 0
var units = 0
val at = mutableMapOf(0 to 0)
var index = 0
while (index < text.length) {
val codePoint = text.codePointAt(index)
val width = Character.charCount(codePoint)
index += width
units = index
bytes += when {
codePoint < 0x80 -> 1
codePoint < 0x800 -> 2
codePoint < 0x10000 -> 3
else -> 4
}
at[bytes] = units
}
val parts = mutableListOf<PastePart>()
var cut = 0
for (span in pastes.sortedBy { it.start }) {
val start = at[span.start]
val end = at[span.end]
if (start == null || end == null || start < cut || end < start) continue
if (start > cut) parts += PastePart.Text(text.substring(cut, start))
parts += PastePart.Paste(text.substring(start, end))
cut = end
}
if (cut < text.length) parts += PastePart.Text(text.substring(cut))
return parts
}
/** Splits embedded-form text into its parts, left to right. A mark with
* no partner is literal text; malformed input never throws. */
private fun pasteParts(text: String): List<PastePart> {
+24 -14
View File
@@ -26,29 +26,37 @@ mock = ["rhema-core/mock"]
[dependencies]
# The shared toolkit: the resident agent assembles its agent from the
# shell, the approval seam, paste expansion, and revive-on-resume
rhema-agent-tools = "0.2.3"
rhema-autonomous-agent = "0.2.3"
rhema-coding-agent = "0.2.3"
rhema-config = "0.2.3"
rhema-core = "0.2.3"
# 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.1"
rhema-prompt = "0.4.1"
rhema-host-agent = "0.4.1"
rhema-autonomous-agent = "0.4.1"
rhema-config = "0.4.1"
rhema-core = "0.4.1"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.2.3"
rhema-transcript = "0.4.1"
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.2.3"
rhema-rsd = "0.2.3"
rhema-identity = "0.4.1"
rhema-rsd = "0.4.1"
# 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
rhema-sandbox = "0.4.1"
rhema-sandbox-http = "0.4.1"
rhema-sandbox-ssh = "0.4.1"
# 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.2.3"
rhema-memory = "0.4.1"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.2.3"
rhema-provider-registry = "0.2.3"
rhema-provider = "0.4.1"
rhema-provider-registry = "0.4.1"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -59,6 +67,8 @@ thiserror = { workspace = true }
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
# concurrent handler runs share it. `net` is the HTTP listener.
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] }
# The sandbox executor implements the shell seam
async-trait = { workspace = true }
# The chat surface: native routes plus SSE, and the OpenAI shim
axum = { workspace = true }
# Broadcast receivers as SSE bodies
@@ -71,7 +81,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.22"
rhema-mcp = "0.2.3"
rhema-mcp = "0.4.1"
[dev-dependencies]
tempfile = "3"
@@ -83,7 +93,7 @@ reqwest = { version = "0.12", features = ["json", "stream"] }
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.2.3", features = ["mock"] }
rhema-core = { version = "0.4.1", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+26 -2
View File
@@ -69,6 +69,12 @@ listen: 127.0.0.1:7799
token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: ssh # local (default), http, or ssh
host: me@box.example # the ssh destination: an alias or user@host
workspace: /srv/claw # ssh only: the workspace base, default /root
# http instead speaks the sandbox protocol (rhema-sandboxd):
# kind: http, url: https://box.example:7600, token: sandbox-secret
poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty
@@ -96,6 +102,19 @@ unattended for a long time, so a cap this deep is a runaway guard, not
a work timer — a turn that hits it ends with a failed outcome and the
conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. `kind: ssh` runs commands on a login the local `ssh`
config resolves (`host`, any alias or `user@host`), nothing installed
on the far end; `workspace` names the remote directory the claw's
workspaces live under, `/root` by default, one directory per claw
workspace under it. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
workspace root. Later edits stay there; the claw does not copy them
back.
The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer
token is what stands between it and the agent's tools. Set a token, or
@@ -123,7 +142,7 @@ The native surface:
```
GET /healthz GET /v1/sessions
POST /v1/sessions {"name"} — create an empty interactive session
POST /v1/sessions/{key}/messages {"text": "..."} -> 202
POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?} -> 202
GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
DELETE /v1/sessions/{key} drop a session and its turn history
@@ -137,6 +156,8 @@ DELETE /v1/consents/{id} deny a pending ask
GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?,"host"?,"workspace"?}, switch and persist
GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
@@ -169,7 +190,10 @@ lets a UI badge setup state.
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
`turn_done`. Every streamed event is persisted as it streams, so both a
`turn_done`. A `user_message` names its paste chips as the byte spans
they stand for in its plain text (`paste::PasteSpan`, the session
record's own shape) — a client renders from that record; rows recorded
before spans arrived carry the legacy mark form in the text instead. Every streamed event is persisted as it streams, so both a
reload and a daemon restart rebuild the transcript, and a session that
runs for weeks keeps all of it.
+1 -1
View File
@@ -26,9 +26,9 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rhema_agent_tools::render_template;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json};
/// The built-in system prompt, kept as data next to the code and read
+90 -6
View File
@@ -13,6 +13,7 @@
//! binary's startup, not here — the daemon library takes the built
//! provider, so tests can inject a mock.
use std::num::NonZeroU32;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -22,10 +23,13 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60;
/// How many tool rounds one chat turn may run, when
/// [`ClawConfig::max_turn_steps`] is unset — the coding driver's own
/// budget shape and its default: deep enough that a cap is a runaway
/// guard for an agent meant to work unattended, not a work timer.
pub const DEFAULT_MAX_TURN_STEPS: u32 = 2048;
/// [`ClawConfig::max_turn_steps`] is unset — the host agent driver's
/// own budget shape and its default: deep enough that a cap is a
/// runaway guard for an agent meant to work unattended, not a work
/// timer. `NonZeroU32`, the driver's own spelling: a turn cannot have
/// no step budget at all, and a config that names zero is refused at
/// load instead of cutting every round dead.
pub const DEFAULT_MAX_TURN_STEPS: NonZeroU32 = NonZeroU32::new(2048).unwrap();
/// Where the HTTP surface listens when [`ClawConfig::listen`] is unset:
/// loopback only — the surface is for the machine's resident user.
@@ -55,6 +59,9 @@ pub enum ConfigError {
"agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
)]
SameAgentToken,
/// The configured sandbox choice cannot run as written.
#[error("sandbox: {0}")]
Sandbox(String),
/// The ingest credential is the same value as the human token or
/// the agent token: boot refuses, because the ingest credential's
/// safety is that it is write-only and the event door only — a
@@ -127,7 +134,7 @@ pub struct ClawConfig {
/// How many tool rounds one chat turn may run before it is cut off
/// with a failed outcome, the conversation intact. A follow-up
/// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset.
pub max_turn_steps: u32,
pub max_turn_steps: NonZeroU32,
/// The handler's model backend: `google`, `llama-cpp`, `openrouter`,
/// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve
/// through the stored rhema config's default profile, env vars
@@ -171,6 +178,10 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still
/// ingest.
pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, or a
/// `rhema-sandboxd` over HTTP. The settings store owns the live
/// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>,
}
impl ClawConfig {
@@ -198,6 +209,7 @@ impl Default for ClawConfig {
tools_bin: None,
ingest_token: None,
transcript: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -326,6 +338,12 @@ impl ClawConfig {
{
return Err(ConfigError::IngestTokenCollision);
}
if let Some(sandbox) = &self.sandbox {
sandbox
.clone()
.normalized()
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
}
Ok(())
}
}
@@ -422,10 +440,14 @@ model: claude-sonnet-4-5
listen: 192.168.1.10:7800
token: sekrit
ingest_token: door-key
sandbox:
kind: http
url: https://box.example:7600
token: sandbox-secret
";
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
assert_eq!(config.poll_interval_secs, 30);
assert_eq!(config.max_turn_steps, 512);
assert_eq!(config.max_turn_steps, NonZeroU32::new(512).unwrap());
assert_eq!(config.provider.as_deref(), Some("anthropic"));
assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5"));
assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800"));
@@ -438,6 +460,68 @@ ingest_token: door-key
config.bootstrap_root.as_deref(),
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap"))
);
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
let config: ClawConfig = serde_yaml::from_str(
"sandbox:\n kind: ssh\n host: me@box.example\n workspace: /srv/claw\n",
)
.expect("the ssh sandbox parses");
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Ssh);
assert_eq!(sandbox.host.as_deref(), Some("me@box.example"));
assert_eq!(sandbox.workspace.as_deref(), Some("/srv/claw"));
}
#[test]
fn an_http_sandbox_needs_a_url_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"a remote sandbox without a URL is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
fn an_ssh_sandbox_needs_a_host_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"an ssh sandbox without a host is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
host: Some("me@box.example".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a bare login is all ssh needs");
}
#[test]
+274 -24
View File
@@ -22,6 +22,7 @@
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};
@@ -62,6 +63,9 @@ pub enum ClawError {
/// The runtime settings table could not be opened or read.
#[error(transparent)]
Settings(#[from] crate::settings::SettingsError),
/// The sandbox choice could not be loaded or is malformed.
#[error(transparent)]
Sandbox(#[from] crate::sandbox::SandboxError),
/// The notification table could not be opened or read.
#[error(transparent)]
Notifications(#[from] crate::notifications::NotificationStoreError),
@@ -123,6 +127,83 @@ fn interactive_dispatch() -> DispatcherConfig {
}
}
/// The forge dispatcher's timing: the library defaults, except the lease
/// TTL.
///
/// A forge turn is not a chat step. The handler clones a repository,
/// reads it, and may build and test a fix — tens of minutes of wall
/// clock — and nothing renews the lease once the turn is under way:
/// `SessionContext::poll_inbox` renews, and the handler calls it once, at
/// the start; the commit hook that runs between tool calls *checkpoints*,
/// which fails on a lapsed lease instead of extending one. So the TTL is
/// a hard ceiling on a whole turn: cross it and the turn dies on its next
/// tool call, after which the driver's own checkpoint and release both
/// report `Expired` and the key ends with no outcome recorded — a silent
/// kill, indistinguishable from a pass that found nothing.
///
/// `DispatcherConfig::default`'s ten minutes are the spec's example
/// values, sized for a single agent step. An hour matches the
/// interactive lane's choice for the same reason: the work is long.
pub fn forge_dispatch() -> DispatcherConfig {
DispatcherConfig {
lease_ttl_millis: 3_600_000,
..DispatcherConfig::default()
}
}
/// Hands one driver pass to its own task, so a turn does not stop the
/// clock.
///
/// [`Driver::run_once`] awaits every run it admits, which is exactly right
/// for a cron pass and wrong for a resident: a forge turn clones a repo
/// and may build a slicer, a coding job runs a session — tens of minutes
/// either way — and everything else the loop does (detecting, and so
/// polling the forges, recording watch health, firing due tasks, reading
/// the calendar, delivering to the phone) waits behind it. With a 60s
/// tick and a ten-minute turn, the daemon polls once per turn.
///
/// One pass per lane at a time. `busy` is held for the pass's whole
/// duration, and a tick that finds it held leaves its events where they
/// are: the dispatcher's inbox is the queue, so nothing is dropped — the
/// next tick admits them. Starting a second pass anyway would only lose
/// lease acquisitions to the first and log the loss.
fn spawn_pass(driver: Arc<Driver>, label: &'static str, busy: Arc<AtomicBool>) {
if busy.swap(true, Ordering::AcqRel) {
return;
}
let held = BusyFlag(busy);
tokio::spawn(async move {
// Dropped however this task ends, a panic included: a lane whose
// flag never cleared would never run again.
let _held = held;
match driver.run_once().await {
Ok(outcomes) => {
let handled = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Handled))
.count();
let failed = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Failed(_)))
.count();
if handled + failed > 0 {
eprintln!("[claw] {label} pass: {handled} handled, {failed} failed");
}
}
Err(err) => eprintln!("[claw] warning: {label} pass failed: {err}"),
}
});
}
/// Clears a lane's in-flight flag when its spawned pass ends.
struct BusyFlag(Arc<AtomicBool>);
impl Drop for BusyFlag {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
/// The resident daemon: the extension set's sources (the forge watches,
/// the task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface.
@@ -139,6 +220,10 @@ 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,
@@ -151,8 +236,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — the resident loop uses the
/// defaults, `--once` zeroes the debounce.
/// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// with `--once` zeroing the debounce.
pub fn build(
config: &ClawConfig,
backends: Arc<BackendRegistry>,
@@ -225,6 +310,10 @@ impl Daemon {
// The forge handler resolves its watches through the table at
// dispatch time, so a watch added mid-run is answerable without a
// restart.
// The runtime settings table, opened before the handlers so the
// sandbox choice and the provider write share one connection.
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The client tools' connection, handed to the agent's shell as
// environment: the URL the surface answers on, the scoped
// agent token (the middleware keeps it to the contract's data
@@ -252,6 +341,25 @@ impl Daemon {
format!("{}:{inherited}", tools_bin.display()),
);
}
// Where `bash` runs: the stored choice wins, the config seeds a
// fresh store. The state is shared by every handler and the
// surface, so a switch is live on the next turn.
let sandbox = Arc::new(crate::sandbox::SandboxState::load(
settings.clone(),
config.sandbox.clone(),
interactive_workspace.clone(),
&tool_env,
)?);
let sandbox_choice = sandbox.choice();
eprintln!(
"[claw] sandbox: {}{}",
sandbox_choice.kind.as_str(),
sandbox_choice
.url
.as_deref()
.map(|url| format!(" ({url})"))
.unwrap_or_default(),
);
let forge_handler = ClawHandler::new(
backends.clone(),
workspace_root,
@@ -259,7 +367,8 @@ impl Daemon {
accounts.clone(),
config.transcript_enabled(),
tool_env.clone(),
);
)
.with_sandbox(sandbox.clone());
// Three drivers over one store admit from the same table, so
// each owns its slice of the key space: a forge pass must never
// pick up a resident or job event (it would fail it, and
@@ -292,7 +401,6 @@ impl Daemon {
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The identity store shares the settings table and keeps its
// images beside the database.
let identity = Arc::new(crate::identity::IdentityStore::new(
@@ -361,7 +469,8 @@ impl Daemon {
extensions.clone(),
config.transcript_enabled(),
)
.with_steer(steer.clone());
.with_steer(steer.clone())
.with_sandbox(sandbox.clone());
let interactive_driver = Arc::new(
Driver::new(
interactive_dispatcher.clone(),
@@ -381,7 +490,8 @@ impl Daemon {
notifications.clone(),
config.max_turn_steps,
config.transcript_enabled(),
);
)
.with_sandbox(sandbox.clone());
let jobs_driver = Arc::new(
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
.with_holder("rhema-claw-jobs")
@@ -410,6 +520,7 @@ impl Daemon {
bridge,
attachments,
phone,
sandbox,
config.token.clone(),
config.agent_token.clone(),
config.ingest_token.clone(),
@@ -424,6 +535,8 @@ 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)),
@@ -469,19 +582,16 @@ impl Daemon {
Ok(())
}
/// 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.
/// 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.
pub async fn tick(&self) -> Result<TickReport, ClawError> {
// 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?;
}
let detected = self.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 {
@@ -501,6 +611,50 @@ 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());
@@ -508,13 +662,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, 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.
/// 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.
pub async fn run(&self) -> Result<(), ClawError> {
self.bootstrap().await?;
let listener = tokio::net::TcpListener::bind(&self.listen).await?;
@@ -527,7 +681,7 @@ impl Daemon {
});
eprintln!("[claw] http listening on {addr}");
loop {
if let Err(err) = self.tick().await {
if let Err(err) = self.resident_tick().await {
eprintln!("[claw] warning: pass failed: {err}");
}
tokio::select! {
@@ -551,7 +705,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig {
debounce_window_millis: 0,
..DispatcherConfig::default()
..forge_dispatch()
};
let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?;
@@ -562,6 +716,102 @@ 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();
+148 -4
View File
@@ -24,10 +24,10 @@ use std::sync::{Arc, Mutex, PoisonError};
use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_forge_integration::forge_key_fn;
use rhema_forge_integration::triage::{self, Triage};
use rhema_forge_integration::triage::{self, Role, Triage};
use rhema_forge_integration::{
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, RepoRef, Timestamp, Watcher,
register_forge,
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, NotificationReason, RepoRef,
Timestamp, Watcher, register_forge,
};
use rhema_identity::{IdentityStore, SecretKind};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
@@ -514,7 +514,7 @@ impl ForgeSource {
let now = SystemClock.now_millis();
let mut fed = 0;
for notification in &page.notifications {
match triage::classify(notification) {
match claw_triage(notification) {
Triage::Ignore => {}
Triage::Surface => {
if let Err(err) = self.notifications.push(
@@ -565,6 +565,22 @@ impl ForgeSource {
fed += 1;
}
}
// The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning
// 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.
if let Err(err) = client.mark_read(notification).await {
eprintln!(
"[claw] warning: mark-read of {} failed: {err}",
notification.id
);
}
}
if let Some(cursor) = page.cursor {
self.account_cursors
@@ -576,6 +592,24 @@ impl ForgeSource {
}
}
/// [`triage::classify`], plus the one reclassification a resident agent
/// owes its own name: an @-mention of the daemon is an ask.
///
/// The shared vocabulary reads a mention as [`Triage::Surface`] — right
/// for a consumer that only notifies its human, since a mention is not an
/// assignment. This daemon is the party named: somebody typed `@handle` on
/// a thread and is waiting for an answer, which is the same ask an
/// assignment is. Left as a surface, a mention would be a phone buzz and
/// nothing else — this loop never dispatches for a surface, so the turn
/// that reads the thread would never run and the mention would go
/// unanswered.
fn claw_triage(notification: &Notification) -> Triage {
match &notification.reason {
NotificationReason::Mention => Triage::Agent(Role::Implementer),
_ => triage::classify(notification),
}
}
/// The device-notification text a [`Triage::Surface`] lands: the reason
/// and the thread title, so the human can judge without opening the
/// forge.
@@ -671,6 +705,65 @@ 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, 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;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"id": 42188,
"unread": true,
"reason": "mention",
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": "https://api.github.com/repos/acme/widgets/pulls/142",
"type": "PullRequest"
},
"repository": { "full_name": "acme/widgets" }
}
])))
.mount(&server)
.await;
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let (dispatcher, accounts, notifications) = test_parts(store.clone());
// The store mints the id; the watch row is what names it.
let account = accounts
.put(rhema_identity::AccountDraft::new(
"forge bot",
"github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
))
.expect("account lands");
store
.add_account_watch("github", Some(&server.uri()), &account.id)
.expect("account watch lands");
let source = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
assert_eq!(
source.detect().await.expect("the pass runs"),
1,
"a mention dispatches a turn"
);
// The read route keys on the notification, not the thread.
let requests = server.received_requests().await.expect("recording is on");
let reads: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(reads.len(), 1, "one mark-read per triaged row");
assert_eq!(reads[0].url.path(), "/notifications/threads/42188");
}
/// The parts a test source polls through, all in memory.
fn test_parts(
store: Arc<ClawStore>,
@@ -954,6 +1047,7 @@ mod tests {
title: Some("Add the flange".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
};
let payload = |notification: &Notification| {
@@ -985,4 +1079,54 @@ mod tests {
});
assert_eq!(key.as_str(), "github:issue:acme/widgets#142");
}
/// The notification fixture the reclassification tests classify: one
/// plain issue thread, the reason the only thing that varies.
fn triaged_notification(reason: NotificationReason) -> Notification {
Notification {
id: format!("github:notification:1@{}", reason.as_str()),
reason,
repo: RepoRef::new("acme", "widgets"),
number: 7,
is_pr: false,
actor: Some("stranger".to_owned()),
title: Some("a title".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-11-21T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
}
}
/// A mention of the daemon is an ask: this daemon is the party named,
/// so the feed dispatches a turn that reads the thread — not a phone
/// buzz that leaves the mention unanswered.
#[test]
fn a_mention_of_the_daemon_dispatches_instead_of_surfacing() {
assert_eq!(
claw_triage(&triaged_notification(NotificationReason::Mention)),
Triage::Agent(Role::Implementer),
"somebody addressed the daemon and is waiting"
);
}
/// Every other reason keeps the shared vocabulary's verdict — the
/// reclassification is one row, not a second opinion.
#[test]
fn every_other_reason_keeps_the_shared_verdict() {
for reason in [
NotificationReason::ReviewRequested,
NotificationReason::Assigned,
NotificationReason::ReviewFeedback,
NotificationReason::Author,
NotificationReason::CiActivity,
NotificationReason::Other("subscribed".to_owned()),
] {
assert_eq!(
claw_triage(&triaged_notification(reason.clone())),
triage::classify(&triaged_notification(reason.clone())),
"{} keeps the base verdict",
reason.as_str()
);
}
}
}
+49 -13
View File
@@ -10,7 +10,7 @@
//!
//! Session continuity rides the dispatcher, not the filesystem: the
//! agent's session JSON is stashed into `ctx.session.core.driver_state`
//! before the run returns and restored with [`CodingAgent::from_session`]
//! before the run returns and restored with [`HostAgent::from_session`]
//! on the next dispatch of the same key, so a resumed thread keeps its
//! conversation. Commit-before-execute rides it too: the run installs the
//! context's commit hook, so the intent is in the store before the first
@@ -25,9 +25,8 @@ use std::sync::{Arc, Mutex, PoisonError};
use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore;
use rhema_agent_tools::AllowAll;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
use rhema_coding_agent::{CodingAgent, CodingAgentConfig};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
use rhema_forge_integration::ForgeKind;
use rhema_forge_integration::triage::Role;
@@ -35,11 +34,13 @@ use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode,
parse_key,
};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_identity::IdentityStore;
use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell;
use crate::backends::BackendRegistry;
use crate::sandbox::SandboxState;
/// The handler's tool permissions, resolved deterministically before the
/// agent's first step (spec §8) — never by the model, never mid-run. V1
@@ -71,6 +72,9 @@ pub struct ClawHandler {
/// agent shell: the daemon URL, the scoped agent token, the tools'
/// bin dir on PATH. Empty when the config issues no agent token.
tool_env: std::collections::BTreeMap<String, String>,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per dispatch.
sandbox: Option<Arc<SandboxState>>,
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
}
@@ -92,10 +96,18 @@ impl ClawHandler {
watches,
accounts,
tool_env,
sandbox: None,
clients: Mutex::new(HashMap::new()),
}
}
/// Shares the deployment's sandbox choice: a forge turn's commands
/// run where it says, seeded from the thread's host workspace.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// The forge client a dispatch key answers to:
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
/// table at dispatch time — the table is the source of truth, not a
@@ -283,7 +295,7 @@ impl ClawHandler {
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
let mut sink = TurnSink;
let output = agent
.turn(prompt, &mut sink, Arc::new(AllowAll))
.turn(prompt, &mut sink)
.await
.map_err(|err| format!("turn for {key} failed: {err}"))?;
@@ -330,35 +342,55 @@ impl ClawHandler {
ctx: &SessionContext,
workspace: &Path,
key: &str,
) -> Result<CodingAgent, String> {
) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current();
let config = self.agent_config(&model, workspace);
let config = self.agent_config(provider, &model, workspace);
let agent = match &ctx.session.core.driver_state {
// A never-dispatched key carries no stash: start clean.
serde_json::Value::Null => CodingAgent::new(provider, config),
serde_json::Value::Null => HostAgent::new(config),
stashed => {
let session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
CodingAgent::from_session(provider, config, session)
HostAgent::from_session(config, session)
}
};
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
}
/// The config one dispatch's agent runs on: the default coding
/// agent's, with the bounded request view when the config has it on.
/// agent's, with the bounded request view when the config has it on
/// and a remote shell when the sandbox choice says so.
/// A forge thread answers for as long as the thread lives; without
/// the view its history would ride whole on every step.
fn agent_config(&self, model: &str, workspace: &Path) -> CodingAgentConfig {
let mut config = CodingAgentConfig::new(model, workspace);
fn agent_config(
&self,
provider: Arc<dyn rhema_core::ModelProvider>,
model: &str,
workspace: &Path,
) -> HostAgentConfig {
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(workspace),
None => workspace.to_path_buf(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
// Write the resolved value, not an override: the coding agent's
// own default is on now, and the config's `false` must win.
config.transcript = self
.transcript
.then(rhema_transcript::TranscriptSettings::default);
config.shell_env = self.tool_env.clone();
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display,
sandbox.executor(workspace.to_path_buf()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
}
}
config
}
@@ -945,6 +977,7 @@ mod tests {
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-03T09:00:00Z",
"read_key": "42188",
"raw": {},
}))
.expect("notification fixture parses")
@@ -1068,6 +1101,7 @@ mod tests {
Content::Text("on it".into()),
Content::Text(" — closing.".into()),
],
annotations: Default::default(),
};
assert_eq!(final_text(&message).as_deref(), Some("on it — closing."));
let tool_only = Message {
@@ -1078,6 +1112,7 @@ mod tests {
args: serde_json::json!({}),
provider_data: serde_json::Value::Null,
})],
annotations: Default::default(),
};
assert_eq!(final_text(&tool_only), None, "no text, no reply");
}
@@ -1221,6 +1256,7 @@ mod tests {
.expect("constructs"),
);
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0;
let on = ClawHandler::new(
registry.clone(),
"/tmp/w",
@@ -1238,12 +1274,12 @@ mod tests {
std::collections::BTreeMap::new(),
);
assert!(
on.agent_config("m", Path::new("/tmp/w"))
on.agent_config(provider.clone(), "m", Path::new("/tmp/w"))
.transcript
.is_some()
);
assert!(
off.agent_config("m", Path::new("/tmp/w"))
off.agent_config(provider, "m", Path::new("/tmp/w"))
.transcript
.is_none()
);
+91 -4
View File
@@ -123,6 +123,9 @@ pub struct ClawState {
/// The phone tables: the command queue the device polls and the
/// reported state the ingest door feeds.
phone: Arc<crate::phone::PhoneStore>,
/// Where the agent's `bash` runs: the live choice `/v1/sandbox`
/// edits, shared with every handler.
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>,
/// The scoped agent token the client tools hold: a second bearer
/// answering only the contract's data routes (see
@@ -146,7 +149,7 @@ impl ClawState {
/// `agent_token`.
#[expect(
clippy::too_many_arguments,
reason = "eighteen parts, each load-bearing"
reason = "twenty-one parts, each load-bearing"
)]
pub fn new(
dispatcher: Arc<Dispatcher>,
@@ -167,6 +170,7 @@ impl ClawState {
bridge: Arc<crate::consents::WaitBridge>,
attachments: Arc<crate::attachments::AttachmentStore>,
phone: Arc<crate::phone::PhoneStore>,
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>,
agent_token: Option<String>,
ingest_token: Option<String>,
@@ -190,6 +194,7 @@ impl ClawState {
bridge,
attachments,
phone,
sandbox,
token,
agent_token,
ingest_token,
@@ -289,6 +294,11 @@ impl ClawState {
pub fn watches(&self) -> &ClawStore {
&self.watches
}
/// Where the agent's `bash` runs.
pub fn sandbox(&self) -> &crate::sandbox::SandboxState {
&self.sandbox
}
}
/// The app router: `/healthz` open, `/v1` behind the bearer check when
@@ -343,6 +353,7 @@ pub fn router(state: ClawState) -> Router {
)
.route("/providers/{id}", delete(providers_remove))
.route("/providers/{id}/models", get(providers_models))
.route("/sandbox", get(sandbox_get).put(sandbox_put))
.route(
"/chat/completions",
post(crate::openai::chat_completions)
@@ -652,12 +663,20 @@ pub const MAX_INBOUND_IMAGES: usize = 8;
pub const MAX_MESSAGE_BODY_BYTES: usize =
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
/// `{"text": "..."}` — one chat message, plus the images it carries.
/// A body without `images` is the old shape, unchanged.
/// `{"text": "..."}` — one chat message, plus the images and the chip
/// payloads it carries. A body without `images` or `pastes` is the old
/// shape, unchanged.
#[derive(Deserialize)]
pub struct MessageBody {
/// The message text.
/// The message text, plain: each paste payload appended to it in
/// the fold, its chip noted as a span in the recorded event — no
/// mark form on the wire.
pub text: String,
/// The message's staged chips, payloads in order. A sender that
/// mints the legacy mark form sends none; the fold rewrites that
/// form too.
#[serde(default)]
pub pastes: Vec<String>,
/// The message's inline images, each the full MIME type plus bare
/// base64. The route checks the budget, then the dispatch copies
/// the bytes into the attachment store — the stream carries ids,
@@ -729,6 +748,7 @@ async fn messages(
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
key.as_str(),
&body.text,
&body.pastes,
&body.images,
)) {
return (
@@ -1982,6 +2002,73 @@ pub(crate) async fn drain_owned(
}
}
/// `GET /v1/sandbox`: where the agent's `bash` runs. The token never
/// rides the wire: `token_set` says whether one is stored.
async fn sandbox_get(State(state): State<ClawState>) -> Json<Value> {
Json(sandbox_json(&state))
}
/// The sandbox state as the wire sees it: the shared body of the read
/// and of the write that answers with the new choice.
fn sandbox_json(state: &ClawState) -> Value {
let choice = state.sandbox().choice();
json!({
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"host": choice.host,
"ssh_workspace": choice.workspace,
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
})
}
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` is write-only; `clear_token` drops the
/// stored one. The choice applies on the next turn, no restart.
async fn sandbox_put(
State(state): State<ClawState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let Some(kind) = body["kind"].as_str() else {
return Err(bad_request("body must carry a sandbox kind"));
};
let kind = crate::sandbox::SandboxKind::parse(kind)
.ok_or_else(|| bad_request(format!("unknown sandbox kind {kind:?}")))?;
let current = state.sandbox().choice();
let clear_token = body["clear_token"].as_bool().unwrap_or(false);
let token = if clear_token {
None
} else {
body["token"]
.as_str()
.map(str::to_owned)
.or_else(|| current.token.clone())
};
let choice = crate::sandbox::SandboxChoice {
kind,
url: body["url"]
.as_str()
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
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()),
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
crate::sandbox::SandboxError::Store(_) => internal_error(err),
})?;
Ok(Json(sandbox_json(&state)))
}
/// `GET /v1/providers`: every constructible backend and the active pair.
/// The active pair is runtime state — the config file seeded it, the
/// settings store owns it now. Each provider is one instance, named by
+38 -4
View File
@@ -28,6 +28,7 @@
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};
use rhema_core::paste::PasteSpan;
use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
@@ -74,13 +75,23 @@ pub enum TurnEvent {
/// shows its own messages as it sends them, and skips the live
/// echo.
UserMessage {
/// The input text, verbatim.
/// The input text in the plain form the model read — each
/// paste's payload in place, no marks.
text: String,
/// The batch's images, in arrival order, as the attachment
/// store holds them. `default` because rows recorded before
/// images rode the transcript carry no field.
#[serde(default)]
images: Vec<UserImage>,
/// The paste chips the input carried, the same span record the
/// session's `rhema-code` annotation holds: the byte range
/// each chip stands for in `text`, plus its line count for the
/// label. `default` because rows recorded before chips rode
/// as spans carry the marks in the text instead — a client
/// that finds none scans for them; skipped when empty, so
/// rows without chips replay byte-for-byte as they landed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pastes: Vec<PasteSpan>,
},
/// A piece of the model's reasoning trace, in stream order.
ThinkingDelta {
@@ -565,10 +576,27 @@ mod tests {
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: Vec::new(),
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[]}"#
);
// The chip record rides only when there is one: the span
// shape is the session annotation's own, byte offsets over
// the plain text.
assert_eq!(
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: vec![PasteSpan {
start: 3,
end: 9,
lines: 4,
}],
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[],"pastes":[{"start":3,"end":9,"lines":4}]}"#
);
assert_eq!(
serde_json::to_string(&TurnEvent::ToolResult {
name: "bash".into(),
@@ -600,7 +628,8 @@ mod tests {
event,
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
}
@@ -614,7 +643,8 @@ mod tests {
assert_eq!(
TurnEvent::UserMessage {
text: "x".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
.kind(),
"user_message"
@@ -659,6 +689,7 @@ mod tests {
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text("hi"));
@@ -669,7 +700,8 @@ mod tests {
vec![
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
},
text("hi"),
],
@@ -795,6 +827,7 @@ mod tests {
TurnEvent::UserMessage {
text: "earlier".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
let (history, mut receiver) = hub.subscribe_with_history(&key);
@@ -896,6 +929,7 @@ mod tests {
TurnEvent::UserMessage {
text: format!("q{turn}"),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text(&format!("a{turn}")));
+314 -66
View File
@@ -46,7 +46,8 @@
//! v1's starting point — and the resolver chain are assembled before
//! the first model call; the model never decides its own permissions.
//! The chain is the core toolsets (the shell over the interactive
//! workspace, memory, `bootstrap_save`) plus every
//! workspace, or over the sandbox root when one is selected; memory,
//! `bootstrap_save`) plus every
//! [`crate::extension::ClawExtension`]'s tools in the standard set's
//! order. The system prompt is rendered per dispatch from the
//! bootstrap template over the live SOUL/USER files.
@@ -63,16 +64,18 @@
//! rhema-code's UI draws for a steered turn.
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use rhema_agent_tools::{AllowAll, ExpandPastes, ShellTools, revive_dangling_calls};
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
ModelProvider, Role, Session, ToolContext, ToolResolver, close_orphaned_calls, run_turn,
ModelProvider, Role, Session, ToolContext, ToolResolver, close_orphaned_calls,
revive_dangling_calls, run_turn,
};
use rhema_memory::{MemoryResolver, MemoryStore, Scope};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
@@ -82,6 +85,7 @@ use crate::backends::BackendRegistry;
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
use crate::hub::{EventHub, TurnEvent, UserImage};
use crate::notifications::NotificationStore;
use crate::sandbox::SandboxState;
use crate::steer::{SteerGuard, SteerRegistry};
/// The key prefixes of the resident context (see the module docs):
@@ -162,10 +166,10 @@ pub struct WireImage {
/// The event one chat message becomes. The id is unique per message (a
/// wall-clock millisecond plus a process counter), so a redelivery
/// never dedups a different message away. The payload carries the
/// message's images when it has any, and no `images` key when it has
/// none — old payloads stay byte-identical.
pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
/// never dedups a different message away. The chips' payloads ride
/// beside the text, and the images with them, each only when the
/// message staged any — payloads without chips stay byte-identical.
pub fn user_event(key: &str, text: &str, pastes: &[String], images: &[WireImage]) -> Event {
static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -177,10 +181,18 @@ pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
MESSAGE_SEQ.fetch_add(1, Ordering::Relaxed)
),
source: SOURCE.to_owned(),
payload: if images.is_empty() {
json!({ "key": key, "text": text })
} else {
json!({ "key": key, "text": text, "images": images })
// The chips' payloads ride only when the message staged any,
// and images only when it carried any: the old two-field shape
// rides byte-for-byte otherwise.
payload: {
let mut payload = json!({ "key": key, "text": text });
if !pastes.is_empty() {
payload["pastes"] = json!(pastes);
}
if !images.is_empty() {
payload["images"] = json!(images);
}
payload
},
received_at: now.as_millis() as u64,
}
@@ -232,7 +244,7 @@ pub struct InteractiveHandler {
/// How many tool rounds one turn may run before it is cut off — the
/// config's runaway guard for an agent meant to work unattended; a
/// follow-up message keeps going.
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
/// The extension set the tool half of the chain is cut from, per
/// dispatch, in the standard set's order — the same set whose
/// sources the daemon's tick drives and whose boot pass runs first.
@@ -241,10 +253,14 @@ pub struct InteractiveHandler {
/// decorator refreshes it per request, `zoom` reads it, and it
/// lives here — the agent rebuilds per dispatch, the log must not.
transcript_mirror: Option<Arc<std::sync::Mutex<rhema_transcript::Transcript>>>,
/// The wired [`vision`](rhema_agent_tools::vision) section for the
/// The wired [`vision`](rhema_bash::vision) section for the
/// prompt, when provisioning succeeded — the same wiring whose env
/// map lights the shell's inbox up.
vision: Option<String>,
/// Where commands run: this host when absent, a remote sandbox
/// when the surface selected one. Read per dispatch, so a switch
/// takes effect on the next turn.
sandbox: Option<Arc<SandboxState>>,
}
impl InteractiveHandler {
@@ -265,7 +281,7 @@ impl InteractiveHandler {
hub: Arc<EventHub>,
notifications: Arc<NotificationStore>,
attachments: Arc<crate::attachments::AttachmentStore>,
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
extensions: Arc<crate::extension::Extensions>,
transcript: bool,
) -> Self {
@@ -274,7 +290,7 @@ impl InteractiveHandler {
// chat's commands, and its staged images attach to their
// results. Local shells only — the interactive handler's
// executor is this host's by construction.
let vision = rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV"));
let vision = rhema_bash::vision::wire(std::env::var_os("BASH_ENV"));
let tools = Arc::new(match vision {
Some(wiring) => ShellTools::with_env(&workspace, &wiring.shell_env),
None => ShellTools::new(&workspace),
@@ -301,9 +317,17 @@ impl InteractiveHandler {
)))
}),
vision: vision.map(|wiring| wiring.section.to_owned()),
sandbox: None,
}
}
/// Shares the deployment's sandbox choice: commands run where it
/// says, and a remote sandbox replaces the host shell for `bash`.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// The agent for one dispatch: rebuilt per run over the restored
/// session (the engine's own step counter is per-agent; the
/// conversation lives in the session, not the agent). The system
@@ -314,12 +338,7 @@ impl InteractiveHandler {
/// request advertises.
fn agent(&self, key: &ResourceKey) -> Result<Agent, String> {
let (provider, model) = self.backends.current();
// Chat input may carry embedded pastes — the compact chip form
// the UIs mint and the session keeps — so the provider wraps in
// the same expansion the coding driver wraps its own with: the
// model sees plain text, the transcript keeps the chips.
let provider: Arc<dyn ModelProvider> = Arc::new(ExpandPastes::new(provider));
// The view rides outside the expansion: stubs, whole messages,
// The view rides outside the engine: stubs, whole messages,
// and zoom output all show the text the model would have seen.
let provider: Arc<dyn ModelProvider> = match &self.transcript_mirror {
Some(mirror) => Arc::new(rhema_transcript::TranscriptView::new(
@@ -329,13 +348,23 @@ impl InteractiveHandler {
None => provider,
};
let resolver = self.resolver(key);
let workspace = self.workspace();
let vision = if self
.sandbox
.as_ref()
.is_some_and(|sandbox| sandbox.is_remote())
{
None
} else {
self.vision.as_deref()
};
let system = render_system(
DEFAULT_SYSTEM_MD,
key.as_str(),
&self.workspace,
&workspace,
&self.bootstrap,
&resolver.specs(),
self.vision.as_deref(),
vision,
)
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
Agent::builder()
@@ -356,6 +385,15 @@ impl InteractiveHandler {
self
}
/// The workspace the prompt names: the host path locally, the
/// sandbox root when commands run elsewhere.
fn workspace(&self) -> PathBuf {
match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(&self.workspace),
None => self.workspace.clone(),
}
}
/// The resolver chain one dispatch runs under: the core toolsets —
/// the shell over the interactive workspace, memory,
/// `bootstrap_save` — then every extension's tools in the standard
@@ -364,8 +402,18 @@ impl InteractiveHandler {
/// their asks and cards to the session that asked, and the handler
/// serves every session.
fn resolver(&self, key: &ResourceKey) -> Arc<ResolverChain> {
let shell: Arc<dyn rhema_core::ToolResolver> = match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
let workspace = sandbox.workspace_for(&self.workspace);
let tools =
ShellTools::with_executor(workspace, sandbox.executor(self.workspace.clone()));
tools.install_approval(Arc::new(AllowAll));
Arc::new(tools)
}
_ => self.tools.clone(),
};
let mut resolvers: Vec<Arc<dyn rhema_core::ToolResolver>> = vec![
self.tools.clone(),
shell,
Arc::new(MemoryResolver::new(
self.memory.clone(),
Scope::Workspace(self.workspace.clone()),
@@ -401,7 +449,9 @@ impl InteractiveHandler {
.await
.map_err(|err| format!("inbox poll for {key} failed: {err}"))?;
// Texts fold in arrival order, and so do the images, across
// the whole batch whichever events carried them.
// the whole batch whichever events carried them — each text
// with its chips already composed in, their spans measured
// over it.
let mut texts = Vec::new();
let mut images = Vec::new();
for item in &items {
@@ -411,7 +461,35 @@ impl InteractiveHandler {
.or_else(|| payload.get("prompt"))
.and_then(Value::as_str)
{
texts.push(text);
// The fold owns the chip record. A legacy sender's
// marks ride the text and migrate here, per message;
// a payload chip appends in order right after —
// plain either way before the join, its span
// measured where it lands.
let mut message = [Message::text(Role::User, text.to_owned())];
rhema_core::paste::migrate(&mut message);
let mut spans = rhema_core::paste::spans(&message[0]);
let mut composed = match &message[0].content[0] {
Content::Text(text) => text.clone(),
_ => unreachable!("the message was built with one text block"),
};
for paste in payload
.get("pastes")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(rhema_core::paste::normalize)
{
let span = rhema_core::paste::PasteSpan {
start: composed.len(),
end: composed.len() + paste.len(),
lines: paste.lines().count(),
};
composed.push_str(&paste);
spans.push(span);
}
texts.push((composed, spans));
}
if let Some(carried) = payload.get("images").and_then(Value::as_array) {
images.extend(
@@ -421,7 +499,22 @@ impl InteractiveHandler {
);
}
}
let input = texts.join("\n\n");
let mut input = String::new();
let mut pastes = Vec::new();
let mut first = true;
for (text, spans) in texts {
if !first {
input.push_str("\n\n");
}
let base = input.len();
input.push_str(&text);
pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan {
start: span.start + base,
end: span.end + base,
lines: span.lines,
}));
first = false;
}
if input.trim().is_empty() {
// Round one's emptiness is the dispatch bug it always was:
// the lease exists because something waited. A steered
@@ -472,13 +565,17 @@ impl InteractiveHandler {
}
// The transcript's question, recorded before anything else can
// stream: a replay shows what was asked, not only what was
// answered. Raw input — the notification-contract framing below
// is the model's business, not the viewer's.
// answered. The fold composed the record — plain text, the
// chip spans beside it — and the turn runs this exact input;
// the notification-contract framing below is the model's
// business, not the viewer's.
let recorded_len = input.len();
self.hub.emit(
&ctx.key,
TurnEvent::UserMessage {
text: input.clone(),
images: transcript_images,
pastes: pastes.clone(),
},
);
// A non-chat resident key has no subscriber to read the reply:
@@ -532,10 +629,29 @@ impl InteractiveHandler {
// future at its current await — a streaming request, or a
// running shell command, whose child dies with the drop. The
// next round revives whatever committed before the drop.
// The input rides in the plain form the fold recorded — the
// payloads sit in the text and the model never sees a mark —
// with the span note riding the message, so the checkpoint
// (and a session resumed from it) keeps the chips beside the
// plain text. The framings above live in the model's copy:
// their bytes are known exactly, and each span shifts by them,
// still pointing into the text it annotates.
let framed_len = input.len();
let pastes = pastes
.iter()
.map(|span| rhema_core::paste::PasteSpan {
start: span.start + framed_len - recorded_len,
end: span.end + framed_len - recorded_len,
lines: span.lines,
})
.collect::<Vec<_>>();
let mut question = [Message::text_with_images(Role::User, input, core_images)];
rhema_core::paste::annotate(&mut question[0], &pastes);
let [turn_input] = question;
let mut turn = Box::pin(run_turn(
&mut agent,
&mut session,
Message::text_with_images(Role::User, input, core_images),
turn_input,
&mut sink,
&tools,
self.max_turn_steps,
@@ -679,8 +795,16 @@ enum Round {
fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
match stashed {
Value::Null => Ok(Session::default()),
stashed => serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}")),
stashed => {
let mut session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
// A session stashed before paste spans existed carries the
// embedded form in its prompts; the provider must never see
// a mark. One rewrite on the way in, chips survive as the
// span note — the same pass the driver's from_session runs.
rhema_core::paste::migrate(&mut session.history);
Ok(session)
}
}
}
@@ -794,6 +918,10 @@ impl EventSink for HubSink {
| ModelEvent::Usage(_)
| ModelEvent::RetryWait { .. }
| ModelEvent::StepEnd { .. } => return,
// The engine's event enum is non-exhaustive: a future
// event arrives here, dropped like the rest of the engine's
// own bookkeeping until a turn-event shape exists for it.
_ => return,
};
self.hub.emit(&self.key, turn);
}
@@ -1056,12 +1184,17 @@ mod tests {
}
}
/// The paste contract across the provider seam: a chat input that
/// carries an embedded paste (the compact form the UIs mint) is
/// expanded before the request leaves, while the transcript the hub
/// streams keeps the compact form.
#[tokio::test]
async fn an_embedded_paste_expands_for_the_model_and_not_for_the_transcript() {
/// The environment a paste test drives: the recording provider, the
/// hub, and a dispatcher wired to one interactive handler over a
/// throwaway workspace.
fn paste_env() -> (
Arc<RecordingProvider>,
Arc<EventHub>,
Arc<Dispatcher>,
InteractiveHandler,
Key,
tempfile::TempDir,
) {
let recorder = RecordingProvider::new();
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let hub = Arc::new(EventHub::default());
@@ -1087,7 +1220,7 @@ mod tests {
Arc::new(rhema_memory::VolatileStore::new()),
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
hub.clone(),
notifications.clone(),
notifications,
attachments(),
crate::config::DEFAULT_MAX_TURN_STEPS,
extensions,
@@ -1102,14 +1235,31 @@ mod tests {
Arc::new(VolatileStore::new()),
));
register_user(&dispatcher);
(
recorder,
hub,
dispatcher,
handler,
Key::from("interactive:web"),
workspace,
)
}
/// The legacy intake: a chat input still carrying the embedded
/// mark form migrates at the fold — the model reads the payload in
/// place, and the recorded question is the plain form with the
/// chip noted beside it.
#[tokio::test]
async fn an_embedded_arrival_migrates_at_the_fold() {
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let key = Key::from("interactive:web");
dispatcher
.ingest(user_event(
key.as_str(),
"review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}",
&[],
&[],
))
.expect("ingests");
driver.run_once().await.expect("the run happens");
@@ -1119,17 +1269,61 @@ mod tests {
"review this:fn main() {}\nfn other() {}",
"the model saw the payload, not the marks"
);
// The recorded question is the plain form, the chip record
// riding beside it as spans: the mark form lives on only in
// rows recorded before chips rode as spans.
let (history, _) = hub.subscribe_with_history(&key);
let saw_input = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, .. } => Some(text),
let question = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
_ => None,
});
assert!(
saw_input
.expect("the transcript saw the question")
.contains('\u{FFFC}'),
"the transcript keeps the compact chip form"
let (text, pastes) = question.expect("the transcript saw the question");
let payload = "fn main() {}\nfn other() {}";
assert_eq!(text, "review this:fn main() {}\nfn other() {}", "no marks");
assert_eq!(pastes.len(), 1, "the chip is one span");
assert_eq!(pastes[0].start, "review this:".len());
assert_eq!(pastes[0].end, "review this:".len() + payload.len());
assert_eq!(pastes[0].lines, 2);
}
/// The modern intake: chips ride as payloads beside their message,
/// each appending to it — no mark on the wire, the span record born
/// at the fold. A payload's carriage returns and stray marks
/// normalize there too, so a chip can never re-cut the scan.
#[tokio::test]
async fn a_staged_chip_rides_its_payload_beside_the_question() {
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
dispatcher
.ingest(user_event(
key.as_str(),
"review this:",
&["fn main() {}\r\nfn other() {}\u{FFFC}".to_owned()],
&[],
))
.expect("ingests");
driver.run_once().await.expect("the run happens");
// The model read the draft with the normalized payload
// appended: what the record says is what the request carried.
assert_eq!(
recorder.last_user_text(),
"review this:fn main() {}\nfn other() {}",
"the model saw the payload, normalized, in place"
);
let (history, _) = hub.subscribe_with_history(&key);
let question = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
_ => None,
});
let (text, pastes) = question.expect("the transcript saw the question");
let payload = "fn main() {}\nfn other() {}";
assert_eq!(text, format!("review this:{payload}"), "the plain form");
assert_eq!(pastes.len(), 1, "the chip is one span");
assert_eq!(pastes[0].start, "review this:".len());
assert_eq!(pastes[0].end, "review this:".len() + payload.len());
assert_eq!(pastes[0].lines, 2);
}
/// A scripted tool-call turn: the model asking for `name` with `args`.
@@ -1143,6 +1337,7 @@ mod tests {
args,
provider_data: serde_json::Value::Null,
})],
annotations: Default::default(),
},
stop_reason: StopReason::ToolUse,
usage: Usage::default(),
@@ -1253,8 +1448,8 @@ mod tests {
#[test]
fn user_events_carry_the_key_and_unique_ids() {
let first = user_event("interactive:web", "hello", &[]);
let second = user_event("interactive:web", "again", &[]);
let first = user_event("interactive:web", "hello", &[], &[]);
let second = user_event("interactive:web", "again", &[], &[]);
assert_eq!(first.source, "user");
assert_eq!(first.id, first.id, "stable within itself");
assert_ne!(first.id, second.id, "messages never share a dedup id");
@@ -1268,7 +1463,7 @@ mod tests {
/// order; a plain message carries no `images` key at all.
#[test]
fn user_events_carry_images_only_when_the_message_has_any() {
let bare = user_event("interactive:web", "plain", &[]);
let bare = user_event("interactive:web", "plain", &[], &[]);
assert_eq!(
bare.payload,
json!({"key": "interactive:web", "text": "plain"}),
@@ -1277,6 +1472,7 @@ mod tests {
let carried = user_event(
"interactive:web",
"look",
&[],
&[
WireImage {
media_type: "image/png".to_owned(),
@@ -1309,7 +1505,7 @@ mod tests {
Arc::new(VolatileStore::new()),
);
register_user(&dispatcher);
let event = user_event("interactive:web", "hello", &[]);
let event = user_event("interactive:web", "hello", &[], &[]);
// Ingesting resolves the key through the registered fn: the
// record lands under exactly the payload's key.
dispatcher.ingest(event).expect("ingests");
@@ -1344,11 +1540,13 @@ mod tests {
Content::Text("on it".into()),
Content::Text(" — done.".into()),
],
annotations: Default::default(),
};
assert_eq!(final_text(&message).as_deref(), Some("on it — done."));
let empty = Message {
role: Role::Assistant,
content: vec![Content::Text(" ".into())],
annotations: Default::default(),
};
assert_eq!(final_text(&empty), None);
}
@@ -1459,6 +1657,42 @@ mod tests {
assert!(err.contains("does not parse"), "{err}");
}
/// A session stashed before paste spans existed carries the embedded
/// form in its prompts; the restore pass rewrites it so a provider
/// never sees a mark, and the chip rides as the span note instead.
#[test]
fn a_legacy_stash_is_migrated_on_restore() {
let payload = "l1\nl2\nl3";
let embedded = format!("review this:\u{FFFC}{payload}\u{FFFC} please");
let stashed = json!({
"history": [
{
"role": "user",
"content": [embedded]
}
],
"driver_state": serde_json::Value::Null
});
let session = restore_session(&stashed, "interactive:web").expect("the legacy stash loads");
assert_eq!(
final_text(&session.history[0]),
Some(format!("review this:{payload} please")),
"the mark and its payload land as plain text"
);
let text = final_text(&session.history[0]).expect("the prompt is text");
// The chip rides as the span note: one span, over exactly the
// payload's range, and no mark survives the restore.
assert_eq!(
rhema_core::paste::spans(&session.history[0]).as_slice(),
&[rhema_core::paste::PasteSpan {
start: "review this:".len(),
end: "review this:".len() + payload.len(),
lines: 3,
}]
);
assert!(!text.contains('\u{FFFC}'), "no mark survives the restore");
}
/// The full dispatch, in-process: one message in, one scripted reply
/// out, the turn streamed through the hub, the conversation stashed.
#[tokio::test]
@@ -1507,7 +1741,7 @@ mod tests {
let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key);
dispatcher
.ingest(user_event(key.as_str(), "hello", &[]))
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
@@ -1520,7 +1754,8 @@ mod tests {
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
@@ -1596,7 +1831,7 @@ mod tests {
let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key);
dispatcher
.ingest(user_event(key.as_str(), "hello", &[]))
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
@@ -1616,7 +1851,7 @@ mod tests {
// Steer, in the route's order: ingest first, signal second.
dispatcher
.ingest(user_event(key.as_str(), "stop that", &[]))
.ingest(user_event(key.as_str(), "stop that", &[], &[]))
.expect("ingests");
assert!(registry.signal(key.as_str()));
@@ -1633,7 +1868,8 @@ mod tests {
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
@@ -1647,7 +1883,8 @@ mod tests {
receiver.try_recv().unwrap(),
TurnEvent::UserMessage {
text: "stop that".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
);
assert_eq!(
@@ -1821,6 +2058,7 @@ mod tests {
.ingest(user_event(
key.as_str(),
"look at this",
&[],
&[WireImage {
media_type: "image/png".to_owned(),
data: png.clone(),
@@ -1831,6 +2069,7 @@ mod tests {
.ingest(user_event(
key.as_str(),
"and at this",
&[],
&[WireImage {
media_type: "Image/JPEG".to_owned(),
data: jpeg.clone(),
@@ -1838,7 +2077,7 @@ mod tests {
))
.expect("ingests");
dispatcher
.ingest(user_event(key.as_str(), "no picture here", &[]))
.ingest(user_event(key.as_str(), "no picture here", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("the run happens"),
@@ -1851,7 +2090,11 @@ mod tests {
let question = history
.iter()
.find_map(|event| match event {
TurnEvent::UserMessage { text, images } => Some((text.clone(), images.clone())),
TurnEvent::UserMessage {
text,
pastes,
images,
} => Some((text.clone(), images.clone(), pastes.clone())),
_ => None,
})
.expect("the transcript saw the question");
@@ -1957,7 +2200,7 @@ mod tests {
// Dispatch 1: the model saves through the chain's memory tools.
dispatcher
.ingest(user_event(key.as_str(), "remember the channel", &[]))
.ingest(user_event(key.as_str(), "remember the channel", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("first run"),
@@ -1976,7 +2219,7 @@ mod tests {
// Dispatch 2: the model searches the same chain and answers from
// memory — a fresh session turn, the same durable store.
dispatcher
.ingest(user_event(key.as_str(), "where do releases go?", &[]))
.ingest(user_event(key.as_str(), "where do releases go?", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("second run"),
@@ -2064,7 +2307,7 @@ mod tests {
// Dispatch 1: the model writes SOUL.md through the chain. A key
// with a session continues, so both calls ride one key.
dispatcher
.ingest(user_event(key.as_str(), "call me claw", &[]))
.ingest(user_event(key.as_str(), "call me claw", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("first run"),
@@ -2083,7 +2326,7 @@ mod tests {
// Dispatch 2: USER.md, same chain — and the pending flag clears.
dispatcher
.ingest(user_event(key.as_str(), "and I am Ana", &[]))
.ingest(user_event(key.as_str(), "and I am Ana", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("second run"),
@@ -2141,7 +2384,7 @@ mod tests {
register_user(&dispatcher);
let key = Key::from("interactive:web");
dispatcher
.ingest(user_event(key.as_str(), "hello", &[]))
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
driver.run_once().await.expect("the run happens");
@@ -2281,7 +2524,7 @@ mod tests {
// An interactive reply is the chat surface's business: notified
// nowhere.
dispatcher
.ingest(user_event("interactive:web", "hello", &[]))
.ingest(user_event("interactive:web", "hello", &[], &[]))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("the run happens"),
@@ -2359,7 +2602,12 @@ mod tests {
// The evening's work, in the chat session.
dispatcher
.ingest(user_event(key.as_str(), "we shipped the claw tonight", &[]))
.ingest(user_event(
key.as_str(),
"we shipped the claw tonight",
&[],
&[],
))
.expect("ingests");
assert_eq!(
driver.run_once().await.expect("first run"),
+45 -11
View File
@@ -13,7 +13,7 @@
//! instance and job resolve through the store, the workspace is the
//! instance's path, the session blob (or a fresh agent) is loaded, the
//! allowlist is permissive exactly as the forge path's — and then one
//! `CodingAgent` turn runs. The final text lands in the job row and
//! `HostAgent` turn runs. The final text lands in the job row and
//! the user's notifications; the turn itself streams nowhere, its
//! observability is the stderr tool log.
//!
@@ -22,11 +22,13 @@
//! fails before any model call. The trust boundary is unchanged from
//! the forge path — the bearer-gated surface and the instance list.
use std::num::NonZeroU32;
use std::sync::Arc;
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
use rhema_coding_agent::{AllowAll, CodingAgent, CodingAgentConfig};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Event as ModelEvent, EventSink};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use crate::backends::BackendRegistry;
@@ -34,6 +36,7 @@ use crate::handler::final_text;
use crate::interactive::passthrough_key_fn;
use crate::job_store::{CodingJobStore, JobStatus};
use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
use crate::sandbox::SandboxState;
/// The source name the coding jobs ingest under.
pub const JOBS_SOURCE: &str = "jobs";
@@ -137,10 +140,13 @@ pub struct CodingJobHandler {
backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>,
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
/// Whether the jobs run the bounded request view (the config's
/// `transcript`, on unless set false).
transcript: bool,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>,
}
impl CodingJobHandler {
@@ -151,7 +157,7 @@ impl CodingJobHandler {
backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>,
max_turn_steps: u32,
max_turn_steps: NonZeroU32,
transcript: bool,
) -> Self {
Self {
@@ -160,9 +166,17 @@ impl CodingJobHandler {
notifications,
max_turn_steps,
transcript,
sandbox: None,
}
}
/// Shares the deployment's sandbox choice: a job's commands run
/// where it says, seeded from the instance's host path.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// One dispatch, failed with a reason on any step; every failure
/// lands in the job row before it lands in the outcome, so the
/// model's `status` read and the user's notification agree.
@@ -212,7 +226,11 @@ impl CodingJobHandler {
.map_err(|err| format!("job {job_id} could not start: {err}"))?;
let (provider, model) = self.backends.current();
let mut config = CodingAgentConfig::new(model, &workspace);
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(&workspace),
None => workspace.clone(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
config.max_turn_steps = self.max_turn_steps;
// A job's stashed session carries across runs and only ever
// grows; the view is what keeps a repeat run's steps cheap.
@@ -221,8 +239,18 @@ impl CodingJobHandler {
config.transcript = self
.transcript
.then(rhema_transcript::TranscriptSettings::default);
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display,
sandbox.executor(workspace.clone()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
}
}
let stashed = self
.store
.session(&instance_name)
@@ -236,9 +264,9 @@ impl CodingJobHandler {
self.fail(job_id, &instance_name, &reason);
reason
})?;
CodingAgent::from_session(provider, config, session)
HostAgent::from_session(config, session)
}
None => CodingAgent::new(provider, config),
None => HostAgent::new(config),
}
.map_err(|err| {
let reason = format!("cannot start the coding agent for {instance_name:?}: {err}");
@@ -248,12 +276,12 @@ impl CodingJobHandler {
// Commit-before-execute rides the dispatcher exactly as the
// forge handler's does: the intent is in the store before the
// first tool runs, and a crash-left dangling call revives at
// turn entry (CodingAgent::turn's own revive, over the resumed
// turn entry (HostAgent::turn's own revive, over the resumed
// session).
agent.set_commit_hook(Some(ctx.commit_hook()));
let mut sink = JobSink;
let output = match agent.turn(&job.prompt, &mut sink, Arc::new(AllowAll)).await {
let output = match agent.turn(&job.prompt, &mut sink).await {
Ok(output) => output,
Err(err) => {
let reason = format!("the coding turn for {instance_name:?} failed: {err}");
@@ -280,7 +308,7 @@ impl CodingJobHandler {
Ok(Outcome::Handled)
}
fn save_session(&self, instance: &str, agent: &CodingAgent) {
fn save_session(&self, instance: &str, agent: &HostAgent) {
match serde_json::to_string(agent.session()) {
Ok(blob) => {
let _ = self.store.save_session(instance, &blob);
@@ -360,7 +388,13 @@ mod tests {
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"),
);
CodingJobHandler::new(backends, store, notifications, 16, true)
CodingJobHandler::new(
backends,
store,
notifications,
NonZeroU32::new(16).unwrap(),
true,
)
}
fn reply(text: &str) -> ModelOutput {
+5 -1
View File
@@ -42,6 +42,8 @@
//! workspace files handed to the human as fetchable cards
//! - [`phone`] — the phone state and command queue: reported status to
//! read, consent-gated control actions the device executes
//! - [`sandbox`]: where `bash` runs, this host, or a remote daemon
//! speaking the sandbox protocol over HTTP
//! - [`watch_tools`] — the agent's watch-management tool set
//! - [`notify_tools`] — the `notify` tool: the queue a device polls
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
@@ -89,6 +91,7 @@ pub mod notifications;
pub mod notify_tools;
pub mod openai;
pub mod phone;
pub mod sandbox;
pub mod settings;
pub mod steer;
pub mod task_source;
@@ -105,7 +108,7 @@ pub use bootstrap::{
render_system,
};
pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, run_once};
pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
pub use environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource;
@@ -117,6 +120,7 @@ pub use interactive::InteractiveHandler;
pub use mock::MockLoop;
pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError};
pub use rhema_forge_integration::{ForgeKind, resolve_token};
pub use sandbox::{SandboxChoice, SandboxError, SandboxKind, SandboxState};
pub use settings::SettingsStore;
pub use task_source::{TASKS_SOURCE, TaskScheduler};
pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError};
+5 -5
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once};
use rhema_rsd::{DispatcherConfig, Outcome};
use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::Outcome;
/// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)]
@@ -74,9 +74,9 @@ async fn main() {
}
if let Some(Command::Vision { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1);
argv.push(std::ffi::OsString::from(rhema_agent_tools::vision::MODE));
argv.push(std::ffi::OsString::from(rhema_bash::vision::MODE));
argv.extend(rest.iter().cloned());
std::process::exit(rhema_agent_tools::vision::cli_run(&argv));
std::process::exit(rhema_bash::vision::cli_run(&argv));
}
if let Err(err) = run(args).await {
eprintln!("error: {err}");
@@ -135,7 +135,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on.
config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts");
let daemon = Daemon::build(&config, backends, DispatcherConfig::default())?;
let daemon = Daemon::build(&config, backends, forge_dispatch())?;
daemon.run().await
}
}
+8 -3
View File
@@ -9,7 +9,7 @@
use std::collections::BTreeSet;
use std::sync::{Arc, OnceLock};
use rhema_coding_agent::CodingAgentConfig;
use rhema_host_agent::HostAgentConfig;
/// What one wiring produced, held for the process.
struct Wired {
@@ -61,7 +61,7 @@ fn wired() -> Option<&'static Wired> {
/// init file, the socket, the token), the prompt's `mcp` lines, and
/// the persisted off switch. A frontend without wiring changes
/// nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) {
pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else {
return;
};
@@ -82,7 +82,12 @@ mod tests {
/// same map).
#[test]
fn apply_without_any_wiring_leaves_the_config_alone() {
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
let before = config.shell_env.clone();
apply(&mut config);
// The wiring only appears when the machine's global mcp.yaml
+1
View File
@@ -65,6 +65,7 @@ impl ModelProvider for MockLoop {
message: Message {
role: Role::Assistant,
content: vec![Content::Text(text)],
annotations: Default::default(),
},
stop_reason: StopReason::EndTurn,
usage: Usage::default(),
+1
View File
@@ -259,6 +259,7 @@ pub async fn chat_completions(
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
key.as_str(),
&input.text,
&[],
&input.images,
)) {
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
+774
View File
@@ -0,0 +1,774 @@
//! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP, or an ssh login on a far
//! box.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end. The tool spec, approval gate,
//! output caps, and error shaping stay in `ShellTools`; only the
//! machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes the workspace root and, when it is
//! empty, sends the host workspace as a tarball through the seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use base64::Engine as _;
use rhema_bash::exec::{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;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path the http sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The ssh sandbox's default workspace base: the remote login's own
/// home, the ssh backend's documented default. One directory per claw
/// workspace lands under it, named by the session hash.
pub const SSH_WORKSPACE_ROOT: &str = "/root";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
const PROBE_TIMEOUT: Duration = Duration::from_secs(20);
/// Which machine runs the shell.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxKind {
/// The daemon's own host, the original path.
#[default]
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
}
impl SandboxKind {
/// The stored spelling.
pub fn as_str(self) -> &'static str {
match self {
Self::Local => "local",
Self::Http => "http",
Self::Ssh => "ssh",
}
}
/// Parses a stored spelling. Anything else is `None`, which every
/// caller turns into the local default.
pub fn parse(value: &str) -> Option<Self> {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
"ssh" => Some(Self::Ssh),
_ => None,
}
}
}
/// One sandbox choice: the kind and whatever it needs. `local` needs
/// nothing; `http` needs a base URL and may carry a token.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct SandboxChoice {
/// The machine kind.
pub kind: SandboxKind,
/// The `http` sandbox's base URL, no trailing slash after
/// normalization.
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// The `ssh` sandbox's destination, passed to `ssh` as-is: any
/// alias or `user@host` the local config resolves.
#[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>,
}
impl SandboxChoice {
/// Trims the strings, drops blank ones, and validates what `http`
/// needs to run. A choice that fails reads as a 400 at the route,
/// never as a silent fallback.
pub fn normalized(mut self) -> Result<Self, SandboxError> {
self.url = self
.url
.map(|url| url.trim().trim_end_matches('/').to_owned())
.filter(|url| !url.is_empty());
self.token = self
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
self.host = self
.host
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty());
self.workspace = self
.workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty());
if self.kind == SandboxKind::Ssh {
let host = self
.host
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the ssh sandbox needs a host".to_owned()))?;
if host.contains(char::is_whitespace) {
return Err(SandboxError::Invalid(
"the ssh sandbox host is one destination, no spaces".to_owned(),
));
}
if let Some(workspace) = self.workspace.as_deref()
&& !workspace.starts_with('/')
{
return Err(SandboxError::Invalid(
"the ssh sandbox workspace must be an absolute path".to_owned(),
));
}
}
if self.kind == SandboxKind::Http {
let url = self
.url
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the http sandbox needs a url".to_owned()))?;
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err(SandboxError::Invalid(
"the http sandbox url must start with http:// or https://".to_owned(),
));
}
}
Ok(self)
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind != SandboxKind::Local
}
/// The remote directory one workspace's commands run in: the
/// protocol root for `http`, a directory per host workspace under
/// the configured base for `ssh`.
pub fn remote_root(&self, host: &Path) -> PathBuf {
match self.kind {
SandboxKind::Http => PathBuf::from(REMOTE_WORKSPACE),
SandboxKind::Ssh => PathBuf::from(format!(
"{}/{}",
self.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT),
session_name(host)
)),
SandboxKind::Local => host.to_path_buf(),
}
}
}
/// Why a sandbox choice or operation failed.
#[derive(Debug, thiserror::Error)]
pub enum SandboxError {
/// The choice cannot run as written.
#[error("{0}")]
Invalid(String),
/// The settings table failed.
#[error("sandbox store failed: {0}")]
Store(String),
}
/// The chosen sandbox and the executors built over it, shared by every
/// handler so a switch takes effect on the next turn without a restart.
pub struct SandboxState {
choice: RwLock<SandboxChoice>,
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<dyn Sandbox>>>,
}
impl SandboxState {
/// The state over `settings`, seeded by `seed` when no choice was
/// stored. `local_workspace` is the chat workspace the settings
/// surface reports; `shell_env` is layered over local commands.
pub fn load(
settings: Arc<SettingsStore>,
seed: Option<SandboxChoice>,
local_workspace: PathBuf,
shell_env: &BTreeMap<String, String>,
) -> Result<Self, SandboxError> {
let stored = settings
.get(SANDBOX_KEY)
.map_err(|err| SandboxError::Store(err.to_string()))?;
let choice = stored
.as_deref()
.and_then(|raw| serde_json::from_str::<SandboxChoice>(raw).ok())
.and_then(|choice| choice.normalized().ok())
.or_else(|| seed.and_then(|choice| choice.normalized().ok()))
.unwrap_or_default();
Ok(Self {
choice: RwLock::new(choice),
settings,
local_workspace,
local: default_executor_with(shell_env),
remote: Mutex::new(HashMap::new()),
})
}
/// The current choice.
pub fn choice(&self) -> SandboxChoice {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.is_remote()
}
/// Saves and applies a choice. The next turn reads it; nothing is
/// rebuilt in place. Answers the normalized choice that was stored.
pub fn set(&self, choice: SandboxChoice) -> Result<SandboxChoice, SandboxError> {
let choice = choice.normalized()?;
let raw =
serde_json::to_string(&choice).map_err(|err| SandboxError::Store(err.to_string()))?;
self.settings
.set(SANDBOX_KEY, &raw)
.map_err(|err| SandboxError::Store(err.to_string()))?;
*self.choice.write().unwrap_or_else(PoisonError::into_inner) = choice.clone();
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
Ok(choice)
}
/// The workspace a handler should name and start commands in: the
/// host path locally, the choice's remote root otherwise.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
self.choice().remote_root(host)
}
/// The chat workspace under the current choice, for the settings
/// surface.
pub fn workspace(&self) -> PathBuf {
self.workspace_for(&self.local_workspace)
}
/// The host workspace path, whatever the current choice.
pub fn local_workspace(&self) -> &Path {
&self.local_workspace
}
/// An executor for one host workspace. Remote sessions are derived
/// from the workspace path, so two workspaces never share a root.
pub fn executor(
self: &Arc<Self>,
host_workspace: impl Into<PathBuf>,
) -> Arc<dyn ShellExecutor> {
Arc::new(ClawShell {
state: Arc::clone(self),
host_workspace: host_workspace.into(),
local: self.local.clone(),
seeded: AtomicBool::new(false),
last: Mutex::new(None),
})
}
/// The cached sandbox for one session. The map is cleared whenever
/// the choice changes, so a new URL, token, host, or base builds a
/// new client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<dyn Sandbox>, ShellError> {
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(sandbox) = remote.get(&session) {
return Ok(sandbox.clone());
}
}
let sandbox: Arc<dyn Sandbox> = match choice.kind {
SandboxKind::Http => {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
}
SandboxKind::Ssh => {
let dest = choice
.host
.as_deref()
.ok_or_else(|| ShellError::Failed("the ssh sandbox has no host".to_owned()))?;
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
Arc::new(
SshSandbox::new(dest.to_owned()).with_workspace(format!("{base}/{session}")),
)
}
SandboxKind::Local => {
return Err(ShellError::Failed(
"the local sandbox needs no remote client".to_owned(),
));
}
};
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(session, sandbox.clone());
Ok(sandbox)
}
}
/// One handler's view of the choice: local commands go straight to the
/// host executor; remote commands go through the sandbox, seeded from
/// the host workspace once per choice.
struct ClawShell {
state: Arc<SandboxState>,
host_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
seeded: AtomicBool,
last: Mutex<Option<SandboxChoice>>,
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty workspace root gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox. The
/// probe makes the root first: the http daemon keeps one, the ssh
/// far end has none until something makes it, and the unpack's
/// `tar -C` would fail on a missing directory.
async fn seed(
&self,
sandbox: &Arc<dyn Sandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = |_line: &str| {};
let probe = sandbox
.exec(
ExecRequest {
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone(),
timeout: PROBE_TIMEOUT,
},
cancelled,
&mut sink,
)
.await
.map_err(protocol_error)?;
if !probe.stdout.is_empty() {
return Ok(());
}
let root = self.host_workspace.clone();
let archive = tokio::task::spawn_blocking(move || tarball(&root))
.await
.map_err(|err| {
ShellError::Failed(format!("the workspace archive task failed: {err}"))
})??;
let Some(tar_gz_base64) = archive else {
return Ok(());
};
sandbox
.seed(&WorkspaceSeed::Tarball {
name: "workspace.tar.gz".to_owned(),
tar_gz_base64,
})
.await
.map_err(protocol_error)?;
Ok(())
}
}
#[async_trait]
impl ShellExecutor for ClawShell {
async fn run(
&self,
command: &str,
cwd: &Path,
timeout: Duration,
cancelled: &AtomicBool,
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
) -> Result<Executed, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self
.local
.run(command, cwd, timeout, cancelled, progress)
.await;
}
{
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
if last.as_ref() != Some(&choice) {
*last = Some(choice.clone());
self.seeded.store(false, Ordering::Relaxed);
}
}
let sandbox = self.state.remote_sandbox(&choice, &self.host_workspace)?;
if !self.seeded.load(Ordering::Relaxed) {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let root = choice.remote_root(&self.host_workspace);
ShellSandbox::new(sandbox)
.run(command, &root, timeout, cancelled, progress)
.await
}
}
/// Maps a protocol failure onto the shell error the tool shapes into an
/// `is_error` result.
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still
// a failure, reported in-band with its own text.
_ => ShellError::Failed(err.to_string()),
}
}
/// One path quoted for the remote `bash -c`: single quotes, the
/// closing quote spliced, good for every path a workspace root can
/// have.
fn shquote(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
/// The sandbox session name for one host workspace: a stable FNV-1a
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
fn session_name(host: &Path) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in host.to_string_lossy().as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("rhema-claw-{hash:016x}")
}
/// One host workspace as a gzipped tar, base64 for the protocol.
/// `None` when the directory is missing or empty: nothing to seed.
fn tarball(root: &Path) -> Result<Option<String>, ShellError> {
if !root.is_dir() {
return Ok(None);
}
let mut entries = std::fs::read_dir(root)
.map_err(|err| ShellError::Failed(format!("cannot read the workspace {root:?}: {err}")))?;
if entries.next().is_none() {
return Ok(None);
}
let output = std::process::Command::new("tar")
.arg("-czf")
.arg("-")
.arg("-C")
.arg(root)
.arg(".")
.output()
.map_err(|err| {
ShellError::Failed(format!("cannot archive the workspace with tar: {err}"))
})?;
if !output.status.success() {
let detail = String::from_utf8_lossy(&output.stderr);
let detail = detail.trim();
return Err(ShellError::Failed(if detail.is_empty() {
"tar failed to archive the workspace".to_owned()
} else {
format!("tar failed to archive the workspace: {detail}")
}));
}
Ok(Some(
base64::engine::general_purpose::STANDARD.encode(output.stdout),
))
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn state(choice: SandboxChoice) -> Arc<SandboxState> {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
Arc::new(
SandboxState::load(
settings,
Some(choice),
PathBuf::from("/state/claw/workspaces/interactive"),
&BTreeMap::new(),
)
.expect("the state loads"),
)
}
#[test]
fn a_bare_choice_is_local() {
let choice = SandboxChoice::default().normalized().unwrap();
assert_eq!(choice.kind, SandboxKind::Local);
assert!(!choice.is_remote());
assert_eq!(choice.kind.as_str(), "local");
}
#[test]
fn an_http_choice_needs_an_absolute_url() {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a URL is required");
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn an_ssh_choice_needs_a_host_and_an_absolute_base() {
let missing = SandboxChoice {
kind: SandboxKind::Ssh,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a host is required");
let spaced = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me @box".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(spaced.is_err(), "a destination is one word");
let relative = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("srv/claw".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "the base is an absolute path");
let good = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some(" me@box ".to_owned()),
workspace: Some("/srv/claw/".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(good.host.as_deref(), Some("me@box"));
assert_eq!(good.workspace.as_deref(), Some("/srv/claw"));
assert!(good.is_remote());
assert_eq!(good.kind.as_str(), "ssh");
assert_eq!(
SandboxKind::parse("ssh"),
Some(SandboxKind::Ssh),
"the stored spelling round-trips"
);
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
..SandboxChoice::default()
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
state.choice().url.as_deref(),
Some("http://box:7600"),
"the trailing slash is trimmed"
);
}
#[test]
fn an_ssh_workspace_is_one_directory_per_host_workspace() {
let host = PathBuf::from("/state/claw/workspaces/interactive");
let choice = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
};
let root = choice.remote_root(&host);
let root = root.to_string_lossy().to_string();
assert!(
root.starts_with("/srv/claw/rhema-claw-"),
"the root lives under the configured base: {root}"
);
assert_eq!(root.len(), "/srv/claw/rhema-claw-".len() + 16);
let default_root = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
..SandboxChoice::default()
}
.remote_root(&host);
assert_eq!(
default_root.to_string_lossy(),
format!("/root/{}", session_name(&host)),
"the base defaults to the login's home"
);
}
#[test]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
assert_eq!(state.choice().kind, SandboxKind::Local);
state
.set(SandboxChoice {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Http);
assert_eq!(reloaded.choice().url.as_deref(), Some("https://box:7600"));
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[test]
fn an_ssh_choice_persists_with_its_host_and_base() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
state
.set(SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Ssh);
assert_eq!(reloaded.choice().host.as_deref(), Some("me@box"));
assert_eq!(reloaded.choice().workspace.as_deref(), Some("/srv/claw"));
assert_eq!(
reloaded.workspace().to_string_lossy(),
format!("/srv/claw/{}", session_name(Path::new("/tmp/ws"))),
"the settings surface reports the session root"
);
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
// The emptiness probe: nothing at /workspace.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "",
"stderr": "",
"timed_out": false
})))
.up_to_n_times(1)
.mount(&server)
.await;
// The command itself.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "hi\n",
"stderr": "",
"timed_out": false
})))
.mount(&server)
.await;
// The seed: accepted, and the host workspace is not empty.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/seed$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"error": null
})))
.expect(1)
.mount(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("README.md"), "seed me").expect("the file writes");
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
..SandboxChoice::default()
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = |_line: &str| {};
let executed = executor
.run(
"echo hi",
Path::new(REMOTE_WORKSPACE),
Duration::from_secs(5),
&cancelled,
&mut sink,
)
.await
.expect("the remote command answers");
assert_eq!(executed.stdout, b"hi\n");
assert_eq!(executed.code, Some(0));
}
}
+3 -1
View File
@@ -325,6 +325,7 @@ mod tests {
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new(),
},
text_delta("hi"),
],
@@ -348,7 +349,8 @@ mod tests {
0,
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new()
images: Vec::new(),
pastes: Vec::new()
}
),
(1, text_delta("hi")),
+14 -15
View File
@@ -9,21 +9,15 @@
#![forbid(unsafe_code)]
use std::sync::{Arc, OnceLock};
use std::sync::Arc;
use rhema_coding_agent::CodingAgentConfig;
use rhema_host_agent::HostAgentConfig;
static WIRED: OnceLock<Option<Arc<rhema_agent_tools::vision::Wiring>>> = OnceLock::new();
/// The daemon's wiring, established at first use and kept for the
/// process's life. `None` only when provisioning failed, cached like
/// every answer this static gives.
pub(crate) fn wired() -> Option<&'static Arc<rhema_agent_tools::vision::Wiring>> {
WIRED
.get_or_init(|| {
rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV")).map(Arc::clone)
})
.as_ref()
/// The daemon's wiring, provisioned at first use and kept for the
/// process's life — the toolkit's own process-wide cache holds it, so
/// `None` only when provisioning failed, and a failure does not retry.
pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
}
/// The init file a later provisioner chains through — `None` when the
@@ -36,7 +30,7 @@ pub(crate) fn init_path() -> Option<std::ffi::OsString> {
/// Layers the wiring onto one agent config: the shell env map (the
/// init file, the binary, the staging directory) and the prompt's
/// vision section. A frontend without wiring changes nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) {
pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else {
return;
};
@@ -52,7 +46,12 @@ mod tests {
/// values are constants, so extending twice is the same map.
#[test]
fn apply_twice_is_apply_once() {
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
apply(&mut config);
let once = config.shell_env.clone();
apply(&mut config);
+1
View File
@@ -93,6 +93,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+1
View File
@@ -59,6 +59,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+253
View File
@@ -34,6 +34,7 @@ fn reply(text: &str) -> ModelOutput {
fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput {
ModelOutput {
message: Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall {
id: id.to_owned(),
@@ -65,6 +66,7 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
tools_bin: None,
ingest_token: None,
transcript: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -668,6 +670,77 @@ async fn chat_messages_carry_images_into_the_attachment_store() {
);
}
/// A staged chip rides beside its draft and records as spans: the
/// echo on the stream and the stashed session both carry the plain
/// text with the `rhema-code` annotation beside it, and no mark ever
/// crosses the wire.
#[tokio::test]
async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
let provider = Arc::new(MockProvider::new([reply("on it")]));
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(provider),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// The chip rides as a payload beside the plain draft.
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({
"text": "review this:",
"pastes": ["fn main() {}\nfn other() {}"],
}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
// The echo on the stream: the payload in place, the span record
// beside it, no marks in the text.
let events = client
.get(format!("{base}/v1/sessions/interactive:web/events"))
.send()
.await
.expect("the events request goes out");
let mut stream = sse_body(events).await;
let mut seen = String::new();
read_until(&mut stream, &mut seen, r#""type":"turn_done""#).await;
assert!(
seen.contains(r#""type":"user_message","text":"review this:fn main() {}\nfn other() {}""#),
"the echo carries the composed plain form: {seen}"
);
assert!(
seen.contains(r#""pastes":[{"start":12,"end":38,"lines":2}]"#),
"the chip notes itself as the span it stands for: {seen}"
);
assert!(!seen.contains('\u{FFFC}'), "no marks ride the wire: {seen}");
// The stash: the checkpoint's user message carries the payload in
// the text and the annotation that outlives the turn.
let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
let key = ResourceKey::from("interactive:web");
let record = store
.load(&key)
.expect("the record loads")
.expect("the key has a record");
let stashed: Session =
serde_json::from_value(record.session.expect("a session").core.driver_state)
.expect("the stash parses");
let ask = stashed
.history
.iter()
.find(|message| message.role == Role::User)
.expect("the question is stashed");
assert_eq!(rhema_core::paste::spans(ask).len(), 1);
assert_eq!(rhema_core::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_core::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2);
}
/// A turn nobody watched is still replayable: a client arriving after
/// the fact — a reloaded browser, a reopened phone — subscribes cold and
/// gets the finished turns back before the live feed. The same holds
@@ -2238,6 +2311,186 @@ async fn providers_gain_and_lose_backends_over_the_surface() {
assert_eq!(gone.status(), 400);
}
/// The sandbox surface: the default is this host, a remote choice
/// persists across a rebuild, the token is write-only, and a choice
/// without a URL or with an unknown kind is refused.
#[tokio::test]
async fn the_sandbox_choice_is_listed_and_switchable() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let listed: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(listed["kind"], "local");
assert_eq!(listed["token_set"], false);
assert_eq!(listed["remote_workspace"], "/workspace");
assert!(
listed["workspace"]
.as_str()
.is_some_and(|path| !path.is_empty())
);
// A remote choice: the URL and token go in, the token never comes
// back.
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "http",
"url": "https://box.example:7600/",
"token": "s3cret"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "http");
assert_eq!(switched["url"], "https://box.example:7600");
assert_eq!(switched["token_set"], true);
assert_eq!(switched["workspace"], "/workspace");
assert!(
switched.get("token").is_none(),
"the token stays write-only"
);
// A remote choice without a URL is a 400, and an unknown kind too.
let missing = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "http", "url": ""}))
.send()
.await
.expect("the refusal posts");
assert_eq!(missing.status(), 400);
let unknown = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "quantum"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(unknown.status(), 400);
// Back to this host: the remote fields stay staged for the next
// switch, and the workspace path flips with the choice.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["token_set"], true);
// The persisted choice wins after a restart.
drop(base);
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon rebuilds");
let base = serve(&daemon).await;
let reloaded: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(reloaded["kind"], "local");
assert_eq!(reloaded["token_set"], true);
// `clear_token` drops the stored secret without moving the URL.
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local", "clear_token": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["token_set"], false);
assert_eq!(cleared["url"], "https://box.example:7600");
}
/// The 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.
#[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}"
);
// 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,
+1
View File
@@ -66,6 +66,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ FROM debian:stable-slim
# bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+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 git ca-certificates \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+2 -2
View File
@@ -3,5 +3,5 @@ name: rhema-claw
description: "The resident forge-watching agent daemon: forge watches and a
chat HTTP surface over one SQLite store."
type: application
version: 0.1.0
appVersion: "0.1.0"
version: 0.4.0
appVersion: "0.4.0"
@@ -15,10 +15,10 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's
rhema-autonomous-agent = "0.2.3"
rhema-autonomous-agent = "0.4.1"
# The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's
rhema-rsd = "0.2.3"
rhema-rsd = "0.4.1"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -13,7 +13,7 @@ publish = false
[dependencies]
# The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = "0.2.3"
rhema-rsd = "0.4.1"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -230,6 +230,17 @@ pub struct Notification {
/// When the notification row was last touched. The poll cursor
/// advances to the newest of these.
pub timestamp: Timestamp,
/// What the backend's read-marking route keys on, when it has one —
/// GitHub's `PUT /notifications/threads/{id}` takes the numeric
/// notification id, which [`Notification::id`] embeds only as text
/// (its suffix is the dedup timestamp, not the row's identity).
/// `None` on a backend with no read route.
///
/// Defaulted on deserialize: rows already in a dispatcher inbox were
/// written before this field existed, and a replay must not fail on
/// one.
#[serde(default)]
pub read_key: Option<String>,
/// The untouched wire row, minus the keys the notification lifts.
pub raw: serde_json::Value,
}
@@ -16,7 +16,9 @@
use async_trait::async_trait;
use crate::error::ForgeError;
use crate::event::{ForgeEvent, ForgeThreadKind, NotificationPage, RepoRef, Snapshot, Timestamp};
use crate::event::{
ForgeEvent, ForgeThreadKind, Notification, NotificationPage, RepoRef, Snapshot, Timestamp,
};
/// One poll's worth of activity, with the cursor to continue from.
#[derive(Debug, Clone, PartialEq)]
@@ -100,6 +102,25 @@ pub trait Forge: Send + Sync {
since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>;
/// Marks `notification` read on the forge, so the account's feed
/// stops returning it.
///
/// The feed is at-least-once: `since` is inclusive at the boundary
/// and the cursor only ever advances to the newest row seen, so a row
/// that the poll cannot get past — anything at or before the cursor,
/// every poll — comes back for as long as the forge considers it
/// unread. Dedup ids absorb a repeat *within* one pass, but a row
/// re-read on the next pass is a fresh event with the same id, and a
/// restart drops the in-memory cursor entirely and asks for the whole
/// unread feed again. Deciding a row is therefore not the same as
/// consuming it; this is the call that consumes it.
///
/// The default is a no-op: a backend with no read route repeats its
/// rows, which its dedup ids absorb — noisier, never wrong.
async fn mark_read(&self, _notification: &Notification) -> Result<(), ForgeError> {
Ok(())
}
/// The login this client authenticates as — the backend's own answer
/// to "who am I".
///
@@ -585,6 +585,9 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(),
url: None,
timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()),
}))
}
@@ -120,6 +120,17 @@ impl GitHubForge {
}
}
/// A PUT builder for `path` with auth applied.
fn put(&self, path: &str) -> reqwest::RequestBuilder {
let base = &self.base_url;
let request = self.http.put(format!("{base}{path}"));
if self.token.is_empty() {
request
} else {
request.bearer_auth(&self.token)
}
}
/// Follows `per_page`/`page` pagination until a short page.
async fn paged<T: DeserializeOwned>(
&self,
@@ -287,7 +298,9 @@ struct WireComment {
/// One row of the account notifications feed.
#[derive(Debug, Clone, Deserialize)]
struct WireNotification {
#[serde(default)]
/// GitHub sends this one as a JSON string, unlike every other id in
/// this adapter; see [`lenient_id`].
#[serde(default, deserialize_with = "lenient_id")]
id: Option<i64>,
#[serde(default)]
reason: Option<String>,
@@ -452,6 +465,32 @@ fn parent_number(url: &str) -> Option<u64> {
url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
}
/// An id that arrives as either a JSON number or a JSON string.
///
/// GitHub's notifications feed is the odd one out: `id` there is a
/// string (`"27210544329"`), while issues, comments and reviews send
/// numbers. One row that refuses to decode fails the whole page, so the
/// notification id is read leniently.
fn lenient_id<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum IdWire {
Number(i64),
Text(String),
}
match Option::<IdWire>::deserialize(deserializer)? {
None => Ok(None),
Some(IdWire::Number(n)) => Ok(Some(n)),
Some(IdWire::Text(text)) => text.trim().parse().map(Some).map_err(|_| {
serde::de::Error::custom(format!("notification id is not a number: {text}"))
}),
}
}
/// The notification a notifications row carries. GitHub's `reason` field
/// is the row's whole why; the subject's API URL yields the thread.
fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> {
@@ -481,6 +520,9 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(),
url: None,
timestamp: updated,
// `PUT /notifications/threads/{id}` is keyed on this same id:
// the notification, not the thread's number.
read_key: Some(id.to_string()),
raw: Value::Object(row.raw.clone()),
}))
}
@@ -708,6 +750,22 @@ impl Forge for GitHubForge {
}
Ok(NotificationPage::finish(notifications, since))
}
async fn mark_read(&self, notification: &Notification) -> Result<(), ForgeError> {
let Some(read_key) = notification.read_key.as_deref() else {
// A row built without one is a shape break, not a forge
// outage: say so instead of silently re-reading it forever.
return Err(ForgeError::Parse(format!(
"notification {} carries no read key",
notification.id
)));
};
let path = format!("/notifications/threads/{read_key}");
let response = self.put(&path).send().await.map_err(ForgeError::network)?;
// 205 Reset Content: marked, nothing to decode.
ensure_success(response).await?;
Ok(())
}
}
#[cfg(test)]
@@ -870,4 +928,63 @@ mod tests {
assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3");
assert!(event.raw.get("title").is_none());
}
fn notification(json: &str) -> WireNotification {
serde_json::from_str(json).expect("notification fixture parses")
}
// Captured from the live feed on 2026-11-21: `id` there is a string,
// and one such row used to fail the whole page's decode.
#[test]
fn a_notification_id_sent_as_a_string_decodes() {
let row = notification(
r#"{"id": "27210544329", "unread": true, "reason": "mention",
"updated_at": "2026-11-21T22:33:00Z", "last_read_at": null,
"subject": {"title": "Snap build failed for v2.5.1",
"url": "https://api.github.com/repos/acme/widgets/issues/10",
"latest_comment_url": "https://api.github.com/repos/acme/widgets/issues/comments/7070",
"type": "Issue"},
"repository": {"id": 1239653662, "full_name": "acme/widgets"},
"url": "https://api.github.com/notifications/threads/27210544329"}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 10);
assert_eq!(notification.repo, RepoRef::new("acme", "widgets"));
assert_eq!(notification.reason, NotificationReason::Mention);
assert!(!notification.is_pr);
assert_eq!(
notification.id,
"github:notification:27210544329@2026-11-21T22:33:00Z"
);
assert_eq!(notification.read_key.as_deref(), Some("27210544329"));
}
#[test]
fn a_notification_id_sent_as_a_number_still_decodes() {
let row = notification(
r#"{"id": 42188, "reason": "review_requested",
"updated_at": "2026-10-08T12:00:00Z",
"subject": {"title": "tidy the parser", "type": "PullRequest",
"url": "https://api.github.com/repos/acme/widgets/pulls/8"},
"repository": {"full_name": "acme/widgets"}}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 8);
assert!(notification.is_pr);
assert_eq!(
notification.id,
"github:notification:42188@2026-10-08T12:00:00Z"
);
assert_eq!(notification.read_key.as_deref(), Some("42188"));
}
#[test]
fn a_notification_id_that_is_not_a_number_is_a_parse_error() {
let err = serde_json::from_str::<WireNotification>(r#"{"id": "not-a-number"}"#)
.expect_err("a junk id is loud, not silently dropped");
assert!(err.to_string().contains("not-a-number"), "got: {err}");
}
}
@@ -331,6 +331,9 @@ fn todo_notification(row: &WireTodo) -> Result<Option<Notification>, ForgeError>
title: target.title.clone(),
url: row.target_url.clone(),
timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()),
}))
}
@@ -97,6 +97,7 @@ mod tests {
title: None,
url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
}
}
@@ -2,8 +2,8 @@
//! wiremock server. Zero network.
use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, NotificationReason, RepoRef,
Timestamp,
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, Notification, NotificationReason,
RepoRef, Timestamp,
};
use serde_json::{Value, json};
use wiremock::matchers::{header, method, path, query_param};
@@ -533,6 +533,89 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
);
}
/// A notification row, as the account's feed sends it.
fn notification_row(id: i64, reason: &str, number: u64) -> Value {
json!({
"id": id,
"unread": true,
"reason": reason,
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": format!("https://api.github.com/repos/acme/widgets/issues/{number}"),
"type": "Issue"
},
"repository": { "full_name": "acme/widgets" }
})
}
/// Deciding a row is not consuming it: the feed keeps returning anything
/// the account still has unread, so the read route is what ends the
/// repeat. It keys on the notification's own id, not the thread number —
/// the dedup id keeps that integer only as text.
#[tokio::test]
async fn marking_a_notification_read_puts_its_thread() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([notification_row(
42188,
"review_requested",
142
)])),
)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/notifications/threads/42188"))
.and(header("authorization", "Bearer tok"))
.respond_with(ResponseTemplate::new(205))
.mount(&server)
.await;
let forge = forge(&server);
let page = forge.notifications(None).await.expect("poll succeeds");
let notification = &page.notifications[0];
forge.mark_read(notification).await.expect("marks read");
let requests = server.received_requests().await.expect("recording is on");
let puts: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(puts.len(), 1, "one read call, on the row's id");
assert_eq!(puts[0].url.path(), "/notifications/threads/42188");
}
/// A row that reaches the caller with no read key is a shape break, not a
/// silent no-op: re-reading the same thread forever is the failure this
/// whole route exists to stop.
#[tokio::test]
async fn a_notification_without_a_read_key_fails_loudly() {
// Defaulted on deserialize, so this is also the row an inbox written
// before the field existed decodes to.
let notification: Notification = serde_json::from_value(json!({
"id": "github:notification:42188@2026-10-05T12:00:00Z",
"reason": "review_requested",
"repo": { "owner": "acme", "name": "widgets" },
"number": 142,
"is_pr": false,
"actor": null,
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-05T12:00:00Z",
"raw": {}
}))
.expect("a read-key-less row parses");
let err = GitHubForge::new("tok")
.mark_read(&notification)
.await
.expect_err("loud failure");
assert!(matches!(err, ForgeError::Parse(_)), "got: {err:?}");
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
+397
View File
@@ -0,0 +1,397 @@
# rhema-tools — the claw's model-facing tools as bash skills + thin clients
*One project, independent of the claw: the resident's data tools become small
executables and the markdown that teaches them, speaking the daemon's existing
HTTP surface through a scoped agent credential.*
## 0. Scope
This spec moves the claw's model-facing data tools out of the daemon binary and
its system prompt. After it, the model's view of tasks, watches, identity,
notifications, and the phone is: `bash`, a handful of short-named executables
on `PATH`, and one markdown skill per domain. The daemon keeps the state, the
schedulers, and the sources; the tools project owns everything the model
touches.
Two consumers change:
- the model, which stops seeing sixteen tool schemas on every step of every
session and starts composing tool calls in the shell;
- the claw, which stops being the only place a tool can live;
- tool authors — users or the agent itself — who can add a capability without
touching rhema at all (§8).
Non-goals v1: extracting the server side (stores, schedulers, sources) out of
the claw; extracting memory, attachments, or the bootstrap prompt; any
transport other than the daemon's existing HTTP surface; a daemon-side timer
service (tier-1 tools use system schedulers; §8).
## 1. Problem statement
The claw's tools are native: one `TOOL.yaml` manifest and one Rust builtin per
tool, resolved through the `ClawExtension` chain, rendered as a JSON-schema
bullet into every `SYSTEM.md` render. Sixteen of them today, and the list
grows with every feature.
Four costs, all structural:
1. **Context.** Every session pays the schema of every tool on every step, the
resident's whole life long, whether or not the turn touches them.
2. **Round trips.** "Unwatch every archived repo" is one native call per repo —
one model step each. The model cannot loop, filter, or pipeline across tool
results; only the harness can.
3. **Coupling.** A new tool is a manifest, a builtin, an extension-struct line,
and a registry test — all inside `rhema-claw`. Nothing tool-shaped can be
written, versioned, or shipped without the daemon crate.
4. **Reuse.** A second agent (a forge worker, a phone-side helper) cannot share
the tools without depending on the daemon's binary.
That is the signal that the tool surface is a missing boundary, not a missing
feature list. The boundary is a wire contract.
## 2. Design goals
- The model-facing surface is code: `bash` + executables + skills. Skills are
read when a domain is relevant; `--help` is always current.
- The tools project compiles with zero `rhema-claw` dependencies. Independence
is a dependency arrow, not a directory layout, and CI enforces the arrow.
- The daemon's state stays in the daemon. Clients hold no stores, no
schedulers, no caches; they are request printers.
- One trust boundary, made explicit and enforced: a scoped agent credential
that cannot answer consents, forge chats, or ingest events.
- Incremental: each domain migrates alone, and its native tool stays until its
client ships.
## 3. The shape
Three pieces:
1. **Skills.** One markdown file per domain, shipped next to its binary and
installed into the global skills directory that
`rhema_agent_tools::skills::discover` already reads. The skill carries the
examples; the binary carries the behavior; they never drift apart because
they are versioned and installed together.
2. **Thin clients.** One short-named executable per domain: `notify`, `tasks`,
`watches`, `identity`, `phone`. Parse arguments, make one or a few HTTP
calls, print JSON, exit.
3. **The contract.** The daemon's `/v1` HTTP surface — the same routes the web
UI and the phone client already speak. The contract is the tools project's
entire knowledge of the claw.
One call, end to end — `schedule_task` becoming `tasks add`:
1. The user: "check CI hourly for me."
2. The model runs `bash`: `tasks add --every 3600 "check CI" --json`.
3. The `bash` tool spawns `tasks` inside the sandbox.
4. `tasks` reads `RHEMA_URL` and `RHEMA_TOKEN` from its environment and does
`POST /v1/tasks` with the JSON body.
5. The daemon's route writes the same `TaskStore` row the native builtin used
to write. The scheduler picks it up exactly as before — it never notices
the row arrived over HTTP.
6. `tasks` prints `{"id":"t-7"}` and exits 0. The model reads stdout and
replies.
```
model turn
| bash: tasks add --every 3600 "check CI"
v
+----------------+ POST /v1/tasks +----------------------+
| tools project | Authorization: agent | claw daemon |
| tasks, notify, | --------------------> | route -> TaskStore |
| watches, ... | <-------------------- | (state lives HERE) |
| (stateless) | {"id":"t-7"} | scheduler fires |
+----------------+ +----------------------+
```
"HTTP client" is the role, not a framework: the client is to the daemon what
`gh` is to GitHub. The state cannot live in the client — it is a different,
short-lived process, possibly inside a sandbox container — so it forwards, and
the independence is precisely that forwarding: no `rhema-claw` import exists
anywhere in the tools project.
## 4. The wire contract
Transport: the daemon's existing axum router (`crates/rhema-claw/src/http.rs`)
— loopback plus bearer today, an env-provisioned base URL when a deployment
puts the sandbox on another host.
Routes that already serve clients as-is: `GET/POST /v1/watches`,
`DELETE /v1/watches/{forge}/{repo}`, `GET/POST/DELETE /v1/calendars`
(removal takes `/v1/calendars/{name}`; the reminders source reads the
calendar table fresh every pass, so a route write is live without a
restart), `GET/POST /v1/accounts`, `DELETE /v1/accounts/{id}`,
`GET /v1/notifications`, `POST /v1/notifications/{id}/ack`,
`GET /v1/phones`.
Watches and calendars are the pattern for every data domain the
daemon reconfigures at runtime: the domain lives in a SQLite table —
not in `claw.yaml` — the routes are the one write door, validation
runs at the door (an invalid watch or calendar is refused loudly
wherever it enters), and the config file carries only what boot
needs. A config still carrying the retired `watches:` or
`calendars:` keys is refused at parse time, not silently ignored.
Routes the extraction adds, because the operation exists today only as an
in-process tool: `POST /v1/notifications` (the push), `GET/POST /v1/tasks`,
`DELETE /v1/tasks/{id}`, `POST /v1/phones/{device}/commands`. Promoting a tool
to a route is not new work twice — the web UI and phone gain the same
operations the model does.
Conventions, fixed once:
- Every client prints JSON: one object per call, one object per line for
lists. `--json` exists as a no-op flag for readability of examples.
- Exit codes: `0` ok, `1` usage (clap), `2` daemon unreachable, `3` denied.
- On failure the last stdout line is a single JSON object
`{"error": "..."}` — the model parses one shape, always.
- Version: every request carries `X-Rhema-Contract: 1`; a daemon speaking a
different contract answers `409` with that same error shape. A stale
installed binary fails loudly on first use, with no discovery round trip.
## 5. The agent credential
Today one `token: Option<String>` guards all of `/v1`, and the model never
holds it — tools run in-process. Bash-accessible clients change who holds a
credential, and the current token is the wrong one to hold:
`POST /v1/consents/{id}` answers a consent, and an agent that can answer
consents can answer its own `ask_secret`.
Two token classes, checked per route in the router:
- the **human token**, unchanged, for the web UI, the phone, and the scripts a
user runs themselves;
- the **agent token** (`agent_token` in the claw config), provisioned into the
agent environment as `RHEMA_URL` + `RHEMA_TOKEN`, allowed on exactly the
data routes the clients speak (§4), denied on consent resolve/deny, session
and message creation, `phones_forget`, and `/v1/ingest`.
Boot refuses to start extracted-tool mode without `agent_token` configured —
the failure belongs at boot, where the operator is looking, not mid-turn,
where the model is. This is the step that turns the README's "the
bearer-gated surface plus the watch list are the trust boundary" from a
sentence into enforced code.
## 6. What stays native
- `bash` — the substrate the whole design stands on.
- `ask_secret` — the consent round-trip waits inside the tool call, woken by
the hub, its answer arriving through routes the agent credential must never
reach (§5). Making it a client would hand the model its own approval path.
- `coding_agent` — spawns a whole coding session, inherits the parent turn's
approval hook, answers with a job id. Orchestration, not data access.
- `zoom` — reads the in-process transcript mirror; no daemon state behind it.
- memory and `attach_file` — native in v1. Memory is the first later-extraction
candidate: its store is already behind a `MemoryStore` contract, so a
`/v1/memory` route family plus a client is a shape, not a research project.
## 7. What moves
| current tool | client | route | wave |
|---|---|---|---|
| `list_watches` / `watch_repo` / `unwatch_repo` | `watches ls/add/rm` | `/v1/watches` (exists) | 1 |
| `notify` | `notify push` | `POST /v1/notifications` (new) | 1 |
| `schedule_task` / `cancel_task` / `list_tasks` | `tasks add/rm/ls` | `/v1/tasks` (new) | 2 |
| `identity_save` / `identity_set` / `identity_list` / `identity_forget` | `identity save/set/ls/forget` | `/v1/accounts` (exists) | 3 |
| `phone` | `phone run` | `POST /v1/phones/{device}/commands` (new) | 3 |
| `bootstrap_save` | — | `PUT /v1/agent` (exists) | later candidate |
Wave 1 is watches plus notify: watches has complete routes, notify has the
smallest state, and between them they exercise the whole path — scoped
credential, `PATH` provisioning, skill discovery, contract versioning —
before anything harder follows it.
## 8. Self-contained tools
The client extraction frees the tools from the daemon's binary. A second
question follows: can a tool exist that was never part of rhema at all —
written by a user, or by the agent itself mid-session, without a fork or a
patch? Yes — and it needs no new API, because the generic API is the surface
this spec already builds on. Three primitives, all HTTP, all daemon-side:
- **`POST /v1/ingest`** — wake the agent with an event. The route takes
`{source, key, payload}`, registers unknown source names lazily on the RSD
dispatcher, and rejects the daemon's reserved source names. A third-party
tool's events therefore get the same guarantees the built-in integrations
get: at most one live handler per resource key, races queued into the live
inbox, crash recovery by lease.
- **`POST /v1/notifications`** (§4) — reach the user's devices.
- **`GET /v1/sessions/{key}/events`** — read back what the agent said.
Plus two non-daemon primitives: **files** (the tool keeps its own state in its
own directory) and **system schedulers** (cron, launchd, schtasks — the tool
installs its own trigger).
### Anatomy
A self-contained tool is four files and no rhema code:
- an executable, dropped in a bin directory the daemon puts on the agent's
`PATH`;
- a skill markdown next to it, installed into the global skills directory;
- its own state directory under the state root (one subdir per tool, owned by
the tool, `0600` for anything credential-shaped);
- optionally one scheduler entry it installed itself.
### The watch table, from outside
Even the case that motivated native integration works through the front door.
A third-party CI watcher: a cron entry runs its poller every five minutes; the
poller calls the forge's API itself, with a token kept in its own state
directory; it triages what is new against its own last-seen file; and for each
new item it does
`POST /v1/ingest {source: "ciwatch", key: "github/acme/widgets#123", payload: {...}}`.
The dispatcher admits the key, the resident gets a turn, and a second event
racing a live handler queues instead of doubling the work. The tool is a
script; nothing in rhema changed.
### The two tiers
- **Tier 1 — self-contained.** Executable + skill + state dir + scheduler.
Writable by anyone, including the agent. No daemon custody of anything.
- **Tier 2 — native extension.** The `ClawExtension` seam stays for what
genuinely needs the daemon: secret custody (rhema-identity's use-never-read
contract — a tier-1 tool cannot receive a secret through the consent
round-trip, whose answers land in the identity store, not in the tool),
tick-rate and webhook latency (cron is minute-grained, has no catch-up, and
the task table's re-arm semantics are the reference for what a daemon-side
timer would have to do), and deep hub integration (auto-notify on non-chat
replies, the phone command loop). The forge and calendar integrations live
here and are not demoted — they are just no longer the only way.
### What this forbids
No plugin SDK, no tool manifest registry, no new IPC protocol. The platform is
HTTP + files + `PATH` — the same surface the model itself uses. The only
daemon additions this spec asks for are the §4 routes and the directory
conventions. A `toolctl` helper in the tools project (`toolctl new`,
`toolctl schedule` wrapping crontab/launchd/schtasks) is convenience, not
contract.
### The agent as tool author
Tier 1 is writable from inside a session: the model writes a script into the
bin dir, a skill into the skills dir, a crontab line — and the resident has
grown itself a capability. That is the codemode endgame, and it costs only the
conventions. One honest line comes with it: such a tool runs with the agent's
privileges and persists past the session through its scheduler entry. The
trust boundary is the shell, exactly as it already is, and `ENVIRONMENT.md`
says what is installed.
## 9. Provisioning and discovery
The daemon installs the clients (a `bin` directory it controls, added to the
agent's `PATH`) and their skills (the global skills directory). Boot-time
`ENVIRONMENT.md` already inventories what is on `PATH`, so a missing binary is
visible before the first model call. A client that cannot reach the daemon
prints which environment variable is missing or wrong — the model reports it
instead of retrying.
## 10. Approvals, replay, crash
A `bash` call that runs three clients is one approval unit and one
commit-before-execute unit — coarser than three native calls, and already true
of any compound shell command. Resident sessions auto-approve the shell
anyway (the daemon says so at startup), so nothing is lost in practice. In
exchange, mutating verbs are upsert-shaped (`add`, `rm`, `save`), so a replay
after a mid-command crash converges instead of duplicating. The manifests'
`replay_safety: safe` moves into the contract: `GET` verbs are safe,
`POST`/`DELETE` are not, and the exit code says which one ran.
## 11. Layout and the dependency arrow
New project — `rhema-tools`:
- `rhema-claw-tools-contract` — route constants, JSON payload types, a mock router,
and the conformance suite. Depends on nothing.
- one crate per domain — the binary and its skills directory.
- one thin shared client crate — base-URL/token env handling, the HTTP calls,
the error printing every binary shares.
Dependency arrows, both enforced in CI: the claw depends on
`rhema-claw-tools-contract` (to run the conformance suite against its real router)
and never on the domain crates; the tools project depends on nothing of
rhema-claw.
`TOOL.yaml` is retired for extracted domains. The manifest existed to make a
Rust builtin model-facing; a clap surface plus a skill markdown is that now.
The old guarantee — every manifest loads against its builtin — becomes two:
every skill's examples parse against the binary (`--help`/dry-run), and every
route the contract names is exercised by the conformance suite.
## 12. Migration
1. The scoped agent credential lands in the claw: token classes, route
middleware, boot check. No model-facing change.
2. The contract crate lands; the claw grows the new routes
(`POST /v1/notifications`, the `/v1/tasks` family) and passes conformance.
3. Wave 1: `watches` and `notify` clients + skills; the agent environment gets
`PATH`, skills, `RHEMA_URL`/`RHEMA_TOKEN`, and the tier-1 state root; the
two domains' manifests and builtins stop rendering and are deleted.
4. Waves 2–3 repeat step 3 per domain: routes if new, client + skill, delete
manifest + builtin + extension line.
5. When the last wave lands, the claw's `SYSTEM.md` tools section lists
`bash`, `zoom`, `ask_secret`, `coding_agent`, memory — plus a two-line
pointer to the installed skills.
## 13. How we know it works
- Conformance: the contract's suite runs against the claw's real router and
against the contract's mock router, with the same results.
- Arrow test: the tools workspace builds with `rhema-claw` absent.
- End to end: a mock-provider turn whose scripted model runs `tasks add`
through `bash`; the daemon's scheduler fires the task; the phone poll sees
the notification; the agent token's `POST /v1/consents/{id}` answers `403`.
- Skill lint: every fenced shell example in every skill parses (usage check /
dry-run), so doc rot fails a test instead of fooling a model.
- Tier-1 end to end: a test drops a two-line shell script and a skill into the
provisioned dirs, runs it, and its `POST /v1/ingest` lands as a turn;
`POST /v1/ingest` under a reserved source name answers `400`.
## 14. Explicitly not decided here
- Binary naming: short domain names (`tasks`) versus a prefix
(`rhema-tasks`). Short names read best in skills; switch if a collision
appears on a real system.
- Whether the project starts as a repo-local directory (the `integrations/`
shape) and extracts to its own repo later, or is born separate.
- Extraction waves for memory, `attach_file`, and `bootstrap_save`.
- Transports beyond bearer-over-HTTP: a unix-socket listener, mTLS for a
remote daemon, a quota on client calls per turn.
- Whether `toolctl` (scaffolder + scheduler wrapper) ships in v1 or stays
documentation.
- A daemon-side timer service (`POST /v1/timers`) for cronless hosts — the
task table's fire-guards are the reference semantics. Not v1.
- Whether tier-1 tools ever get a consent-shaped way to receive secrets. V1
answer: no — users place credentials in the tool's state dir themselves.
## 15. Decisions
- Model-facing data tools become bash skills + thin executables; the schema
list leaves `SYSTEM.md`.
- Wire contract, not crate dependency; the arrows claw → contract ← tools are
enforced.
- The scoped agent credential precedes every client; consents, sessions, and
ingest are unreachable by it.
- Native keeps: `bash`, `ask_secret`, `coding_agent`, `zoom`, memory,
`attach_file` (v1).
- Waves: watches + notify, then tasks, then identity + phone.
- Self-contained tools are files + system schedulers + the three HTTP
primitives; no plugin SDK, no manifest registry, no new IPC.
- Two tiers: tier 1 writable by anyone, including the agent mid-session;
tier 2 (`ClawExtension`) keeps secret custody, tick/webhook latency, and
hub depth.
---
## Status
Wave 1 is built: `tools/contract` (allowlist, header, conformance
suite), `tools/notify` (the first client tool), the claw's contract
enforcement (the scoped agent token, the allowlist middleware, the
push and schedule routes, the JSON error shape everywhere), and the
provisioning seam (`agent_token` + `tools_bin` → the daemon's tool
environment → `ShellTools::with_env` → the coding agent's commands).
The conformance suite runs against the daemon's real router in
`crates/rhema-claw/tests/http.rs`; `tools/notify/tests` drives the
`notify` binary against a mock. Waves 2–4 (skills mounts, packaging,
more tools) are still future work.
+19 -9
View File
@@ -90,12 +90,21 @@ Two consequences worth knowing before changing this code:
## What the transcript does with the stream
- **Replies, asks and files only.** The stream carries tool calls and
the model's thinking trace; this surface drops both and renders the
reply. A consent card and an attachment card still appear inline,
because the reader has to answer or open them. The mirror still
folds those other events; only the render ignores them.
- **Long pastes travel as chips.** A paste over three lines (the TUI's
`PASTE_INLINE_LINES`) never lands in the composer; it stages as a
droppable chip (`▣1 42L`) and embeds into the sent text as
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s
`paste::embed` keeps — so the transcript renders each embed back as
a chip in place of the payload. An unpaired mark is literal text.
droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
the plain draft — the claw composes the record (the payload in
place, the span note beside it) — so no mark ever crosses the wire.
The `user_message` echo names each chip as the byte span it stands
for (the session record's own shape, `paste::PasteSpan`), and the
transcript renders from that. Rows recorded before spans rode the
stream carry the legacy mark form in the text instead; the render
still scans for those, and an unpaired mark stays literal.
- **The agent can ask.** A `consent_request` event renders as an
inline card: kind `secret` gets a password input plus submit, kind
`phone` gets Approve/Deny, and both carry a deny link
@@ -175,10 +184,10 @@ app/
raw HTML escaped, styles in main.css .md)
ClawBanner.vue the one error/notice banner surface
ChatPanel.vue transcript: sent lines (paste chips),
streamed turns as bash shell lines and
glyph rows, consent + attachment
cards; the growing composer; agent
replies render through AppMarkdown
streamed turns as reply text plus
consent + attachment cards; the growing
composer; agent replies render through
AppMarkdown
SessionsSidebar.vue conversable dispatch keys (phone status
keys hidden), interactive first; the
+ form creates a session
@@ -193,7 +202,8 @@ app/
composables/
useClaw.ts the typed API client + fetch-based SSE
useTranscript.ts folds TurnEvents into renderable turn
blocks; owns the paste-embed text form
blocks; owns the paste span record (and
the legacy mark form old rows carry)
server/
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
```
+59 -8
View File
@@ -17,9 +17,11 @@ import type {
NewAccount,
ProviderCredentials,
ProvidersState,
SandboxSelection,
SandboxState,
StreamStatus,
} from '~/composables/useClaw'
import { useTranscript } from '~/composables/useTranscript'
import { composeChips, useTranscript } from '~/composables/useTranscript'
import type { StagedImage } from '~/composables/useTranscript'
const TOKEN_STORE_KEY = 'claw.token'
@@ -58,7 +60,13 @@ const SETTINGS_SECTIONS: { label: string; entries: { id: string; label: string }
],
},
{ label: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] },
{ label: 'System', entries: [{ id: 'about', label: 'About' }] },
{
label: 'System',
entries: [
{ id: 'sandbox', label: 'Sandbox' },
{ id: 'about', label: 'About' },
],
},
]
function parseHash(): Route {
@@ -265,6 +273,8 @@ const mutatingIdentity = ref(false)
const accounts = ref<ClawAccount[] | null>(null)
const accountsLoading = ref(false)
const mutatingAccounts = ref(false)
const sandboxState = ref<SandboxState | null>(null)
const savingSandbox = ref(false)
const streamStatus = ref<StreamStatus>('connecting')
const busy = ref(false)
const authRequired = ref(false)
@@ -499,21 +509,54 @@ async function removeProvider(id: string): Promise<void> {
}
}
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews; the stream's
// user_message echo carries the stored ids and dedupes against it.
async function refreshSandbox(): Promise<void> {
try {
sandboxState.value = await claw.sandbox()
apiError.value = null
} catch (err) {
noteApiError(err)
}
}
async function saveSandbox(choice: SandboxSelection): Promise<void> {
savingSandbox.value = true
try {
sandboxState.value = await claw.setSandbox(choice)
pushNotice(
choice.kind === 'http'
? 'sandbox: remote host'
: choice.kind === 'ssh'
? 'sandbox: ssh host'
: 'sandbox: this machine',
)
apiError.value = null
} catch (err) {
noteApiError(err)
} finally {
savingSandbox.value = false
}
}
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews and the composed
// chip record — the same plain text and spans the fold records on
// the other side — so the stream's user_message echo, which
// carries the stored ids beside that record, dedupes against it.
const composed = composeChips(message.text, message.pastes)
const rowId = transcript.addSent(
message.text,
composed.text,
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
composed.pastes,
)
busy.value = true
try {
// Fire-and-forget by design: the claw answers 202 and the reply
// arrives on the event stream. The body carries the images only
// when there are some.
// arrives on the event stream. The chips and the images ride the
// body only when there are some.
await claw.sendMessage(
activeKey.value,
message.text,
message.pastes,
message.images.map(({ media_type, data }) => ({ media_type, data })),
)
apiError.value = null
@@ -581,6 +624,7 @@ function saveToken(): void {
void refreshSessions()
void refreshIdentity()
void refreshAccounts()
void refreshSandbox()
}
// --- the one live subscription ---------------------------------------
@@ -657,6 +701,7 @@ onMounted(() => {
void refreshIdentity()
void refreshProviders()
void refreshAccounts()
void refreshSandbox()
void refreshSessions()
healthTimer = setInterval(checkHealth, 30000)
sessionsTimer = setInterval(() => void refreshSessions(), 20000)
@@ -789,6 +834,12 @@ onUnmounted(() => {
@add="addProvider"
@remove="removeProvider"
/>
<SettingsSandboxPage
v-show="route.section === 'sandbox'"
:state="sandboxState"
:saving="savingSandbox"
@save="saveSandbox"
/>
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
</template>
</main>
+74 -19
View File
@@ -10,12 +10,14 @@
import {
PASTE_INLINE_LINES,
chipLabel,
embedPastes,
byteToIndex,
chipLinesLabel,
lineCount,
normalizePaste,
pasteParts,
} from '~/composables/useTranscript'
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
import type { PasteSpan } from '~/composables/useClaw'
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
const props = defineProps<{
@@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
* the staged images, previews included for the optimistic row. */
interface SendPayload {
text: string
/** The chip payloads, in staging order — the wire carries them
* beside the plain draft; the fold composes the record. */
pastes: string[]
images: StagedImage[]
}
@@ -136,20 +141,12 @@ watch(
},
)
// Thinking grows inside the trailing entry without changing the
// entries length, so its total length joins the watch to keep the
// stream pinned at the bottom.
function liveThinkingLength(): number {
return (
props.live?.entries.reduce(
(count, entry) => (entry.kind === 'thinking' ? count + entry.text.length : count),
0,
) ?? 0
)
}
// A consent or attachment card opening inside the trailing turn
// changes the rendered height, so the reply length and the entries
// length both join the watch that keeps the stream pinned at the
// bottom.
watch(
() => [props.items.length, props.live?.reply.length, liveThinkingLength(), props.live?.entries.length],
() => [props.items.length, props.live?.reply.length, props.live?.entries.length],
async () => {
if (!pinned.value) return
await nextTick()
@@ -165,7 +162,7 @@ function submit(): void {
// answers 202 at once) — a running turn never blocks the composer,
// because a send into one steers it.
if (!text || !props.canSend || props.busy) return
emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value })
emit('send', { text, pastes: pastes.value, images: stagedImages.value })
stageGeneration++
draft.value = ''
pastes.value = []
@@ -367,8 +364,12 @@ function storedImageName(image: SentImage): string {
type MessageSegment = PastePart | { kind: 'chip'; label: string }
/** The message's render pieces: literal text and resolved chips, the
* chips' one-based ids counted across the message. */
function messageSegments(text: string): MessageSegment[] {
* chips' one-based ids counted across the message. The chips come
* from the row's span record — the plain text sliced at the spans'
* byte boundaries — and a row from before spans rode the wire
* carries none; that one still scans the mark form in its text. */
function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] {
if (pastes.length === 0) {
const segments: MessageSegment[] = []
let chip = 0
for (const part of pasteParts(text)) {
@@ -379,6 +380,21 @@ function messageSegments(text: string): MessageSegment[] {
}
}
return segments
}
const indexOf = byteToIndex(text)
const segments: MessageSegment[] = []
let chip = 0
let cut = 0
for (const span of [...pastes].sort((a, b) => a.start - b.start)) {
const start = indexOf(span.start)
const end = indexOf(span.end)
if (start === -1 || end === -1 || start < cut || end < start) continue
if (start > cut) segments.push({ kind: 'text', text: text.slice(cut, start) })
segments.push({ kind: 'chip', label: chipLinesLabel(span.lines, chip++) })
cut = end
}
if (cut < text.length) segments.push({ kind: 'text', text: text.slice(cut) })
return segments
}
const displayName = computed(() => props.activeKey.replace(/^interactive:/, ''))
@@ -453,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
</button>
</div>
<div class="reply plain">
<template v-for="(segment, index) in messageSegments(item.text)" :key="index">
<template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
<template v-else>{{ segment.text }}</template>
</template>
@@ -498,12 +514,15 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="who">{{ agentName }}</div>
<TurnEntries
:entries="live.entries"
:open-thinking="true"
@consent-answer="(id, answer) => emit('consentAnswer', id, answer)"
@consent-deny="(id) => emit('consentDeny', id)"
@download-attachment="(id, name) => emit('downloadAttachment', id, name)"
/>
<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>
@@ -740,6 +759,42 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
color: var(--accent-text);
}
/* 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 {
+64 -3
View File
@@ -7,6 +7,10 @@
// 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.
import { SESSION_NAME_PATTERN, isResidentKey } from '~/composables/useClaw'
import type { ClawSession } from '~/composables/useClaw'
@@ -28,6 +32,10 @@ const emit = defineEmits<{
interface Group {
label: string
rows: { key: string; name: string; session: ClawSession }[]
/** How many rows hold a lease; the others' header shows the count. */
working: number
/** Whether the rows fold away until the toggle says otherwise. */
collapsible: boolean
}
const groups = computed<Group[]>(() => {
@@ -52,13 +60,29 @@ const groups = computed<Group[]>(() => {
name: session.key.replace(/^interactive:/, ''),
session,
})
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) })
if (others.length > 0) groups.push({ label: 'other keys', rows: others.map(row) })
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,
})
return groups
})
/** Whether the others group is folded out; it starts folded. */
const othersOpen = ref(false)
const shownCount = computed(() =>
groups.value.reduce((total, group) => total + group.rows.length, 0),
)
@@ -159,7 +183,21 @@ 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>
<button
v-if="group.collapsible"
class="ghost toggle"
:title="othersOpen ? 'fold the other keys away' : 'show every other key'"
@click="othersOpen = !othersOpen"
>
{{ othersOpen ? 'less' : 'more' }}
</button>
</div>
<template v-if="!group.collapsible || othersOpen">
<div
v-for="row in group.rows"
:key="row.key"
@@ -183,6 +221,7 @@ watch(
×
</button>
</div>
</template>
</div>
</aside>
</template>
@@ -287,10 +326,32 @@ watch(
margin-bottom: 14px;
}
.group .label {
.group-head {
display: flex;
align-items: center;
gap: 8px;
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. */
+16 -39
View File
@@ -1,17 +1,22 @@
<script setup lang="ts">
// A turn's stream-ordered middle: tool rows, pieces of the thinking
// trace, the agent's asks, its handovers — each at the position the
// stream delivered it, so an ask sits at the tool call that raised it
// and thinking sits between the calls it precedes.
// The turn's middle, as the web surface shows it: the agent's asks
// (consent cards) and its handovers (attachment cards), each at the
// position the stream delivered it. Tool calls and the thinking trace
// stay off this surface; the reply is what it shows, and these two
// cards are the only things the reader must act on or can open.
import { computed } from 'vue'
import type { TurnEntry } from '~/composables/useTranscript'
import type { ConsentAnswer } from '~/composables/useClaw'
defineProps<{
const props = defineProps<{
entries: TurnEntry[]
/** A live turn's thinking blocks start expanded; finished ones collapse. */
openThinking?: boolean
}>()
/** Cards only: a turn's tool rows and thinking blocks never render. */
const cards = computed(() =>
props.entries.filter((entry) => entry.kind === 'consent' || entry.kind === 'attachment'),
)
const emit = defineEmits<{
consentAnswer: [id: string, answer: ConsentAnswer]
consentDeny: [id: string]
@@ -20,21 +25,16 @@ const emit = defineEmits<{
</script>
<template>
<div v-if="entries.length > 0" class="entries">
<template v-for="(entry, index) in entries" :key="index">
<TurnToolRow v-if="entry.kind === 'tool'" :row="entry.row" />
<details v-else-if="entry.kind === 'thinking'" class="thinking" :open="openThinking">
<summary>thinking</summary>
<pre>{{ entry.text }}</pre>
</details>
<div v-if="cards.length > 0" class="entries">
<template v-for="(entry, index) in cards" :key="index">
<TurnConsentCard
v-else-if="entry.kind === 'consent'"
v-if="entry.kind === 'consent'"
:consent="entry.consent"
@answer="(id, answer) => emit('consentAnswer', id, answer)"
@deny="(id) => emit('consentDeny', id)"
/>
<TurnAttachmentCard
v-else
v-else-if="entry.kind === 'attachment'"
:attachment="entry.attachment"
@download="(id, name) => emit('downloadAttachment', id, name)"
/>
@@ -49,27 +49,4 @@ const emit = defineEmits<{
gap: 4px;
margin-bottom: 10px;
}
.thinking {
color: var(--text3);
}
.thinking summary {
cursor: pointer;
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.thinking pre {
margin: 6px 0 0;
padding: 8px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text3);
font-style: italic;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
-102
View File
@@ -1,102 +0,0 @@
<script setup lang="ts">
// One tool call in a turn: running, completed, or failed — shell lines
// for bash (the TUI's tool_row), glyph rows for everything else.
import type { ToolRow } from '~/composables/useTranscript'
defineProps<{ row: ToolRow }>()
/** Command rows render as shell lines, not glyph rows; run_command is
* the bash tool's other name. */
function isShellTool(name: string): boolean {
return name === 'bash' || name === 'run_command'
}
</script>
<template>
<div class="tool-row" :class="{ error: row.isError === true }">
<template v-if="isShellTool(row.name)">
<span class="shell-mark" aria-hidden="true">$ </span>
<span class="shell-command mono">{{ row.command ?? '…' }}</span>
<span
v-if="typeof row.code === 'number'"
class="shell-code mono"
:class="row.code === 0 ? 'ok' : 'failed'"
>[{{ row.code }}]</span>
<span v-else-if="row.isError === true" class="shell-code failed">✗</span>
</template>
<template v-else>
<span class="glyph" aria-hidden="true">{{
row.isError === null ? '…' : row.isError ? '✗' : '✓'
}}</span>
<span class="name mono">{{ row.name }}</span>
<span v-if="row.summary" class="summary mono">{{ row.summary }}</span>
</template>
</div>
</template>
<style scoped>
.tool-row {
display: flex;
gap: 8px;
align-items: baseline;
padding: 5px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-left: 3px solid var(--ok);
border-radius: 6px;
}
.tool-row.error {
border-left-color: var(--error);
}
.glyph {
flex: none;
color: var(--ok);
}
.tool-row.error .glyph {
color: var(--error);
}
.name {
color: var(--text);
}
.summary {
color: var(--text3);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A bash row reads as the shell line it ran: dim $ prefix, the
command, and the exit code pushed to the row's right end. */
.shell-mark {
flex: none;
color: var(--text3);
white-space: pre;
}
.shell-command {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text);
}
.shell-code {
flex: none;
font-size: 11px;
}
.shell-code.ok {
color: var(--ok);
}
.shell-code.failed {
color: var(--error);
}
</style>
@@ -0,0 +1,330 @@
<script setup lang="ts">
// The Sandbox page: where the agent's `bash` runs. The choice saves as
// a whole; the token is write-only, so an empty field keeps whatever
// the claw already stored. Presentational: data flows in as props,
// intent flows up as events.
import type { SandboxKind, SandboxSelection, SandboxState } from '~/composables/useClaw'
const props = defineProps<{
state: SandboxState | null
saving: boolean
}>()
const emit = defineEmits<{
save: [choice: SandboxSelection]
}>()
const kind = ref<SandboxKind>('local')
const url = ref('')
const token = ref('')
const clearToken = ref(false)
const host = ref('')
const workspace = ref('')
const 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 false
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const hostValid = computed(
() => host.value.trim() !== '' && !host.value.trim().includes(' '),
)
const ready = computed(() => {
if (kind.value === 'http') return urlValid.value
if (kind.value === 'ssh') return hostValid.value
return true
})
const urlHint = computed(() =>
url.value.trim() && !urlValid.value
? 'The URL must start with http:// or https://.'
: 'The sandboxd base URL, for example https://box.example:7600.',
)
const hostHint = computed(() =>
host.value.trim() && !hostValid.value
? 'One destination, no spaces: an alias or user@host your ssh config resolves.'
: 'An alias or user@host your ssh config resolves.',
)
function sync(): void {
const state = props.state
if (!state) return
kind.value = state.kind
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? ''
}
watch(
() => props.state,
(state) => {
if (state) sync()
},
{ immediate: true },
)
function discard(): void {
sync()
}
function save(): void {
if (!dirty.value || props.saving || !ready.value) return
const choice: SandboxSelection = { kind: kind.value }
if (kind.value === 'http') {
choice.url = url.value.trim()
if (token.value.trim() !== '') {
choice.token = token.value.trim()
} else if (clearToken.value) {
choice.clear_token = true
}
}
if (kind.value === 'ssh') {
choice.host = host.value.trim()
choice.workspace = workspace.value.trim()
}
emit('save', choice)
}
// The path the staged choice would use, not the saved one.
const workspacePath = computed(() => {
const state = props.state
if (!state) return ''
if (kind.value === 'local') return state.local_workspace
if (kind.value === 'http') return state.remote_workspace
return state.workspace
})
</script>
<template>
<div class="page">
<PageHeader title="Sandbox" subtitle="Where the agent's bash runs.">
<template #actions>
<button :disabled="!dirty || saving" @click="discard">Discard</button>
<button class="primary" :disabled="!dirty || saving || !ready" @click="save">
{{ saving ? 'Saving…' : 'Save' }}
</button>
</template>
</PageHeader>
<div class="scroll">
<p v-if="!state" class="muted">loading sandbox…</p>
<template v-else>
<SettingCard title="Execution" meta="applies on the next turn">
<label class="option" :class="{ selected: kind === 'local' }">
<input v-model="kind" type="radio" value="local" :disabled="saving" />
<span class="option-text">
<span class="option-title">
This machine
<span v-if="state.kind === 'local'" class="current">current</span>
</span>
<span class="option-detail">
Commands run as processes on the daemon's host.
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'http' }">
<input v-model="kind" type="radio" value="http" :disabled="saving" />
<span class="option-text">
<span class="option-title">
Remote sandbox
<span v-if="state.kind === 'http'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a host that speaks the sandbox protocol over HTTP.
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'ssh' }">
<input v-model="kind" type="radio" value="ssh" :disabled="saving" />
<span class="option-text">
<span class="option-title">
SSH host
<span v-if="state.kind === 'ssh'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a box the claw reaches with ssh, nothing installed on the far end.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'ssh'" title="SSH host">
<SettingRow title="Destination" :description="hostHint">
<input
v-model="host"
type="text"
class="mono"
placeholder="me@box.example"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Workspace base"
description="The remote directory the claw's workspaces live under. Defaults to /root."
>
<input
v-model="workspace"
type="text"
class="mono"
placeholder="/root"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
</SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
<SettingRow
title="URL"
:description="urlHint"
>
<input
v-model="url"
type="text"
class="mono"
placeholder="https://box.example:7600"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Token"
:description="state.token_set
? 'A token is stored. Leave this blank to keep it.'
: 'The shared secret the daemon checks. Leave it blank when the daemon has none.'"
>
<input
v-model="token"
type="password"
:placeholder="state.token_set ? 'stored' : 'optional'"
autocomplete="off"
:disabled="saving || clearToken"
/>
</SettingRow>
<SettingRow
v-if="state.token_set"
title="Stored token"
:description="clearToken
? 'The stored token is removed when you save.'
: 'The token stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearToken = !clearToken">
{{ clearToken ? 'Keep token' : 'Forget token' }}
</button>
</SettingRow>
</SettingCard>
<AppCallout v-if="kind !== 'local'" variant="info" title="Remote commands start from a copy">
On first use the claw sends the local workspace to the sandbox as a tarball.
Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout>
<SettingCard title="Workspace">
<SettingRow
title="Path"
description="Where the agent's bash starts under this choice."
>
<code>{{ workspacePath }}</code>
</SettingRow>
</SettingCard>
</template>
</div>
</div>
</template>
<style scoped>
.page {
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
flex: 1;
}
.scroll {
flex: 1;
overflow-y: auto;
padding: 0 24px 24px;
display: flex;
flex-direction: column;
gap: 16px;
max-width: 860px;
}
.muted {
color: var(--text3);
padding: 8px 2px;
}
.option {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 13px 16px;
cursor: pointer;
}
.option:hover {
background: var(--elevated);
}
.option.selected {
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
}
.option input[type='radio'] {
flex: none;
margin: 3px 0 0;
accent-color: var(--accent);
}
.option-text {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
.option-title {
display: flex;
align-items: baseline;
gap: 8px;
color: var(--text);
font-weight: 600;
}
.option-detail {
color: var(--text3);
font-size: 12.5px;
}
.current {
color: var(--accent-text);
font-size: 12px;
font-weight: 500;
}
</style>
+140 -9
View File
@@ -56,9 +56,20 @@ export interface UserImage {
media_type: string
}
/** One paste chip a `user_message` carries: the record the session's
* `rhema-code` annotation holds — the byte range in the plain text the
* chip stands for (UTF-8 offsets; see useTranscript's
* `byteToIndex`), plus the payload's line count for the chip's label
* (rhema-core `PasteSpan`). */
export interface PasteSpan {
start: number
end: number
lines: number
}
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
export type TurnEvent =
| { type: 'user_message'; text: string; images: UserImage[] }
| { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
| { type: 'thinking_delta'; text: string }
| { type: 'text_delta'; text: string }
| { type: 'tool_start'; name: string }
@@ -220,6 +231,44 @@ 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'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */
export interface SandboxState {
kind: SandboxKind
url: string | null
token_set: boolean
/** The ssh destination, an alias or `user@host` the local ssh
* config resolves. */
host: string | null
/** The ssh workspace base the workspaces sit under, `null` for the
* default. */
ssh_workspace: string | null
/** Where `bash` starts under the current choice. */
workspace: string
/** The daemon's chat workspace, whatever the choice. */
local_workspace: string
/** The path a remote sandbox exposes. */
remote_workspace: string
}
/** The body `PUT /v1/sandbox` takes. `token` is write-only, and
* `clear_token` drops the stored one. An omitted `url` keeps the
* current one. */
export interface SandboxSelection {
kind: SandboxKind
url?: string
token?: string
clear_token?: boolean
host?: string
/** The ssh 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. */
export class ClawError extends Error {
/** HTTP status; 0 when the claw was unreachable at all. */
@@ -240,7 +289,9 @@ const INTERACTIVE_PREFIX = 'interactive:'
* connection and reconnects: the claw sends a keep-alive comment every
* fifteen seconds (hub.rs), so three missed ones means the path is
* black-holed — a half-open TCP after a laptop sleep shows the same
* 'live' badge a healthy stream does without this check. */
* 'live' badge a healthy stream does without this check. The watchdog
* is paused while the tab is hidden: browsers throttle timers and can
* stall the reader there, and a tab switch is not a dead stream. */
const STREAM_SILENCE_TIMEOUT_MS = 45000
/** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */
@@ -368,8 +419,8 @@ export interface ClawApi {
* a plain src will not do). Cached per id: attachments are immutable,
* so a replayed event never refetches. */
attachmentUrl(id: string): Promise<string>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
/** `GET /v1/providers` — the constructible backends and the active pair. */
providers(): Promise<ProvidersState>
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
@@ -383,6 +434,11 @@ export interface ClawApi {
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers
* the new providers state. The last backend is refused claw-side. */
removeProvider(id: string): Promise<ProvidersState>
/** `GET /v1/sandbox`: where the agent's `bash` runs. */
sandbox(): Promise<SandboxState>
/** `PUT /v1/sandbox`: switch the sandbox, persisted claw-side. The
* choice applies on the next turn. */
setSandbox(choice: SandboxSelection): Promise<SandboxState>
/** `GET /v1/accounts` — the stored accounts, redacted. */
accounts(): Promise<ClawAccount[]>
/** `POST /v1/accounts` — store an account (the secret is write-only),
@@ -498,11 +554,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})
}
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> {
async function sendMessage(
key: string,
text: string,
pastes?: string[],
images?: OutboundImage[],
): Promise<void> {
const body: { text: string; pastes?: string[]; images?: OutboundImage[] } = { text }
if (pastes?.length) body.pastes = pastes
if (images?.length) body.images = images
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(images?.length ? { text, images } : { text }),
body: JSON.stringify(body),
})
}
@@ -563,6 +627,18 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})) as ProvidersState
}
async function sandbox(): Promise<SandboxState> {
return (await get('/v1/sandbox', token.value)) as SandboxState
}
async function setSandbox(choice: SandboxSelection): Promise<SandboxState> {
return (await send('/v1/sandbox', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(choice),
})) as SandboxState
}
async function accounts(): Promise<ClawAccount[]> {
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
return body.accounts
@@ -639,11 +715,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
* notice says so instead of naming an opaque abort error. */
let timedOut = false
let silence: ReturnType<typeof setTimeout> | null = null
const isHidden = (): boolean =>
typeof document !== 'undefined' && document.hidden
/** Whether the attempt in flight crossed a hidden tab: a drop there
* is a backgrounded connection, not a stream the user needs a notice
* about. */
let hiddenDuringAttempt = isHidden()
const rearmSilence = (): void => {
if (silence !== null) clearTimeout(silence)
silence = null
if (closed || isHidden()) return
silence = setTimeout(() => {
if (closed) return
if (closed || isHidden()) return
timedOut = true
current?.abort()
}, STREAM_SILENCE_TIMEOUT_MS)
@@ -652,6 +736,23 @@ export function useClaw(token: Ref<string | null>): ClawApi {
if (silence !== null) clearTimeout(silence)
silence = null
}
/** A frame or keep-alive proved this attempt alive: from here on a
* drop is real, even if the tab was hidden earlier. */
const noteActivity = (): void => {
hiddenDuringAttempt = false
rearmSilence()
}
const visibility = (): void => {
if (isHidden()) {
hiddenDuringAttempt = true
stopSilence()
return
}
if (current !== null && !current.signal.aborted) rearmSilence()
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', visibility)
}
const status = (next: StreamStatus) => {
if (!closed) handlers.onStatus?.(next)
@@ -663,6 +764,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const controller = new AbortController()
current = controller
timedOut = false
hiddenDuringAttempt = isHidden()
rearmSilence()
try {
const resume = cursor === null ? '' : `?since=${cursor}`
@@ -684,7 +786,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
await readFrames(
response.body,
(data, id) => {
rearmSilence()
noteActivity()
const event = parseTurnEvent(data)
if (!event) return
const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null
@@ -694,7 +796,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
(comment) => {
// Keep-alives come through here too; each one proves the
// path alive.
rearmSilence()
noteActivity()
// The record lost what this mirror holds: drop the cursor
// so the next open asks for the tail, and let the consumer
// drop its items before the tail that already followed
@@ -720,11 +822,16 @@ export function useClaw(token: Ref<string | null>): ClawApi {
// Backoff caps at 15s: a live stream of a running turn is the
// UI's whole job, so retries stay eager but not tight-looped.
const backoff = Math.min(15000, 1000 * 2 ** attempt++)
// A connection that crossed a hidden tab reconnects quietly:
// the browser held it while the page was in the background,
// and the operator did not just lose a live stream.
if (!isHidden() && !hiddenDuringAttempt) {
handlers.onNotice?.(
timedOut
? `the event stream went quiet (no keep-alive for ${STREAM_SILENCE_TIMEOUT_MS / 1000}s); reconnecting in ${backoff / 1000}s`
: `event stream dropped (${cause instanceof Error ? cause.message : String(cause)}); retrying in ${backoff / 1000}s`,
)
}
status('reconnecting')
await new Promise((resolve) => setTimeout(resolve, backoff))
} finally {
@@ -738,6 +845,9 @@ export function useClaw(token: Ref<string | null>): ClawApi {
close() {
closed = true
stopSilence()
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', visibility)
}
current?.abort()
},
}
@@ -757,6 +867,8 @@ export function useClaw(token: Ref<string | null>): ClawApi {
models,
setCredentials,
removeProvider,
sandbox,
setSandbox,
accounts,
addAccount,
removeAccount,
@@ -836,6 +948,24 @@ function parseUserImages(raw: unknown): UserImage[] {
return images
}
/** The paste chips a `user_message` carries: rows recorded before
* chips rode as spans carry the mark form in the text instead and no
* field at all — empty, the render falls back to scanning — and a
* span without whole-number bounds or a line count is not one. */
function parseUserPastes(raw: unknown): PasteSpan[] {
if (!Array.isArray(raw)) return []
const pastes: PasteSpan[] = []
for (const entry of raw) {
const span = entry as Record<string, unknown>
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
if (typeof span.lines !== 'number') continue
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
pastes.push({ start: span.start, end: span.end, lines: span.lines })
}
return pastes
}
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
function parseTurnEvent(data: string): TurnEvent | null {
try {
@@ -846,6 +976,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'user_message',
text: String(raw.text ?? ''),
images: parseUserImages(raw.images),
pastes: parseUserPastes(raw.pastes),
}
case 'thinking_delta':
case 'text_delta':
+50 -16
View File
@@ -6,7 +6,7 @@
// mirror when the stream reopens and folds what arrives, never the other
// way around.
import { ref } from 'vue'
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw'
import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
/** One tool call inside a turn: started, then completed by its result. */
export interface ToolRow {
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
/** A transcript line: a message the local user sent, or one streamed turn. */
export type TranscriptItem =
| { kind: 'sent'; id: number; text: string; images: SentImage[] }
| { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
| { kind: 'turn'; id: number; turn: TurnBlock }
| { kind: 'consent'; id: number; consent: ConsentCard }
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
return lines.length
}
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
* payload's line count (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return `▣${index + 1} ${lineCount(paste)}L`
/** A chip's label from its line count: `▣1 5L` — the chip's
* one-based id and the payload's line count (the TUI's chip_label). */
export function chipLinesLabel(lines: number, index: number): string {
return `▣${index + 1} ${lines}L`
}
/** Appends each paste as one MARK-payload-MARK embed, in order — the
* session's record of the prompt (paste::embed; a web draft holds no
* anchors, so every payload lands at the end). */
export function embedPastes(draft: string, pastes: string[]): string {
return (
draft +
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
)
/** A chip's label from its payload (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return chipLinesLabel(lineCount(paste), index)
}
/** The modern record the wire carries: each paste a byte span in the
* plain text (the `rhema-code` annotation's own shape), one walk over
* the composed text mapping every code-point boundary — a span that
* splits a code point maps to none, the render skips it. */
export function byteToIndex(text: string): (byte: number) => number {
const at = new Map<number, number>([[0, 0]])
const bytesOf = new TextEncoder()
let bytes = 0
let units = 0
for (const cp of text) {
bytes += bytesOf.encode(cp).length
units += cp.length
at.set(bytes, units)
}
return (byte) => at.get(byte) ?? -1
}
/** Composes a send the way the fold composes its record: each paste's
* normalized payload appends to the draft, its chip's span measured
* over the composed plain text. The same form the `user_message`
* echo carries, so the optimistic row and the replay render rows of
* one shape and the echo dedupes against what this surface sent. */
export function composeChips(
draft: string,
pastes: string[],
): { text: string; pastes: PasteSpan[] } {
const bytesOf = new TextEncoder()
let text = draft
const spans: PasteSpan[] = []
for (const paste of pastes) {
const payload = normalizePaste(paste)
const start = bytesOf.encode(text).length
text += payload
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
}
return { text, pastes: spans }
}
/** One scanned piece of embedded-form text. */
@@ -244,6 +277,7 @@ export function useTranscript() {
id: nextId++,
text: event.text,
images: event.images.map((image) => ({ ...image, url: null, name: null })),
pastes: event.pastes,
})
break
}
@@ -356,10 +390,10 @@ export function useTranscript() {
* Its images render from the staged previews — the claw stores them
* and the stream's echo dedupes against this row. Returns the row's
* id, so a failed POST can retract it. */
function addSent(text: string, images: SentImage[] = []): number {
function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
const id = nextId++
pendingSent.push({ text, images: images.length, itemId: id })
items.value.push({ kind: 'sent', id, text, images })
items.value.push({ kind: 'sent', id, text, images, pastes })
return id
}