Author SHA1 Message Date
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
45 changed files with 3064 additions and 471 deletions

No files matched your search

Generated
+341 -85
View File
@@ -411,6 +411,23 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" 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]] [[package]]
name = "cipher" name = "cipher"
version = "0.5.2" version = "0.5.2"
@@ -893,8 +910,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"wasi", "wasi",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -904,8 +923,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"r-efi", "r-efi",
"rand_core 0.10.1",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1079,6 +1101,7 @@ dependencies = [
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
"tower-service", "tower-service",
"webpki-roots",
] ]
[[package]] [[package]]
@@ -1338,6 +1361,12 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "lru-slab"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]] [[package]]
name = "matchit" name = "matchit"
version = "0.8.4" version = "0.8.4"
@@ -1672,6 +1701,62 @@ dependencies = [
"memchr", "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]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@@ -1695,7 +1780,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [ dependencies = [
"libc", "libc",
"rand_chacha", "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]] [[package]]
@@ -1705,7 +1801,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [ dependencies = [
"ppv-lite86", "ppv-lite86",
"rand_core", "rand_core 0.6.4",
] ]
[[package]] [[package]]
@@ -1717,6 +1813,21 @@ dependencies = [
"getrandom 0.2.17", "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]] [[package]]
name = "regex" name = "regex"
version = "1.13.1" version = "1.13.1"
@@ -1771,6 +1882,8 @@ dependencies = [
"native-tls", "native-tls",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types", "rustls-pki-types",
"serde", "serde",
"serde_json", "serde_json",
@@ -1778,6 +1891,7 @@ dependencies = [
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tokio-native-tls", "tokio-native-tls",
"tokio-rustls",
"tokio-util", "tokio-util",
"tower", "tower",
"tower-http", "tower-http",
@@ -1787,30 +1901,14 @@ dependencies = [
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasm-streams", "wasm-streams",
"web-sys", "web-sys",
] "webpki-roots",
[[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",
] ]
[[package]] [[package]]
name = "rhema-autonomous-agent" name = "rhema-autonomous-agent"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e3ee50c812fa93f31be669557cb642ed8d03154613234b2090fa9567374516e" checksum = "08fd6d5fe5f9551226d322491d03b14d5e42ac2ff73544c15a555fb97a04bbfd"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"rhema-core", "rhema-core",
@@ -1822,9 +1920,25 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "rhema-bash"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf9ae34e5c556e0abdf279dd7d0aa08632bdcd68cff965bce2b81c226ada8f1e"
dependencies = [
"async-trait",
"base64 0.22.1",
"rhema-core",
"rhema-submissions",
"serde",
"serde_json",
"thiserror",
"tokio",
]
[[package]] [[package]]
name = "rhema-calendar-integration" name = "rhema-calendar-integration"
version = "0.2.3" version = "0.4.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"quick-xml", "quick-xml",
@@ -1843,27 +1957,31 @@ dependencies = [
[[package]] [[package]]
name = "rhema-claw" name = "rhema-claw"
version = "0.2.3" version = "0.4.0"
dependencies = [ dependencies = [
"async-trait",
"axum", "axum",
"base64 0.22.1", "base64 0.22.1",
"bytes", "bytes",
"clap", "clap",
"reqwest", "reqwest",
"rhema-agent-tools",
"rhema-autonomous-agent", "rhema-autonomous-agent",
"rhema-bash",
"rhema-calendar-integration", "rhema-calendar-integration",
"rhema-claw-tools-contract", "rhema-claw-tools-contract",
"rhema-coding-agent",
"rhema-config", "rhema-config",
"rhema-core", "rhema-core",
"rhema-forge-integration", "rhema-forge-integration",
"rhema-host-agent",
"rhema-identity", "rhema-identity",
"rhema-mcp", "rhema-mcp",
"rhema-memory", "rhema-memory",
"rhema-prompt",
"rhema-provider", "rhema-provider",
"rhema-provider-registry", "rhema-provider-registry",
"rhema-rsd", "rhema-rsd",
"rhema-sandbox",
"rhema-sandbox-http",
"rhema-transcript", "rhema-transcript",
"rusqlite", "rusqlite",
"serde", "serde",
@@ -1879,7 +1997,7 @@ dependencies = [
[[package]] [[package]]
name = "rhema-claw-tools-contract" name = "rhema-claw-tools-contract"
version = "0.2.3" version = "0.4.0"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
@@ -1887,40 +2005,24 @@ dependencies = [
] ]
[[package]] [[package]]
name = "rhema-coding-agent" name = "rhema-config"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b5ef3b970ced4f05b4d18b9df56ca6a46bb488af7579f8d3c4a10788ca47761" checksum = "a0bbfb885f219272d24534c004819db377cf5370de0f82a851f9329466a5349c"
dependencies = [ dependencies = [
"minijinja", "keyring",
"rhema-agent-tools",
"rhema-config",
"rhema-core", "rhema-core",
"rhema-transcript",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
"thiserror", "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]] [[package]]
name = "rhema-core" name = "rhema-core"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b399005d398dd0dca791415a07f6280bacebc0aedfa84f9d3a29640f45f91144" checksum = "c3cd4c7a28b121243a2e26371e53750f28368e96c1a1629f021847c717e1cd55"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"serde", "serde",
@@ -1930,7 +2032,7 @@ dependencies = [
[[package]] [[package]]
name = "rhema-forge-integration" name = "rhema-forge-integration"
version = "0.2.3" version = "0.4.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"reqwest", "reqwest",
@@ -1943,10 +2045,30 @@ dependencies = [
] ]
[[package]] [[package]]
name = "rhema-identity" name = "rhema-host-agent"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f9355d075f5ff5800f9b6b4216e65ba087f681716bc0faf69986852eb13be26" checksum = "3c10a82a420f1ea5ad1e68cabf0da67e6d05f18ec9e6fa02993969c2dcc53a68"
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.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bb799ae7395c647577b9cf26208d81c2913d893db050adc82976e88436226c"
dependencies = [ dependencies = [
"rusqlite", "rusqlite",
"serde", "serde",
@@ -1955,9 +2077,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-mcp" name = "rhema-mcp"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efb7dff3b33b3931c9da4ea6577e55f41c820cf5b2b880b06b8581f15673e06e" checksum = "6ed674931827b5b5e3130b376bda837cf49bda6ca6c94392430b74e292b6f516"
dependencies = [ dependencies = [
"async-stream", "async-stream",
"axum", "axum",
@@ -1967,10 +2089,12 @@ dependencies = [
"futures-util", "futures-util",
"http-body-util", "http-body-util",
"hyper", "hyper",
"hyper-rustls",
"hyper-util", "hyper-util",
"mcp-to-cli", "mcp-to-cli",
"rhema-agent-tools", "rhema-bash",
"rhema-config", "rhema-config",
"rhema-prompt",
"serde", "serde",
"serde_json", "serde_json",
"sha2 0.10.9", "sha2 0.10.9",
@@ -1980,9 +2104,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-memory" name = "rhema-memory"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5a0f161c473ae19dc161a1ad898603150ec6be081f24262182e15ea348db3b5" checksum = "34d3b6763b7c567849b6f1787bae7152ce92ec38bdbe2ec27691d4ef2596c259"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"rhema-core", "rhema-core",
@@ -1993,13 +2117,27 @@ dependencies = [
] ]
[[package]] [[package]]
name = "rhema-provider" name = "rhema-prompt"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d178053a9d5400cf001109670f2294e427ded6cb895b235b4f4ffc2bc20f2f09" checksum = "b70bba0a045879067817db80fcaa7578dc32ef699786cc004b8fdb73bccc47e4"
dependencies = [
"minijinja",
"rhema-core",
"serde",
"serde_json",
"serde_yaml",
]
[[package]]
name = "rhema-provider"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c400c1ac8430f78184ecc12024605686a988ada7a3ee30dd67a4ce12114ccb9e"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-core", "futures-core",
"reqwest",
"rhema-core", "rhema-core",
"serde", "serde",
"serde_json", "serde_json",
@@ -2009,9 +2147,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-anthropic" name = "rhema-provider-anthropic"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc26ff01350bab0fb10a53fc11665dca939c3fda2ec1a3df93912a39b3fc8b0c" checksum = "a57458493f5b1fb540fa47f558f7743094dc123d2c06815d2078f9303d9df22f"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-util", "futures-util",
@@ -2025,14 +2163,14 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-chatgpt" name = "rhema-provider-chatgpt"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb807b39e95c49d2a5e8c101220ac34a9d6770aece6bece1eebcf8113b1811a2" checksum = "7642b1e0bc194cc81d7f347182eecd6702a04a85de41912bd2d34b2cdf41ca7b"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64 0.22.1", "base64 0.22.1",
"futures-util", "futures-util",
"rand", "rand 0.8.8",
"reqwest", "reqwest",
"rhema-core", "rhema-core",
"rhema-provider", "rhema-provider",
@@ -2044,9 +2182,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-copilot" name = "rhema-provider-copilot"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98cc6f041cb328de999c17abc34d3e050d586a2390d32ec9ae5fa543bd177fa0" checksum = "eb39fa7f059df415bdef2453e58ad5359fd74eeb39f7981179f03c78ffb5af7d"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-util", "futures-util",
@@ -2062,9 +2200,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-google" name = "rhema-provider-google"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99cbbb477a94d995b09a3154288a0f5f10aee22fd35bc1d1145bbffee27ea388" checksum = "7dda76eea354cfbdfd4a2dfa1fc1ce8da823675699cf2bf4d3ace8560fec2cd7"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-util", "futures-util",
@@ -2078,9 +2216,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-llama-cpp" name = "rhema-provider-llama-cpp"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e3491fcb305e448492868473c6a146575174bdbb7ab328c85bf43a698052f56" checksum = "953181611b909688db511f891e8c59e034b90bd798034f1afef36cac05409566"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-util", "futures-util",
@@ -2094,10 +2232,29 @@ dependencies = [
] ]
[[package]] [[package]]
name = "rhema-provider-openai-compatible" name = "rhema-provider-mistral"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98976f2fd5f8f09e5838405f53e2b9f113a5e9d2ed3823a80117f4919f0249a6" checksum = "1f657297d7d617a14b10bb6248e944d053d73a536d3b6ae4ee4cc8acabcb4a57"
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.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a90f1620882b2a3dbdb00065b29c329622c5596f582027b29130fbd40003b450"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-util", "futures-util",
@@ -2111,9 +2268,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-opencode" name = "rhema-provider-opencode"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f6cc7db60525e63712ec2b66881cd57f3bb7b7b8c14001eebf86f64030302a" checksum = "2068c980362fe3d4f7876e5e842f51c0719626449afac64192592865e11a0108"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"reqwest", "reqwest",
@@ -2126,9 +2283,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-openrouter" name = "rhema-provider-openrouter"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ca68e90f9627c58e0908e52e010bd7c47e498290c40358c2ff326e95a9a20cc" checksum = "c2025f84d6a1fd1e513ffad4b374d280f0db600ffac635dfe08a58d04b03e91d"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"futures-util", "futures-util",
@@ -2142,9 +2299,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-provider-registry" name = "rhema-provider-registry"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8f6b0b10943f6fa4272490acc3c33040944d85490971a8a1acc8515d704bfc2" checksum = "be5ed790e3dc4fc3a42bd9b1a633ef72204c519810ce03dafb2792a8ff0b6bf8"
dependencies = [ dependencies = [
"rhema-core", "rhema-core",
"rhema-provider", "rhema-provider",
@@ -2153,6 +2310,7 @@ dependencies = [
"rhema-provider-copilot", "rhema-provider-copilot",
"rhema-provider-google", "rhema-provider-google",
"rhema-provider-llama-cpp", "rhema-provider-llama-cpp",
"rhema-provider-mistral",
"rhema-provider-openai-compatible", "rhema-provider-openai-compatible",
"rhema-provider-opencode", "rhema-provider-opencode",
"rhema-provider-openrouter", "rhema-provider-openrouter",
@@ -2161,9 +2319,9 @@ dependencies = [
[[package]] [[package]]
name = "rhema-rsd" name = "rhema-rsd"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1e05417b86144a2a0dbad3018a73c0b2376b5fec378676aea6b912678b059f6" checksum = "3a4bd0555ff3720c0501187f5e9c6ee19ebebb95c1ecdb296c509c2e2dd971ce"
dependencies = [ dependencies = [
"rhema-core", "rhema-core",
"rusqlite", "rusqlite",
@@ -2173,10 +2331,75 @@ dependencies = [
] ]
[[package]] [[package]]
name = "rhema-transcript" name = "rhema-sandbox"
version = "0.2.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b00234b8879bd894f0a45a1fd804c94c7cc3d31ea9f5361609041cb42587a719" checksum = "7030dbd46aa8a2398452dcf86b6b39d13b82909b9fdc654c49e1374183594779"
dependencies = [
"async-trait",
"rhema-bash",
"rhema-core",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "rhema-sandbox-http"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5171470a8a56246e036aa10fc63e641ae7907a3ce70ac8f4816f3c9499eb75b"
dependencies = [
"async-trait",
"base64 0.22.1",
"reqwest",
"rhema-sandbox",
"serde",
"serde_json",
]
[[package]]
name = "rhema-session-store"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef2dd4aca030a56e438c136099d3f07d6fd4649a3db1be6c9838a68a6530cbf6"
dependencies = [
"rhema-core",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "rhema-session-store-file"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5ff65f110123026ae79679572b084c517693f81e0d464897e580b64985a9507"
dependencies = [
"rhema-config",
"rhema-core",
"rhema-session-store",
"serde_json",
]
[[package]]
name = "rhema-submissions"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d054ba904c324ef057c8fb4b9c88a40703496c8b621768844af56a8893d3fb99"
dependencies = [
"rhema-core",
"rhema-session-store",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "rhema-transcript"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "800261e8c1f29e6ceee48769bba2aaea19ccd3496ff8c6c76c617aa7d53ec2db"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"rhema-core", "rhema-core",
@@ -2224,6 +2447,12 @@ dependencies = [
"sqlite-wasm-rs", "sqlite-wasm-rs",
] ]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.6" version = "1.1.6"
@@ -2244,6 +2473,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"ring",
"rustls-pki-types", "rustls-pki-types",
"rustls-webpki", "rustls-webpki",
"subtle", "subtle",
@@ -2256,6 +2486,7 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [ dependencies = [
"web-time",
"zeroize", "zeroize",
] ]
@@ -2661,6 +2892,12 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.54.1" version = "1.54.1"
@@ -3032,6 +3269,25 @@ dependencies = [
"wasm-bindgen", "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]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*", "integrations/*"] members = ["crates/*", "integrations/*"]
[workspace.package] [workspace.package]
version = "0.2.3" version = "0.4.0"
edition = "2024" edition = "2024"
rust-version = "1.89" rust-version = "1.89"
license = "MIT" 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. with a web UI and an Android client talking to it.
The framework it embeds (the crates under `crates/` it pulls from 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-rsd`, and friends) lives in the
[rhema repository](https://git.vhaudiquet.fr/vhaudiquet/rhema). [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 **subscribe first, then POST**, the reply arrives on the stream. Thinking
deltas render dim and collapsible, tool rows show name/summary with error deltas render dim and collapsible, tool rows show name/summary with error
coloring (bash-like tools render as shell lines instead: dim `$` prefix, coloring (bash-like tools render as shell lines instead: dim `$` prefix,
the command line, and an exit-code badge), pasted payloads embedded in a the command line, and an exit-code badge), a message's paste chips render
message as paired `U+FFFC` marks render as compact `▣N 5L` chips, and as compact `▣N 5L` labels sliced from the span record its
`user_message` carries beside the plain text (rows recorded before
spans rode the stream still scan the legacy paired-`U+FFFC` form in
the text), and
`attachment` events render as cards: file name, size, caption, an inline `attachment` events render as cards: file name, size, caption, an inline
preview for small (≤ 2 MB) images, and a download-and-open row (bytes preview for small (≤ 2 MB) images, and a download-and-open row (bytes
from `GET /v1/attachments/{id}` land in the app cache and open through a from `GET /v1/attachments/{id}` land in the app cache and open through a
@@ -11,6 +11,7 @@ import rs.rhema.phone.net.ClawApi
import rs.rhema.phone.net.ClawEvent import rs.rhema.phone.net.ClawEvent
import rs.rhema.phone.net.ClawResult import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.OutboundImage import rs.rhema.phone.net.OutboundImage
import rs.rhema.phone.net.PasteSpan
import rs.rhema.phone.net.SseFrame import rs.rhema.phone.net.SseFrame
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -61,6 +62,10 @@ class ChatController(
override val id: Long, override val id: Long,
val text: String, val text: String,
val images: List<SentImage> = emptyList(), val images: List<SentImage> = emptyList(),
// The chip record this surface's rows never carry (its
// composer sends plain text) but a replayed row — a web user's
// chips in this conversation — does; the render slices on it.
val pastes: List<PasteSpan> = emptyList(),
) : Item ) : Item
data class Thinking(override val id: Long, val text: String) : Item data class Thinking(override val id: Long, val text: String) : Item
data class ToolCall( data class ToolCall(
@@ -355,14 +360,15 @@ class ChatController(
is ClawEvent.UserMessage -> { is ClawEvent.UserMessage -> {
// The recorded question — replayed on reload, echoed live // The recorded question — replayed on reload, echoed live
// for a message this surface just sent. An identical last // for a message this surface just sent. An identical last
// row — same text, same image count — is that echo's // row — same text, same image count, same chip record —
// stand-in; skip it, previews and all. // is that echo's stand-in; skip it, previews and all.
val last = list.lastOrNull() val last = list.lastOrNull()
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size)) { if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size && last.pastes == event.pastes)) {
list = list + UserMessage( list = list + UserMessage(
newId(), newId(),
event.text, event.text,
event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) }, event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) },
event.pastes,
) )
} }
} }
@@ -117,6 +117,13 @@ data class RhemaNotification(
@Serializable @Serializable
data class UserImage(val id: String, @SerialName("media_type") val mediaType: String) data class UserImage(val id: String, @SerialName("media_type") val mediaType: String)
// One paste chip a user_message records: the byte span (UTF-8) of the
// payload in the message's plain text, plus the payload's line count
// — the session annotation's own shape (rhema-core `PasteSpan`), so a
// chip renders from the record instead of rebuilding the wire form.
@Serializable
data class PasteSpan(val start: Int = 0, val end: Int = 0, val lines: Int = 0)
// One event of GET /v1/sessions/{key}/history: the record's seq for it, // One event of GET /v1/sessions/{key}/history: the record's seq for it,
// beside the event itself. Seq order is the wire order. // beside the event itself. Seq order is the wire order.
@Serializable @Serializable
@@ -138,11 +145,13 @@ data class HistoryPage(val events: List<HistoryEvent> = emptyList(), val more: B
sealed interface ClawEvent { sealed interface ClawEvent {
@Serializable @Serializable
@SerialName("user_message") @SerialName("user_message")
// Rows recorded before images rode the stream carry no field at // Rows recorded before images — and then before chips — rode the
// all; absent folds to none, never a guessed shape. // stream carry no field at all; absent folds to none, never a
// guessed shape.
data class UserMessage( data class UserMessage(
val text: String = "", val text: String = "",
val images: List<UserImage> = emptyList(), val images: List<UserImage> = emptyList(),
val pastes: List<PasteSpan> = emptyList(),
) : ClawEvent ) : ClawEvent
@Serializable @Serializable
@@ -82,6 +82,7 @@ import rs.rhema.phone.chat.MAX_STAGED_IMAGES
import rs.rhema.phone.data.AgentIdentityCache import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.di.AppContainer import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PasteSpan
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -438,6 +439,7 @@ private sealed interface TurnGroup {
val id: Long, val id: Long,
val text: String, val text: String,
val images: List<ChatController.SentImage>, val images: List<ChatController.SentImage>,
val pastes: List<PasteSpan> = emptyList(),
) : TurnGroup { ) : TurnGroup {
override val key: String = "u$id" override val key: String = "u$id"
} }
@@ -451,7 +453,7 @@ private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
val groups = mutableListOf<TurnGroup>() val groups = mutableListOf<TurnGroup>()
for (item in items) { for (item in items) {
when (item) { when (item) {
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images) is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images, item.pastes)
else -> { else -> {
val last = groups.lastOrNull() val last = groups.lastOrNull()
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item)) if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item))
@@ -501,10 +503,13 @@ private fun TurnGroupRow(
} }
} }
} }
// Embedded pastes render as chips, not payloads; the // Chips render as chips, not payloads; the text
// text around them stays verbatim. // around them stays verbatim. The row's chip record
// slices them out of the plain text; a row from
// before the record rode the stream carries none
// and still scans the mark form in the text.
var chip = 0 var chip = 0
pasteParts(group.text).forEach { part -> messageParts(group.text, group.pastes).forEach { part ->
when (part) { when (part) {
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge) is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
is PastePart.Paste -> { is PastePart.Paste -> {
@@ -740,20 +745,67 @@ private fun PasteChip(label: String) {
) )
} }
// --- embedded pastes -------------------------------------------------- // --- paste chips ------------------------------------------------------
// The wire form a long paste travels in: MARK, payload, MARK — one // A long paste rides as a chip the render stands in for its payload.
// logical unit inside otherwise plain text (rhema-core's paste module // The record is the span list a user_message carries (the session
// is the definition; these are its client-side shape). A mark with no // annotation's own shape); the marks in the text are the record's
// partner is literal text. // legacy spelling, kept for rows that predate it — a mark with no
// partner is literal text (rhema-core's paste module is the
// definition; these are its client-side shape).
private const val PASTE_MARK = '\uFFFC' private const val PASTE_MARK = '\uFFFC'
/** One scanned piece of embedded-form text. */ /** One piece of a rendered message: literal text, or a chip standing
* for its payload. */
private sealed interface PastePart { private sealed interface PastePart {
data class Text(val text: String) : PastePart data class Text(val text: String) : PastePart
data class Paste(val payload: String) : PastePart data class Paste(val payload: String) : PastePart
} }
/** A message's parts. The chip record is the modern form — each span
* names the payload's byte range in the plain text — and rows recorded
* before it rode the stream carry none; those still scan the legacy
* mark form in the text itself. */
private fun messageParts(text: String, pastes: List<PasteSpan> = emptyList()): List<PastePart> =
if (pastes.isEmpty()) pasteParts(text) else spanParts(text, pastes)
/** Splits a record-carrying message into its parts, left to right. The
* spans' offsets are UTF-8 bytes, the plain form the fold measured —
* every character boundary is mapped in one walk, and a span that
* splits a character maps to none: the render skips it rather than cut
* one in half. Malformed input never throws. */
private fun spanParts(text: String, pastes: List<PasteSpan>): List<PastePart> {
var bytes = 0
var units = 0
val at = mutableMapOf(0 to 0)
var index = 0
while (index < text.length) {
val codePoint = text.codePointAt(index)
val width = Character.charCount(codePoint)
index += width
units = index
bytes += when {
codePoint < 0x80 -> 1
codePoint < 0x800 -> 2
codePoint < 0x10000 -> 3
else -> 4
}
at[bytes] = units
}
val parts = mutableListOf<PastePart>()
var cut = 0
for (span in pastes.sortedBy { it.start }) {
val start = at[span.start]
val end = at[span.end]
if (start == null || end == null || start < cut || end < start) continue
if (start > cut) parts += PastePart.Text(text.substring(cut, start))
parts += PastePart.Paste(text.substring(start, end))
cut = end
}
if (cut < text.length) parts += PastePart.Text(text.substring(cut))
return parts
}
/** Splits embedded-form text into its parts, left to right. A mark with /** Splits embedded-form text into its parts, left to right. A mark with
* no partner is literal text; malformed input never throws. */ * no partner is literal text; malformed input never throws. */
private fun pasteParts(text: String): List<PastePart> { private fun pasteParts(text: String): List<PastePart> {
+23 -14
View File
@@ -26,29 +26,36 @@ mock = ["rhema-core/mock"]
[dependencies] [dependencies]
# The shared toolkit: the resident agent assembles its agent from the # The shared toolkit: the resident agent assembles its agent from the
# shell, the approval seam, paste expansion, and revive-on-resume # shell, the approval seam, and revive-on-resume (rhema-bash), the
rhema-agent-tools = "0.2.3" # system-prompt renderer (rhema-prompt), and the driver that turns a
rhema-autonomous-agent = "0.2.3" # provider into a host-operating agent (rhema-host-agent)
rhema-coding-agent = "0.2.3" rhema-bash = "0.4.0"
rhema-config = "0.2.3" rhema-prompt = "0.4.0"
rhema-core = "0.2.3" rhema-host-agent = "0.4.0"
rhema-autonomous-agent = "0.4.0"
rhema-config = "0.4.0"
rhema-core = "0.4.0"
# The bounded request view over the claw sessions, on by default here # The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.2.3" rhema-transcript = "0.4.0"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" } rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" } rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll # The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat # with, and the identity tools manage them over chat
rhema-identity = "0.2.3" rhema-identity = "0.4.0"
rhema-rsd = "0.2.3" rhema-rsd = "0.4.0"
# The sandbox seam: where `bash` runs, local process or a daemon speaking
# the wire protocol over HTTP
rhema-sandbox = "0.4.0"
rhema-sandbox-http = "0.4.0"
# The tool contract: the agent-token allowlist and version the auth # The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw -> # middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse. # contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" } rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain # The resident tier's durable memory: its tools join the resolver chain
rhema-memory = "0.2.3" rhema-memory = "0.4.0"
# The shared ModelCard the backend registry's listings return # The shared ModelCard the backend registry's listings return
rhema-provider = "0.2.3" rhema-provider = "0.4.0"
rhema-provider-registry = "0.2.3" rhema-provider-registry = "0.4.0"
# Args for the two-flag binary surface # Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true } serde = { workspace = true }
@@ -59,6 +66,8 @@ thiserror = { workspace = true }
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's # A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
# concurrent handler runs share it. `net` is the HTTP listener. # concurrent handler runs share it. `net` is the HTTP listener.
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] }
# The sandbox executor implements the shell seam
async-trait = { workspace = true }
# The chat surface: native routes plus SSE, and the OpenAI shim # The chat surface: native routes plus SSE, and the OpenAI shim
axum = { workspace = true } axum = { workspace = true }
# Broadcast receivers as SSE bodies # Broadcast receivers as SSE bodies
@@ -71,7 +80,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the # Inbound chat images ride base64; the dispatch decodes them into the
# attachment store # attachment store
base64 = "0.22" base64 = "0.22"
rhema-mcp = "0.2.3" rhema-mcp = "0.4.0"
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
@@ -83,7 +92,7 @@ reqwest = { version = "0.12", features = ["json", "stream"] }
bytes = "1" bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock # The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer # feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.2.3", features = ["mock"] } rhema-core = { version = "0.4.0", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints] [lints]
+19 -2
View File
@@ -69,6 +69,10 @@ listen: 127.0.0.1:7799
token: change-me # optional; when set, /v1/* requires it token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools) agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: http # local (default) or http
url: https://box.example:7600 # the sandboxd base URL
token: sandbox-secret # the daemon's shared secret, if it has one
poll_interval_secs: 120 poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty watches: # a seed: imported while the table is empty
@@ -96,6 +100,14 @@ unattended for a long time, so a cap this deep is a runaway guard, not
a work timer — a turn that hits it ends with a failed outcome and the a work timer — a turn that hits it ends with a failed outcome and the
conversation intact; a follow-up message keeps going. conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
`/workspace`. Later edits stay there; the claw does not copy them back.
The surface refuses to start on a non-loopback `listen` with no The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer `token`: anything beyond loopback can reach the port, and the bearer
token is what stands between it and the agent's tools. Set a token, or token is what stands between it and the agent's tools. Set a token, or
@@ -123,7 +135,7 @@ The native surface:
``` ```
GET /healthz GET /v1/sessions GET /healthz GET /v1/sessions
POST /v1/sessions {"name"} — create an empty interactive session POST /v1/sessions {"name"} — create an empty interactive session
POST /v1/sessions/{key}/messages {"text": "..."} -> 202 POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?} -> 202
GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n> GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
DELETE /v1/sessions/{key} drop a session and its turn history DELETE /v1/sessions/{key} drop a session and its turn history
@@ -137,6 +149,8 @@ DELETE /v1/consents/{id} deny a pending ask
GET /v1/attachments/{id} an attached file's bytes GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
GET /v1/providers the backend instances + the active pair GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted PUT /v1/providers/{id}/credentials add or replace an instance, persisted
@@ -169,7 +183,10 @@ lets a UI badge setup state.
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`, SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`, `thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
`turn_done`. Every streamed event is persisted as it streams, so both a `turn_done`. A `user_message` names its paste chips as the byte spans
they stand for in its plain text (`paste::PasteSpan`, the session
record's own shape) — a client renders from that record; rows recorded
before spans arrived carry the legacy mark form in the text instead. Every streamed event is persisted as it streams, so both a
reload and a daemon restart rebuild the transcript, and a session that reload and a daemon restart rebuild the transcript, and a session that
runs for weeks keeps all of it. runs for weeks keeps all of it.
+1 -1
View File
@@ -26,9 +26,9 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use rhema_agent_tools::render_template;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait}; use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::ToolSpec; use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json}; use serde_json::{Value, json};
/// The built-in system prompt, kept as data next to the code and read /// The built-in system prompt, kept as data next to the code and read
+57 -6
View File
@@ -13,6 +13,7 @@
//! binary's startup, not here — the daemon library takes the built //! binary's startup, not here — the daemon library takes the built
//! provider, so tests can inject a mock. //! provider, so tests can inject a mock.
use std::num::NonZeroU32;
use std::path::PathBuf; use std::path::PathBuf;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -22,10 +23,13 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60; pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60;
/// How many tool rounds one chat turn may run, when /// How many tool rounds one chat turn may run, when
/// [`ClawConfig::max_turn_steps`] is unset — the coding driver's own /// [`ClawConfig::max_turn_steps`] is unset — the host agent driver's
/// budget shape and its default: deep enough that a cap is a runaway /// own budget shape and its default: deep enough that a cap is a
/// guard for an agent meant to work unattended, not a work timer. /// runaway guard for an agent meant to work unattended, not a work
pub const DEFAULT_MAX_TURN_STEPS: u32 = 2048; /// timer. `NonZeroU32`, the driver's own spelling: a turn cannot have
/// no step budget at all, and a config that names zero is refused at
/// load instead of cutting every round dead.
pub const DEFAULT_MAX_TURN_STEPS: NonZeroU32 = NonZeroU32::new(2048).unwrap();
/// Where the HTTP surface listens when [`ClawConfig::listen`] is unset: /// Where the HTTP surface listens when [`ClawConfig::listen`] is unset:
/// loopback only — the surface is for the machine's resident user. /// loopback only — the surface is for the machine's resident user.
@@ -55,6 +59,9 @@ pub enum ConfigError {
"agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes" "agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
)] )]
SameAgentToken, SameAgentToken,
/// The configured sandbox choice cannot run as written.
#[error("sandbox: {0}")]
Sandbox(String),
/// The ingest credential is the same value as the human token or /// The ingest credential is the same value as the human token or
/// the agent token: boot refuses, because the ingest credential's /// the agent token: boot refuses, because the ingest credential's
/// safety is that it is write-only and the event door only — a /// safety is that it is write-only and the event door only — a
@@ -127,7 +134,7 @@ pub struct ClawConfig {
/// How many tool rounds one chat turn may run before it is cut off /// How many tool rounds one chat turn may run before it is cut off
/// with a failed outcome, the conversation intact. A follow-up /// with a failed outcome, the conversation intact. A follow-up
/// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset. /// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset.
pub max_turn_steps: u32, pub max_turn_steps: NonZeroU32,
/// The handler's model backend: `google`, `llama-cpp`, `openrouter`, /// The handler's model backend: `google`, `llama-cpp`, `openrouter`,
/// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve /// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve
/// through the stored rhema config's default profile, env vars /// through the stored rhema config's default profile, env vars
@@ -171,6 +178,10 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still /// Unset closes the door to credentials; the human token can still
/// ingest. /// ingest.
pub ingest_token: Option<String>, pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, or a
/// `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 { impl ClawConfig {
@@ -198,6 +209,7 @@ impl Default for ClawConfig {
tools_bin: None, tools_bin: None,
ingest_token: None, ingest_token: None,
transcript: None, transcript: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
@@ -326,6 +338,12 @@ impl ClawConfig {
{ {
return Err(ConfigError::IngestTokenCollision); return Err(ConfigError::IngestTokenCollision);
} }
if let Some(sandbox) = &self.sandbox {
sandbox
.clone()
.normalized()
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
}
Ok(()) Ok(())
} }
} }
@@ -422,10 +440,14 @@ model: claude-sonnet-4-5
listen: 192.168.1.10:7800 listen: 192.168.1.10:7800
token: sekrit token: sekrit
ingest_token: door-key ingest_token: door-key
sandbox:
kind: http
url: https://box.example:7600
token: sandbox-secret
"; ";
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses"); let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
assert_eq!(config.poll_interval_secs, 30); assert_eq!(config.poll_interval_secs, 30);
assert_eq!(config.max_turn_steps, 512); assert_eq!(config.max_turn_steps, NonZeroU32::new(512).unwrap());
assert_eq!(config.provider.as_deref(), Some("anthropic")); assert_eq!(config.provider.as_deref(), Some("anthropic"));
assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5")); assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5"));
assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800")); assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800"));
@@ -438,6 +460,35 @@ ingest_token: door-key
config.bootstrap_root.as_deref(), config.bootstrap_root.as_deref(),
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap")) Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap"))
); );
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
}
#[test]
fn an_http_sandbox_needs_a_url_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
token: None,
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"a remote sandbox without a URL is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
token: None,
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
} }
#[test] #[test]
+74 -7
View File
@@ -62,6 +62,9 @@ pub enum ClawError {
/// The runtime settings table could not be opened or read. /// The runtime settings table could not be opened or read.
#[error(transparent)] #[error(transparent)]
Settings(#[from] crate::settings::SettingsError), Settings(#[from] crate::settings::SettingsError),
/// The sandbox choice could not be loaded or is malformed.
#[error(transparent)]
Sandbox(#[from] crate::sandbox::SandboxError),
/// The notification table could not be opened or read. /// The notification table could not be opened or read.
#[error(transparent)] #[error(transparent)]
Notifications(#[from] crate::notifications::NotificationStoreError), Notifications(#[from] crate::notifications::NotificationStoreError),
@@ -123,6 +126,30 @@ fn interactive_dispatch() -> DispatcherConfig {
} }
} }
/// The forge dispatcher's timing: the library defaults, except the lease
/// TTL.
///
/// A forge turn is not a chat step. The handler clones a repository,
/// reads it, and may build and test a fix — tens of minutes of wall
/// clock — and nothing renews the lease once the turn is under way:
/// `SessionContext::poll_inbox` renews, and the handler calls it once, at
/// the start; the commit hook that runs between tool calls *checkpoints*,
/// which fails on a lapsed lease instead of extending one. So the TTL is
/// a hard ceiling on a whole turn: cross it and the turn dies on its next
/// tool call, after which the driver's own checkpoint and release both
/// report `Expired` and the key ends with no outcome recorded — a silent
/// kill, indistinguishable from a pass that found nothing.
///
/// `DispatcherConfig::default`'s ten minutes are the spec's example
/// values, sized for a single agent step. An hour matches the
/// interactive lane's choice for the same reason: the work is long.
pub fn forge_dispatch() -> DispatcherConfig {
DispatcherConfig {
lease_ttl_millis: 3_600_000,
..DispatcherConfig::default()
}
}
/// The resident daemon: the extension set's sources (the forge watches, /// The resident daemon: the extension set's sources (the forge watches,
/// the task scheduler, the coding jobs, the calendar reminders), the /// the task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface. /// three drivers, and the HTTP surface.
@@ -151,8 +178,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one /// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive /// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is /// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — the resident loop uses the /// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// defaults, `--once` zeroes the debounce. /// with `--once` zeroing the debounce.
pub fn build( pub fn build(
config: &ClawConfig, config: &ClawConfig,
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
@@ -225,6 +252,10 @@ impl Daemon {
// The forge handler resolves its watches through the table at // The forge handler resolves its watches through the table at
// dispatch time, so a watch added mid-run is answerable without a // dispatch time, so a watch added mid-run is answerable without a
// restart. // restart.
// The runtime settings table, opened before the handlers so the
// sandbox choice and the provider write share one connection.
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The client tools' connection, handed to the agent's shell as // The client tools' connection, handed to the agent's shell as
// environment: the URL the surface answers on, the scoped // environment: the URL the surface answers on, the scoped
// agent token (the middleware keeps it to the contract's data // agent token (the middleware keeps it to the contract's data
@@ -252,6 +283,25 @@ impl Daemon {
format!("{}:{inherited}", tools_bin.display()), format!("{}:{inherited}", tools_bin.display()),
); );
} }
// Where `bash` runs: the stored choice wins, the config seeds a
// fresh store. The state is shared by every handler and the
// surface, so a switch is live on the next turn.
let sandbox = Arc::new(crate::sandbox::SandboxState::load(
settings.clone(),
config.sandbox.clone(),
interactive_workspace.clone(),
&tool_env,
)?);
let sandbox_choice = sandbox.choice();
eprintln!(
"[claw] sandbox: {}{}",
sandbox_choice.kind.as_str(),
sandbox_choice
.url
.as_deref()
.map(|url| format!(" ({url})"))
.unwrap_or_default(),
);
let forge_handler = ClawHandler::new( let forge_handler = ClawHandler::new(
backends.clone(), backends.clone(),
workspace_root, workspace_root,
@@ -259,7 +309,8 @@ impl Daemon {
accounts.clone(), accounts.clone(),
config.transcript_enabled(), config.transcript_enabled(),
tool_env.clone(), tool_env.clone(),
); )
.with_sandbox(sandbox.clone());
// Three drivers over one store admit from the same table, so // Three drivers over one store admit from the same table, so
// each owns its slice of the key space: a forge pass must never // each owns its slice of the key space: a forge pass must never
// pick up a resident or job event (it would fail it, and // pick up a resident or job event (it would fail it, and
@@ -292,7 +343,6 @@ impl Daemon {
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?); let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?); let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?); let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The identity store shares the settings table and keeps its // The identity store shares the settings table and keeps its
// images beside the database. // images beside the database.
let identity = Arc::new(crate::identity::IdentityStore::new( let identity = Arc::new(crate::identity::IdentityStore::new(
@@ -361,7 +411,8 @@ impl Daemon {
extensions.clone(), extensions.clone(),
config.transcript_enabled(), config.transcript_enabled(),
) )
.with_steer(steer.clone()); .with_steer(steer.clone())
.with_sandbox(sandbox.clone());
let interactive_driver = Arc::new( let interactive_driver = Arc::new(
Driver::new( Driver::new(
interactive_dispatcher.clone(), interactive_dispatcher.clone(),
@@ -381,7 +432,8 @@ impl Daemon {
notifications.clone(), notifications.clone(),
config.max_turn_steps, config.max_turn_steps,
config.transcript_enabled(), config.transcript_enabled(),
); )
.with_sandbox(sandbox.clone());
let jobs_driver = Arc::new( let jobs_driver = Arc::new(
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler)) Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
.with_holder("rhema-claw-jobs") .with_holder("rhema-claw-jobs")
@@ -410,6 +462,7 @@ impl Daemon {
bridge, bridge,
attachments, attachments,
phone, phone,
sandbox,
config.token.clone(), config.token.clone(),
config.agent_token.clone(), config.agent_token.clone(),
config.ingest_token.clone(), config.ingest_token.clone(),
@@ -551,7 +604,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> { ) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig { let dispatch = DispatcherConfig {
debounce_window_millis: 0, debounce_window_millis: 0,
..DispatcherConfig::default() ..forge_dispatch()
}; };
let daemon = Daemon::build(config, backends, dispatch)?; let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?; daemon.bootstrap().await?;
@@ -562,6 +615,20 @@ pub async fn run_once(
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn the_forge_dispatcher_leases_for_a_turn_not_a_step() {
let dispatch = forge_dispatch();
assert_eq!(
dispatch.lease_ttl_millis, 3_600_000,
"an hour: a turn clones, reads, builds and tests"
);
assert_eq!(
dispatch.debounce_window_millis,
DispatcherConfig::default().debounce_window_millis,
"the rest stays the library's defaults"
);
}
#[test] #[test]
fn the_interactive_dispatcher_dispatches_now_and_leases_long() { fn the_interactive_dispatcher_dispatches_now_and_leases_long() {
let dispatch = interactive_dispatch(); let dispatch = interactive_dispatch();
+71 -4
View File
@@ -24,10 +24,10 @@ use std::sync::{Arc, Mutex, PoisonError};
use rhema_autonomous_agent::{Source, SourceError, async_trait}; use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_forge_integration::forge_key_fn; use rhema_forge_integration::forge_key_fn;
use rhema_forge_integration::triage::{self, Triage}; use rhema_forge_integration::triage::{self, Role, Triage};
use rhema_forge_integration::{ use rhema_forge_integration::{
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, RepoRef, Timestamp, Watcher, Forge, GitHubForge, GitLabForge, GiteaForge, Notification, NotificationReason, RepoRef,
register_forge, Timestamp, Watcher, register_forge,
}; };
use rhema_identity::{IdentityStore, SecretKind}; use rhema_identity::{IdentityStore, SecretKind};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock}; use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
@@ -514,7 +514,7 @@ impl ForgeSource {
let now = SystemClock.now_millis(); let now = SystemClock.now_millis();
let mut fed = 0; let mut fed = 0;
for notification in &page.notifications { for notification in &page.notifications {
match triage::classify(notification) { match claw_triage(notification) {
Triage::Ignore => {} Triage::Ignore => {}
Triage::Surface => { Triage::Surface => {
if let Err(err) = self.notifications.push( if let Err(err) = self.notifications.push(
@@ -576,6 +576,24 @@ impl ForgeSource {
} }
} }
/// [`triage::classify`], plus the one reclassification a resident agent
/// owes its own name: an @-mention of the daemon is an ask.
///
/// The shared vocabulary reads a mention as [`Triage::Surface`] — right
/// for a consumer that only notifies its human, since a mention is not an
/// assignment. This daemon is the party named: somebody typed `@handle` on
/// a thread and is waiting for an answer, which is the same ask an
/// assignment is. Left as a surface, a mention would be a phone buzz and
/// nothing else — this loop never dispatches for a surface, so the turn
/// that reads the thread would never run and the mention would go
/// unanswered.
fn claw_triage(notification: &Notification) -> Triage {
match &notification.reason {
NotificationReason::Mention => Triage::Agent(Role::Implementer),
_ => triage::classify(notification),
}
}
/// The device-notification text a [`Triage::Surface`] lands: the reason /// The device-notification text a [`Triage::Surface`] lands: the reason
/// and the thread title, so the human can judge without opening the /// and the thread title, so the human can judge without opening the
/// forge. /// forge.
@@ -985,4 +1003,53 @@ mod tests {
}); });
assert_eq!(key.as_str(), "github:issue:acme/widgets#142"); assert_eq!(key.as_str(), "github:issue:acme/widgets#142");
} }
/// The notification fixture the reclassification tests classify: one
/// plain issue thread, the reason the only thing that varies.
fn triaged_notification(reason: NotificationReason) -> Notification {
Notification {
id: format!("github:notification:1@{}", reason.as_str()),
reason,
repo: RepoRef::new("acme", "widgets"),
number: 7,
is_pr: false,
actor: Some("stranger".to_owned()),
title: Some("a title".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-11-21T00:00:00Z").expect("parses"),
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()
);
}
}
} }
+48 -13
View File
@@ -10,7 +10,7 @@
//! //!
//! Session continuity rides the dispatcher, not the filesystem: the //! Session continuity rides the dispatcher, not the filesystem: the
//! agent's session JSON is stashed into `ctx.session.core.driver_state` //! agent's session JSON is stashed into `ctx.session.core.driver_state`
//! before the run returns and restored with [`CodingAgent::from_session`] //! before the run returns and restored with [`HostAgent::from_session`]
//! on the next dispatch of the same key, so a resumed thread keeps its //! on the next dispatch of the same key, so a resumed thread keeps its
//! conversation. Commit-before-execute rides it too: the run installs the //! conversation. Commit-before-execute rides it too: the run installs the
//! context's commit hook, so the intent is in the store before the first //! context's commit hook, so the intent is in the store before the first
@@ -25,9 +25,8 @@ use std::sync::{Arc, Mutex, PoisonError};
use crate::forge::{WatchCredential, record_client, resolve_watch_credential}; use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore; use crate::watch_store::ClawStore;
use rhema_agent_tools::AllowAll;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait}; use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
use rhema_coding_agent::{CodingAgent, CodingAgentConfig}; use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session}; use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
use rhema_forge_integration::ForgeKind; use rhema_forge_integration::ForgeKind;
use rhema_forge_integration::triage::Role; use rhema_forge_integration::triage::Role;
@@ -35,11 +34,13 @@ use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode, EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode,
parse_key, parse_key,
}; };
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_identity::IdentityStore; use rhema_identity::IdentityStore;
use rhema_rsd::{InboxItem, Outcome, ResourceKey}; use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell; use tokio::sync::OnceCell;
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
use crate::sandbox::SandboxState;
/// The handler's tool permissions, resolved deterministically before the /// The handler's tool permissions, resolved deterministically before the
/// agent's first step (spec §8) — never by the model, never mid-run. V1 /// agent's first step (spec §8) — never by the model, never mid-run. V1
@@ -71,6 +72,9 @@ pub struct ClawHandler {
/// agent shell: the daemon URL, the scoped agent token, the tools' /// agent shell: the daemon URL, the scoped agent token, the tools'
/// bin dir on PATH. Empty when the config issues no agent token. /// bin dir on PATH. Empty when the config issues no agent token.
tool_env: std::collections::BTreeMap<String, String>, tool_env: std::collections::BTreeMap<String, String>,
/// 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>>>, clients: Mutex<HashMap<String, Arc<WatchClient>>>,
} }
@@ -92,10 +96,18 @@ impl ClawHandler {
watches, watches,
accounts, accounts,
tool_env, tool_env,
sandbox: None,
clients: Mutex::new(HashMap::new()), clients: Mutex::new(HashMap::new()),
} }
} }
/// Shares the deployment's sandbox choice: a forge turn's commands
/// run where it says, seeded from the thread's host workspace.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// The forge client a dispatch key answers to: /// The forge client a dispatch key answers to:
/// `"github:issue:acme/widgets#7"` resolves its watch record from the /// `"github:issue:acme/widgets#7"` resolves its watch record from the
/// table at dispatch time — the table is the source of truth, not a /// table at dispatch time — the table is the source of truth, not a
@@ -283,7 +295,7 @@ impl ClawHandler {
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role); let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
let mut sink = TurnSink; let mut sink = TurnSink;
let output = agent let output = agent
.turn(prompt, &mut sink, Arc::new(AllowAll)) .turn(prompt, &mut sink)
.await .await
.map_err(|err| format!("turn for {key} failed: {err}"))?; .map_err(|err| format!("turn for {key} failed: {err}"))?;
@@ -330,35 +342,55 @@ impl ClawHandler {
ctx: &SessionContext, ctx: &SessionContext,
workspace: &Path, workspace: &Path,
key: &str, key: &str,
) -> Result<CodingAgent, String> { ) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current(); let (provider, model) = self.backends.current();
let config = self.agent_config(&model, workspace); let config = self.agent_config(provider, &model, workspace);
let agent = match &ctx.session.core.driver_state { let agent = match &ctx.session.core.driver_state {
// A never-dispatched key carries no stash: start clean. // A never-dispatched key carries no stash: start clean.
serde_json::Value::Null => CodingAgent::new(provider, config), serde_json::Value::Null => HostAgent::new(config),
stashed => { stashed => {
let session: Session = serde_json::from_value(stashed.clone()) let session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?; .map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
CodingAgent::from_session(provider, config, session) HostAgent::from_session(config, session)
} }
}; };
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}")) agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
} }
/// The config one dispatch's agent runs on: the default coding /// The config one dispatch's agent runs on: the 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 /// A forge thread answers for as long as the thread lives; without
/// the view its history would ride whole on every step. /// the view its history would ride whole on every step.
fn agent_config(&self, model: &str, workspace: &Path) -> CodingAgentConfig { fn agent_config(
let mut config = CodingAgentConfig::new(model, workspace); &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 // Write the resolved value, not an override: the coding agent's
// own default is on now, and the config's `false` must win. // own default is on now, and the config's `false` must win.
config.transcript = self config.transcript = self
.transcript .transcript
.then(rhema_transcript::TranscriptSettings::default); .then(rhema_transcript::TranscriptSettings::default);
config.shell_env = self.tool_env.clone(); config.shell_env = self.tool_env.clone();
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::vision::apply(&mut config);
crate::mcp::apply(&mut config); crate::mcp::apply(&mut config);
}
}
config config
} }
@@ -1068,6 +1100,7 @@ mod tests {
Content::Text("on it".into()), Content::Text("on it".into()),
Content::Text(" — closing.".into()), Content::Text(" — closing.".into()),
], ],
annotations: Default::default(),
}; };
assert_eq!(final_text(&message).as_deref(), Some("on it — closing.")); assert_eq!(final_text(&message).as_deref(), Some("on it — closing."));
let tool_only = Message { let tool_only = Message {
@@ -1078,6 +1111,7 @@ mod tests {
args: serde_json::json!({}), args: serde_json::json!({}),
provider_data: serde_json::Value::Null, provider_data: serde_json::Value::Null,
})], })],
annotations: Default::default(),
}; };
assert_eq!(final_text(&tool_only), None, "no text, no reply"); assert_eq!(final_text(&tool_only), None, "no text, no reply");
} }
@@ -1221,6 +1255,7 @@ mod tests {
.expect("constructs"), .expect("constructs"),
); );
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new()); let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0;
let on = ClawHandler::new( let on = ClawHandler::new(
registry.clone(), registry.clone(),
"/tmp/w", "/tmp/w",
@@ -1238,12 +1273,12 @@ mod tests {
std::collections::BTreeMap::new(), std::collections::BTreeMap::new(),
); );
assert!( assert!(
on.agent_config("m", Path::new("/tmp/w")) on.agent_config(provider.clone(), "m", Path::new("/tmp/w"))
.transcript .transcript
.is_some() .is_some()
); );
assert!( assert!(
off.agent_config("m", Path::new("/tmp/w")) off.agent_config(provider, "m", Path::new("/tmp/w"))
.transcript .transcript
.is_none() .is_none()
); );
+81 -4
View File
@@ -123,6 +123,9 @@ pub struct ClawState {
/// The phone tables: the command queue the device polls and the /// The phone tables: the command queue the device polls and the
/// reported state the ingest door feeds. /// reported state the ingest door feeds.
phone: Arc<crate::phone::PhoneStore>, phone: Arc<crate::phone::PhoneStore>,
/// Where the agent's `bash` runs: the live choice `/v1/sandbox`
/// edits, shared with every handler.
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>, token: Option<String>,
/// The scoped agent token the client tools hold: a second bearer /// The scoped agent token the client tools hold: a second bearer
/// answering only the contract's data routes (see /// answering only the contract's data routes (see
@@ -146,7 +149,7 @@ impl ClawState {
/// `agent_token`. /// `agent_token`.
#[expect( #[expect(
clippy::too_many_arguments, clippy::too_many_arguments,
reason = "eighteen parts, each load-bearing" reason = "twenty-one parts, each load-bearing"
)] )]
pub fn new( pub fn new(
dispatcher: Arc<Dispatcher>, dispatcher: Arc<Dispatcher>,
@@ -167,6 +170,7 @@ impl ClawState {
bridge: Arc<crate::consents::WaitBridge>, bridge: Arc<crate::consents::WaitBridge>,
attachments: Arc<crate::attachments::AttachmentStore>, attachments: Arc<crate::attachments::AttachmentStore>,
phone: Arc<crate::phone::PhoneStore>, phone: Arc<crate::phone::PhoneStore>,
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>, token: Option<String>,
agent_token: Option<String>, agent_token: Option<String>,
ingest_token: Option<String>, ingest_token: Option<String>,
@@ -190,6 +194,7 @@ impl ClawState {
bridge, bridge,
attachments, attachments,
phone, phone,
sandbox,
token, token,
agent_token, agent_token,
ingest_token, ingest_token,
@@ -289,6 +294,11 @@ impl ClawState {
pub fn watches(&self) -> &ClawStore { pub fn watches(&self) -> &ClawStore {
&self.watches &self.watches
} }
/// Where the agent's `bash` runs.
pub fn sandbox(&self) -> &crate::sandbox::SandboxState {
&self.sandbox
}
} }
/// The app router: `/healthz` open, `/v1` behind the bearer check when /// The app router: `/healthz` open, `/v1` behind the bearer check when
@@ -343,6 +353,7 @@ pub fn router(state: ClawState) -> Router {
) )
.route("/providers/{id}", delete(providers_remove)) .route("/providers/{id}", delete(providers_remove))
.route("/providers/{id}/models", get(providers_models)) .route("/providers/{id}/models", get(providers_models))
.route("/sandbox", get(sandbox_get).put(sandbox_put))
.route( .route(
"/chat/completions", "/chat/completions",
post(crate::openai::chat_completions) post(crate::openai::chat_completions)
@@ -652,12 +663,20 @@ pub const MAX_INBOUND_IMAGES: usize = 8;
pub const MAX_MESSAGE_BODY_BYTES: usize = pub const MAX_MESSAGE_BODY_BYTES: usize =
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024; MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
/// `{"text": "..."}` — one chat message, plus the images it carries. /// `{"text": "..."}` — one chat message, plus the images and the chip
/// A body without `images` is the old shape, unchanged. /// payloads it carries. A body without `images` or `pastes` is the old
/// shape, unchanged.
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct MessageBody { pub struct MessageBody {
/// The message text. /// The message text, plain: each paste payload appended to it in
/// the fold, its chip noted as a span in the recorded event — no
/// mark form on the wire.
pub text: String, pub text: String,
/// The message's staged chips, payloads in order. A sender that
/// mints the legacy mark form sends none; the fold rewrites that
/// form too.
#[serde(default)]
pub pastes: Vec<String>,
/// The message's inline images, each the full MIME type plus bare /// The message's inline images, each the full MIME type plus bare
/// base64. The route checks the budget, then the dispatch copies /// base64. The route checks the budget, then the dispatch copies
/// the bytes into the attachment store — the stream carries ids, /// the bytes into the attachment store — the stream carries ids,
@@ -729,6 +748,7 @@ async fn messages(
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event( if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
key.as_str(), key.as_str(),
&body.text, &body.text,
&body.pastes,
&body.images, &body.images,
)) { )) {
return ( return (
@@ -1982,6 +2002,63 @@ pub(crate) async fn drain_owned(
} }
} }
/// `GET /v1/sandbox`: where the agent's `bash` runs. The token never
/// rides the wire: `token_set` says whether one is stored.
async fn sandbox_get(State(state): State<ClawState>) -> Json<Value> {
Json(sandbox_json(&state))
}
/// The sandbox state as the wire sees it: the shared body of the read
/// and of the write that answers with the new choice.
fn sandbox_json(state: &ClawState) -> Value {
let choice = state.sandbox().choice();
json!({
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
})
}
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` is write-only; `clear_token` drops the
/// stored one. The choice applies on the next turn, no restart.
async fn sandbox_put(
State(state): State<ClawState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let Some(kind) = body["kind"].as_str() else {
return Err(bad_request("body must carry a sandbox kind"));
};
let kind = crate::sandbox::SandboxKind::parse(kind)
.ok_or_else(|| bad_request(format!("unknown sandbox kind {kind:?}")))?;
let current = state.sandbox().choice();
let clear_token = body["clear_token"].as_bool().unwrap_or(false);
let token = if clear_token {
None
} else {
body["token"]
.as_str()
.map(str::to_owned)
.or_else(|| current.token.clone())
};
let choice = crate::sandbox::SandboxChoice {
kind,
url: body["url"]
.as_str()
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
crate::sandbox::SandboxError::Store(_) => internal_error(err),
})?;
Ok(Json(sandbox_json(&state)))
}
/// `GET /v1/providers`: every constructible backend and the active pair. /// `GET /v1/providers`: every constructible backend and the active pair.
/// The active pair is runtime state — the config file seeded it, the /// The active pair is runtime state — the config file seeded it, the
/// settings store owns it now. Each provider is one instance, named by /// settings store owns it now. Each provider is one instance, named by
+38 -4
View File
@@ -28,6 +28,7 @@
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, PoisonError};
use rhema_core::paste::PasteSpan;
use rhema_rsd::ResourceKey; use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::sync::broadcast; use tokio::sync::broadcast;
@@ -74,13 +75,23 @@ pub enum TurnEvent {
/// shows its own messages as it sends them, and skips the live /// shows its own messages as it sends them, and skips the live
/// echo. /// echo.
UserMessage { UserMessage {
/// The input text, verbatim. /// The input text in the plain form the model read — each
/// paste's payload in place, no marks.
text: String, text: String,
/// The batch's images, in arrival order, as the attachment /// The batch's images, in arrival order, as the attachment
/// store holds them. `default` because rows recorded before /// store holds them. `default` because rows recorded before
/// images rode the transcript carry no field. /// images rode the transcript carry no field.
#[serde(default)] #[serde(default)]
images: Vec<UserImage>, images: Vec<UserImage>,
/// The paste chips the input carried, the same span record the
/// session's `rhema-code` annotation holds: the byte range
/// each chip stands for in `text`, plus its line count for the
/// label. `default` because rows recorded before chips rode
/// as spans carry the marks in the text instead — a client
/// that finds none scans for them; skipped when empty, so
/// rows without chips replay byte-for-byte as they landed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pastes: Vec<PasteSpan>,
}, },
/// A piece of the model's reasoning trace, in stream order. /// A piece of the model's reasoning trace, in stream order.
ThinkingDelta { ThinkingDelta {
@@ -565,10 +576,27 @@ mod tests {
serde_json::to_string(&TurnEvent::UserMessage { serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(), text: "hi".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}) })
.unwrap(), .unwrap(),
r#"{"type":"user_message","text":"hi","images":[]}"# r#"{"type":"user_message","text":"hi","images":[]}"#
); );
// The chip record rides only when there is one: the span
// shape is the session annotation's own, byte offsets over
// the plain text.
assert_eq!(
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: vec![PasteSpan {
start: 3,
end: 9,
lines: 4,
}],
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[],"pastes":[{"start":3,"end":9,"lines":4}]}"#
);
assert_eq!( assert_eq!(
serde_json::to_string(&TurnEvent::ToolResult { serde_json::to_string(&TurnEvent::ToolResult {
name: "bash".into(), name: "bash".into(),
@@ -600,7 +628,8 @@ mod tests {
event, event,
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
); );
} }
@@ -614,7 +643,8 @@ mod tests {
assert_eq!( assert_eq!(
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "x".into(), text: "x".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
.kind(), .kind(),
"user_message" "user_message"
@@ -659,6 +689,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
); );
hub.emit(&key, text("hi")); hub.emit(&key, text("hi"));
@@ -669,7 +700,8 @@ mod tests {
vec![ vec![
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
}, },
text("hi"), text("hi"),
], ],
@@ -795,6 +827,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "earlier".into(), text: "earlier".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
); );
let (history, mut receiver) = hub.subscribe_with_history(&key); let (history, mut receiver) = hub.subscribe_with_history(&key);
@@ -896,6 +929,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: format!("q{turn}"), text: format!("q{turn}"),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
); );
hub.emit(&key, text(&format!("a{turn}"))); hub.emit(&key, text(&format!("a{turn}")));
+314 -66
View File
@@ -46,7 +46,8 @@
//! v1's starting point — and the resolver chain are assembled before //! v1's starting point — and the resolver chain are assembled before
//! the first model call; the model never decides its own permissions. //! the first model call; the model never decides its own permissions.
//! The chain is the core toolsets (the shell over the interactive //! 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 //! [`crate::extension::ClawExtension`]'s tools in the standard set's
//! order. The system prompt is rendered per dispatch from the //! order. The system prompt is rendered per dispatch from the
//! bootstrap template over the live SOUL/USER files. //! bootstrap template over the live SOUL/USER files.
@@ -63,16 +64,18 @@
//! rhema-code's UI draws for a steered turn. //! rhema-code's UI draws for a steered turn.
use std::collections::HashMap; use std::collections::HashMap;
use std::num::NonZeroU32;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use rhema_agent_tools::{AllowAll, ExpandPastes, ShellTools, revive_dangling_calls};
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait}; use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{ use rhema_core::{
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message, Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
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_memory::{MemoryResolver, MemoryStore, Scope};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey}; 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::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
use crate::hub::{EventHub, TurnEvent, UserImage}; use crate::hub::{EventHub, TurnEvent, UserImage};
use crate::notifications::NotificationStore; use crate::notifications::NotificationStore;
use crate::sandbox::SandboxState;
use crate::steer::{SteerGuard, SteerRegistry}; use crate::steer::{SteerGuard, SteerRegistry};
/// The key prefixes of the resident context (see the module docs): /// 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 /// The event one chat message becomes. The id is unique per message (a
/// wall-clock millisecond plus a process counter), so a redelivery /// wall-clock millisecond plus a process counter), so a redelivery
/// never dedups a different message away. The payload carries the /// never dedups a different message away. The chips' payloads ride
/// message's images when it has any, and no `images` key when it has /// beside the text, and the images with them, each only when the
/// none — old payloads stay byte-identical. /// message staged any — payloads without chips stay byte-identical.
pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event { pub fn user_event(key: &str, text: &str, pastes: &[String], images: &[WireImage]) -> Event {
static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0); static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0);
let now = SystemTime::now() let now = SystemTime::now()
.duration_since(UNIX_EPOCH) .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) MESSAGE_SEQ.fetch_add(1, Ordering::Relaxed)
), ),
source: SOURCE.to_owned(), source: SOURCE.to_owned(),
payload: if images.is_empty() { // The chips' payloads ride only when the message staged any,
json!({ "key": key, "text": text }) // and images only when it carried any: the old two-field shape
} else { // rides byte-for-byte otherwise.
json!({ "key": key, "text": text, "images": images }) 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, 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 /// 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 /// config's runaway guard for an agent meant to work unattended; a
/// follow-up message keeps going. /// 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 /// The extension set the tool half of the chain is cut from, per
/// dispatch, in the standard set's order — the same set whose /// dispatch, in the standard set's order — the same set whose
/// sources the daemon's tick drives and whose boot pass runs first. /// 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 /// decorator refreshes it per request, `zoom` reads it, and it
/// lives here — the agent rebuilds per dispatch, the log must not. /// lives here — the agent rebuilds per dispatch, the log must not.
transcript_mirror: Option<Arc<std::sync::Mutex<rhema_transcript::Transcript>>>, 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 /// prompt, when provisioning succeeded — the same wiring whose env
/// map lights the shell's inbox up. /// map lights the shell's inbox up.
vision: Option<String>, 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 { impl InteractiveHandler {
@@ -265,7 +281,7 @@ impl InteractiveHandler {
hub: Arc<EventHub>, hub: Arc<EventHub>,
notifications: Arc<NotificationStore>, notifications: Arc<NotificationStore>,
attachments: Arc<crate::attachments::AttachmentStore>, attachments: Arc<crate::attachments::AttachmentStore>,
max_turn_steps: u32, max_turn_steps: NonZeroU32,
extensions: Arc<crate::extension::Extensions>, extensions: Arc<crate::extension::Extensions>,
transcript: bool, transcript: bool,
) -> Self { ) -> Self {
@@ -274,7 +290,7 @@ impl InteractiveHandler {
// chat's commands, and its staged images attach to their // chat's commands, and its staged images attach to their
// results. Local shells only — the interactive handler's // results. Local shells only — the interactive handler's
// executor is this host's by construction. // 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 { let tools = Arc::new(match vision {
Some(wiring) => ShellTools::with_env(&workspace, &wiring.shell_env), Some(wiring) => ShellTools::with_env(&workspace, &wiring.shell_env),
None => ShellTools::new(&workspace), None => ShellTools::new(&workspace),
@@ -301,9 +317,17 @@ impl InteractiveHandler {
))) )))
}), }),
vision: vision.map(|wiring| wiring.section.to_owned()), 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 /// The agent for one dispatch: rebuilt per run over the restored
/// session (the engine's own step counter is per-agent; the /// session (the engine's own step counter is per-agent; the
/// conversation lives in the session, not the agent). The system /// conversation lives in the session, not the agent). The system
@@ -314,12 +338,7 @@ impl InteractiveHandler {
/// request advertises. /// request advertises.
fn agent(&self, key: &ResourceKey) -> Result<Agent, String> { fn agent(&self, key: &ResourceKey) -> Result<Agent, String> {
let (provider, model) = self.backends.current(); let (provider, model) = self.backends.current();
// Chat input may carry embedded pastes — the compact chip form // The view rides outside the engine: stubs, whole messages,
// 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,
// and zoom output all show the text the model would have seen. // and zoom output all show the text the model would have seen.
let provider: Arc<dyn ModelProvider> = match &self.transcript_mirror { let provider: Arc<dyn ModelProvider> = match &self.transcript_mirror {
Some(mirror) => Arc::new(rhema_transcript::TranscriptView::new( Some(mirror) => Arc::new(rhema_transcript::TranscriptView::new(
@@ -329,13 +348,23 @@ impl InteractiveHandler {
None => provider, None => provider,
}; };
let resolver = self.resolver(key); 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( let system = render_system(
DEFAULT_SYSTEM_MD, DEFAULT_SYSTEM_MD,
key.as_str(), key.as_str(),
&self.workspace, &workspace,
&self.bootstrap, &self.bootstrap,
&resolver.specs(), &resolver.specs(),
self.vision.as_deref(), vision,
) )
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?; .map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
Agent::builder() Agent::builder()
@@ -356,6 +385,15 @@ impl InteractiveHandler {
self 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 resolver chain one dispatch runs under: the core toolsets —
/// the shell over the interactive workspace, memory, /// the shell over the interactive workspace, memory,
/// `bootstrap_save` — then every extension's tools in the standard /// `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 /// their asks and cards to the session that asked, and the handler
/// serves every session. /// serves every session.
fn resolver(&self, key: &ResourceKey) -> Arc<ResolverChain> { 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![ let mut resolvers: Vec<Arc<dyn rhema_core::ToolResolver>> = vec![
self.tools.clone(), shell,
Arc::new(MemoryResolver::new( Arc::new(MemoryResolver::new(
self.memory.clone(), self.memory.clone(),
Scope::Workspace(self.workspace.clone()), Scope::Workspace(self.workspace.clone()),
@@ -401,7 +449,9 @@ impl InteractiveHandler {
.await .await
.map_err(|err| format!("inbox poll for {key} failed: {err}"))?; .map_err(|err| format!("inbox poll for {key} failed: {err}"))?;
// Texts fold in arrival order, and so do the images, across // 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 texts = Vec::new();
let mut images = Vec::new(); let mut images = Vec::new();
for item in &items { for item in &items {
@@ -411,7 +461,35 @@ impl InteractiveHandler {
.or_else(|| payload.get("prompt")) .or_else(|| payload.get("prompt"))
.and_then(Value::as_str) .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) { if let Some(carried) = payload.get("images").and_then(Value::as_array) {
images.extend( 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() { if input.trim().is_empty() {
// Round one's emptiness is the dispatch bug it always was: // Round one's emptiness is the dispatch bug it always was:
// the lease exists because something waited. A steered // the lease exists because something waited. A steered
@@ -472,13 +565,17 @@ impl InteractiveHandler {
} }
// The transcript's question, recorded before anything else can // The transcript's question, recorded before anything else can
// stream: a replay shows what was asked, not only what was // stream: a replay shows what was asked, not only what was
// answered. Raw input — the notification-contract framing below // answered. The fold composed the record — plain text, the
// is the model's business, not the viewer's. // 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( self.hub.emit(
&ctx.key, &ctx.key,
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: input.clone(), text: input.clone(),
images: transcript_images, images: transcript_images,
pastes: pastes.clone(),
}, },
); );
// A non-chat resident key has no subscriber to read the reply: // 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 // future at its current await — a streaming request, or a
// running shell command, whose child dies with the drop. The // running shell command, whose child dies with the drop. The
// next round revives whatever committed before the drop. // 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( let mut turn = Box::pin(run_turn(
&mut agent, &mut agent,
&mut session, &mut session,
Message::text_with_images(Role::User, input, core_images), turn_input,
&mut sink, &mut sink,
&tools, &tools,
self.max_turn_steps, self.max_turn_steps,
@@ -679,8 +795,16 @@ enum Round {
fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> { fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
match stashed { match stashed {
Value::Null => Ok(Session::default()), Value::Null => Ok(Session::default()),
stashed => serde_json::from_value(stashed.clone()) stashed => {
.map_err(|err| format!("stashed session for {key} does not parse: {err}")), 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::Usage(_)
| ModelEvent::RetryWait { .. } | ModelEvent::RetryWait { .. }
| ModelEvent::StepEnd { .. } => return, | 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); self.hub.emit(&self.key, turn);
} }
@@ -1056,12 +1184,17 @@ mod tests {
} }
} }
/// The paste contract across the provider seam: a chat input that /// The environment a paste test drives: the recording provider, the
/// carries an embedded paste (the compact form the UIs mint) is /// hub, and a dispatcher wired to one interactive handler over a
/// expanded before the request leaves, while the transcript the hub /// throwaway workspace.
/// streams keeps the compact form. fn paste_env() -> (
#[tokio::test] Arc<RecordingProvider>,
async fn an_embedded_paste_expands_for_the_model_and_not_for_the_transcript() { Arc<EventHub>,
Arc<Dispatcher>,
InteractiveHandler,
Key,
tempfile::TempDir,
) {
let recorder = RecordingProvider::new(); let recorder = RecordingProvider::new();
let store = Arc::new(ClawStore::in_memory().expect("store opens")); let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let hub = Arc::new(EventHub::default()); let hub = Arc::new(EventHub::default());
@@ -1087,7 +1220,7 @@ mod tests {
Arc::new(rhema_memory::VolatileStore::new()), Arc::new(rhema_memory::VolatileStore::new()),
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")), Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
hub.clone(), hub.clone(),
notifications.clone(), notifications,
attachments(), attachments(),
crate::config::DEFAULT_MAX_TURN_STEPS, crate::config::DEFAULT_MAX_TURN_STEPS,
extensions, extensions,
@@ -1102,14 +1235,31 @@ mod tests {
Arc::new(VolatileStore::new()), Arc::new(VolatileStore::new()),
)); ));
register_user(&dispatcher); 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)) let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test"); .with_holder("test");
let key = Key::from("interactive:web");
dispatcher dispatcher
.ingest(user_event( .ingest(user_event(
key.as_str(), key.as_str(),
"review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}", "review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}",
&[], &[],
&[],
)) ))
.expect("ingests"); .expect("ingests");
driver.run_once().await.expect("the run happens"); driver.run_once().await.expect("the run happens");
@@ -1119,17 +1269,61 @@ mod tests {
"review this:fn main() {}\nfn other() {}", "review this:fn main() {}\nfn other() {}",
"the model saw the payload, not the marks" "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 (history, _) = hub.subscribe_with_history(&key);
let saw_input = history.into_iter().find_map(|event| match event { let question = history.into_iter().find_map(|event| match event {
TurnEvent::UserMessage { text, .. } => Some(text), TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
_ => None, _ => None,
}); });
assert!( let (text, pastes) = question.expect("the transcript saw the question");
saw_input let payload = "fn main() {}\nfn other() {}";
.expect("the transcript saw the question") assert_eq!(text, "review this:fn main() {}\nfn other() {}", "no marks");
.contains('\u{FFFC}'), assert_eq!(pastes.len(), 1, "the chip is one span");
"the transcript keeps the compact chip form" 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`. /// A scripted tool-call turn: the model asking for `name` with `args`.
@@ -1143,6 +1337,7 @@ mod tests {
args, args,
provider_data: serde_json::Value::Null, provider_data: serde_json::Value::Null,
})], })],
annotations: Default::default(),
}, },
stop_reason: StopReason::ToolUse, stop_reason: StopReason::ToolUse,
usage: Usage::default(), usage: Usage::default(),
@@ -1253,8 +1448,8 @@ mod tests {
#[test] #[test]
fn user_events_carry_the_key_and_unique_ids() { fn user_events_carry_the_key_and_unique_ids() {
let first = user_event("interactive:web", "hello", &[]); let first = user_event("interactive:web", "hello", &[], &[]);
let second = user_event("interactive:web", "again", &[]); let second = user_event("interactive:web", "again", &[], &[]);
assert_eq!(first.source, "user"); assert_eq!(first.source, "user");
assert_eq!(first.id, first.id, "stable within itself"); assert_eq!(first.id, first.id, "stable within itself");
assert_ne!(first.id, second.id, "messages never share a dedup id"); 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. /// order; a plain message carries no `images` key at all.
#[test] #[test]
fn user_events_carry_images_only_when_the_message_has_any() { 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!( assert_eq!(
bare.payload, bare.payload,
json!({"key": "interactive:web", "text": "plain"}), json!({"key": "interactive:web", "text": "plain"}),
@@ -1277,6 +1472,7 @@ mod tests {
let carried = user_event( let carried = user_event(
"interactive:web", "interactive:web",
"look", "look",
&[],
&[ &[
WireImage { WireImage {
media_type: "image/png".to_owned(), media_type: "image/png".to_owned(),
@@ -1309,7 +1505,7 @@ mod tests {
Arc::new(VolatileStore::new()), Arc::new(VolatileStore::new()),
); );
register_user(&dispatcher); 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 // Ingesting resolves the key through the registered fn: the
// record lands under exactly the payload's key. // record lands under exactly the payload's key.
dispatcher.ingest(event).expect("ingests"); dispatcher.ingest(event).expect("ingests");
@@ -1344,11 +1540,13 @@ mod tests {
Content::Text("on it".into()), Content::Text("on it".into()),
Content::Text(" — done.".into()), Content::Text(" — done.".into()),
], ],
annotations: Default::default(),
}; };
assert_eq!(final_text(&message).as_deref(), Some("on it — done.")); assert_eq!(final_text(&message).as_deref(), Some("on it — done."));
let empty = Message { let empty = Message {
role: Role::Assistant, role: Role::Assistant,
content: vec![Content::Text(" ".into())], content: vec![Content::Text(" ".into())],
annotations: Default::default(),
}; };
assert_eq!(final_text(&empty), None); assert_eq!(final_text(&empty), None);
} }
@@ -1459,6 +1657,42 @@ mod tests {
assert!(err.contains("does not parse"), "{err}"); 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 /// The full dispatch, in-process: one message in, one scripted reply
/// out, the turn streamed through the hub, the conversation stashed. /// out, the turn streamed through the hub, the conversation stashed.
#[tokio::test] #[tokio::test]
@@ -1507,7 +1741,7 @@ mod tests {
let key = Key::from("interactive:web"); let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key); let mut receiver = hub.subscribe(&key);
dispatcher dispatcher
.ingest(user_event(key.as_str(), "hello", &[])) .ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests"); .expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler)) let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
@@ -1520,7 +1754,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
); );
assert_eq!( assert_eq!(
@@ -1596,7 +1831,7 @@ mod tests {
let key = Key::from("interactive:web"); let key = Key::from("interactive:web");
let mut receiver = hub.subscribe(&key); let mut receiver = hub.subscribe(&key);
dispatcher dispatcher
.ingest(user_event(key.as_str(), "hello", &[])) .ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests"); .expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler)) let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test"); .with_holder("test");
@@ -1616,7 +1851,7 @@ mod tests {
// Steer, in the route's order: ingest first, signal second. // Steer, in the route's order: ingest first, signal second.
dispatcher dispatcher
.ingest(user_event(key.as_str(), "stop that", &[])) .ingest(user_event(key.as_str(), "stop that", &[], &[]))
.expect("ingests"); .expect("ingests");
assert!(registry.signal(key.as_str())); assert!(registry.signal(key.as_str()));
@@ -1633,7 +1868,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
); );
assert_eq!( assert_eq!(
@@ -1647,7 +1883,8 @@ mod tests {
receiver.try_recv().unwrap(), receiver.try_recv().unwrap(),
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "stop that".into(), text: "stop that".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
); );
assert_eq!( assert_eq!(
@@ -1821,6 +2058,7 @@ mod tests {
.ingest(user_event( .ingest(user_event(
key.as_str(), key.as_str(),
"look at this", "look at this",
&[],
&[WireImage { &[WireImage {
media_type: "image/png".to_owned(), media_type: "image/png".to_owned(),
data: png.clone(), data: png.clone(),
@@ -1831,6 +2069,7 @@ mod tests {
.ingest(user_event( .ingest(user_event(
key.as_str(), key.as_str(),
"and at this", "and at this",
&[],
&[WireImage { &[WireImage {
media_type: "Image/JPEG".to_owned(), media_type: "Image/JPEG".to_owned(),
data: jpeg.clone(), data: jpeg.clone(),
@@ -1838,7 +2077,7 @@ mod tests {
)) ))
.expect("ingests"); .expect("ingests");
dispatcher dispatcher
.ingest(user_event(key.as_str(), "no picture here", &[])) .ingest(user_event(key.as_str(), "no picture here", &[], &[]))
.expect("ingests"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("the run happens"), driver.run_once().await.expect("the run happens"),
@@ -1851,7 +2090,11 @@ mod tests {
let question = history let question = history
.iter() .iter()
.find_map(|event| match event { .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, _ => None,
}) })
.expect("the transcript saw the question"); .expect("the transcript saw the question");
@@ -1957,7 +2200,7 @@ mod tests {
// Dispatch 1: the model saves through the chain's memory tools. // Dispatch 1: the model saves through the chain's memory tools.
dispatcher dispatcher
.ingest(user_event(key.as_str(), "remember the channel", &[])) .ingest(user_event(key.as_str(), "remember the channel", &[], &[]))
.expect("ingests"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("first run"), driver.run_once().await.expect("first run"),
@@ -1976,7 +2219,7 @@ mod tests {
// Dispatch 2: the model searches the same chain and answers from // Dispatch 2: the model searches the same chain and answers from
// memory — a fresh session turn, the same durable store. // memory — a fresh session turn, the same durable store.
dispatcher dispatcher
.ingest(user_event(key.as_str(), "where do releases go?", &[])) .ingest(user_event(key.as_str(), "where do releases go?", &[], &[]))
.expect("ingests"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("second run"), 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 // Dispatch 1: the model writes SOUL.md through the chain. A key
// with a session continues, so both calls ride one key. // with a session continues, so both calls ride one key.
dispatcher dispatcher
.ingest(user_event(key.as_str(), "call me claw", &[])) .ingest(user_event(key.as_str(), "call me claw", &[], &[]))
.expect("ingests"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("first run"), driver.run_once().await.expect("first run"),
@@ -2083,7 +2326,7 @@ mod tests {
// Dispatch 2: USER.md, same chain — and the pending flag clears. // Dispatch 2: USER.md, same chain — and the pending flag clears.
dispatcher dispatcher
.ingest(user_event(key.as_str(), "and I am Ana", &[])) .ingest(user_event(key.as_str(), "and I am Ana", &[], &[]))
.expect("ingests"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("second run"), driver.run_once().await.expect("second run"),
@@ -2141,7 +2384,7 @@ mod tests {
register_user(&dispatcher); register_user(&dispatcher);
let key = Key::from("interactive:web"); let key = Key::from("interactive:web");
dispatcher dispatcher
.ingest(user_event(key.as_str(), "hello", &[])) .ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests"); .expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler)); let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
driver.run_once().await.expect("the run happens"); driver.run_once().await.expect("the run happens");
@@ -2281,7 +2524,7 @@ mod tests {
// An interactive reply is the chat surface's business: notified // An interactive reply is the chat surface's business: notified
// nowhere. // nowhere.
dispatcher dispatcher
.ingest(user_event("interactive:web", "hello", &[])) .ingest(user_event("interactive:web", "hello", &[], &[]))
.expect("ingests"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("the run happens"), driver.run_once().await.expect("the run happens"),
@@ -2359,7 +2602,12 @@ mod tests {
// The evening's work, in the chat session. // The evening's work, in the chat session.
dispatcher 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"); .expect("ingests");
assert_eq!( assert_eq!(
driver.run_once().await.expect("first run"), 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 and job resolve through the store, the workspace is the
//! instance's path, the session blob (or a fresh agent) is loaded, the //! instance's path, the session blob (or a fresh agent) is loaded, the
//! allowlist is permissive exactly as the forge path's — and then one //! allowlist is permissive exactly as the forge path's — and then one
//! `CodingAgent` turn runs. The final text lands in the job row and //! `HostAgent` turn runs. The final text lands in the job row and
//! the user's notifications; the turn itself streams nowhere, its //! the user's notifications; the turn itself streams nowhere, its
//! observability is the stderr tool log. //! observability is the stderr tool log.
//! //!
@@ -22,11 +22,13 @@
//! fails before any model call. The trust boundary is unchanged from //! fails before any model call. The trust boundary is unchanged from
//! the forge path — the bearer-gated surface and the instance list. //! the forge path — the bearer-gated surface and the instance list.
use std::num::NonZeroU32;
use std::sync::Arc; use std::sync::Arc;
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait}; use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
use rhema_coding_agent::{AllowAll, CodingAgent, CodingAgentConfig}; use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Event as ModelEvent, EventSink}; use rhema_core::{Event as ModelEvent, EventSink};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey}; use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
@@ -34,6 +36,7 @@ use crate::handler::final_text;
use crate::interactive::passthrough_key_fn; use crate::interactive::passthrough_key_fn;
use crate::job_store::{CodingJobStore, JobStatus}; use crate::job_store::{CodingJobStore, JobStatus};
use crate::notifications::{DEFAULT_DEVICE, NotificationStore}; use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
use crate::sandbox::SandboxState;
/// The source name the coding jobs ingest under. /// The source name the coding jobs ingest under.
pub const JOBS_SOURCE: &str = "jobs"; pub const JOBS_SOURCE: &str = "jobs";
@@ -137,10 +140,13 @@ pub struct CodingJobHandler {
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>, store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>, notifications: Arc<NotificationStore>,
max_turn_steps: u32, max_turn_steps: NonZeroU32,
/// Whether the jobs run the bounded request view (the config's /// Whether the jobs run the bounded request view (the config's
/// `transcript`, on unless set false). /// `transcript`, on unless set false).
transcript: bool, transcript: bool,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>,
} }
impl CodingJobHandler { impl CodingJobHandler {
@@ -151,7 +157,7 @@ impl CodingJobHandler {
backends: Arc<BackendRegistry>, backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>, store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>, notifications: Arc<NotificationStore>,
max_turn_steps: u32, max_turn_steps: NonZeroU32,
transcript: bool, transcript: bool,
) -> Self { ) -> Self {
Self { Self {
@@ -160,9 +166,17 @@ impl CodingJobHandler {
notifications, notifications,
max_turn_steps, max_turn_steps,
transcript, 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 /// One dispatch, failed with a reason on any step; every failure
/// lands in the job row before it lands in the outcome, so the /// lands in the job row before it lands in the outcome, so the
/// model's `status` read and the user's notification agree. /// model's `status` read and the user's notification agree.
@@ -212,7 +226,11 @@ impl CodingJobHandler {
.map_err(|err| format!("job {job_id} could not start: {err}"))?; .map_err(|err| format!("job {job_id} could not start: {err}"))?;
let (provider, model) = self.backends.current(); let (provider, model) = self.backends.current();
let mut config = CodingAgentConfig::new(model, &workspace); let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(&workspace),
None => workspace.clone(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
config.max_turn_steps = self.max_turn_steps; config.max_turn_steps = self.max_turn_steps;
// A job's stashed session carries across runs and only ever // A job's stashed session carries across runs and only ever
// grows; the view is what keeps a repeat run's steps cheap. // grows; the view is what keeps a repeat run's steps cheap.
@@ -221,8 +239,18 @@ impl CodingJobHandler {
config.transcript = self config.transcript = self
.transcript .transcript
.then(rhema_transcript::TranscriptSettings::default); .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::vision::apply(&mut config);
crate::mcp::apply(&mut config); crate::mcp::apply(&mut config);
}
}
let stashed = self let stashed = self
.store .store
.session(&instance_name) .session(&instance_name)
@@ -236,9 +264,9 @@ impl CodingJobHandler {
self.fail(job_id, &instance_name, &reason); self.fail(job_id, &instance_name, &reason);
reason reason
})?; })?;
CodingAgent::from_session(provider, config, session) HostAgent::from_session(config, session)
} }
None => CodingAgent::new(provider, config), None => HostAgent::new(config),
} }
.map_err(|err| { .map_err(|err| {
let reason = format!("cannot start the coding agent for {instance_name:?}: {err}"); let reason = format!("cannot start the coding agent for {instance_name:?}: {err}");
@@ -248,12 +276,12 @@ impl CodingJobHandler {
// Commit-before-execute rides the dispatcher exactly as the // Commit-before-execute rides the dispatcher exactly as the
// forge handler's does: the intent is in the store before the // forge handler's does: the intent is in the store before the
// first tool runs, and a crash-left dangling call revives at // first tool runs, and a crash-left dangling call revives at
// turn entry (CodingAgent::turn's own revive, over the resumed // turn entry (HostAgent::turn's own revive, over the resumed
// session). // session).
agent.set_commit_hook(Some(ctx.commit_hook())); agent.set_commit_hook(Some(ctx.commit_hook()));
let mut sink = JobSink; let mut sink = JobSink;
let output = match agent.turn(&job.prompt, &mut sink, Arc::new(AllowAll)).await { let output = match agent.turn(&job.prompt, &mut sink).await {
Ok(output) => output, Ok(output) => output,
Err(err) => { Err(err) => {
let reason = format!("the coding turn for {instance_name:?} failed: {err}"); let reason = format!("the coding turn for {instance_name:?} failed: {err}");
@@ -280,7 +308,7 @@ impl CodingJobHandler {
Ok(Outcome::Handled) Ok(Outcome::Handled)
} }
fn save_session(&self, instance: &str, agent: &CodingAgent) { fn save_session(&self, instance: &str, agent: &HostAgent) {
match serde_json::to_string(agent.session()) { match serde_json::to_string(agent.session()) {
Ok(blob) => { Ok(blob) => {
let _ = self.store.save_session(instance, &blob); let _ = self.store.save_session(instance, &blob);
@@ -360,7 +388,13 @@ mod tests {
BackendRegistry::new(vec![Backend::headless("mock", provider)], None) BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"), .expect("a single mock backend always constructs"),
); );
CodingJobHandler::new(backends, store, notifications, 16, true) CodingJobHandler::new(
backends,
store,
notifications,
NonZeroU32::new(16).unwrap(),
true,
)
} }
fn reply(text: &str) -> ModelOutput { fn reply(text: &str) -> ModelOutput {
+5 -1
View File
@@ -42,6 +42,8 @@
//! workspace files handed to the human as fetchable cards //! workspace files handed to the human as fetchable cards
//! - [`phone`] — the phone state and command queue: reported status to //! - [`phone`] — the phone state and command queue: reported status to
//! read, consent-gated control actions the device executes //! read, consent-gated control actions the device executes
//! - [`sandbox`]: where `bash` runs, this host, or a remote daemon
//! speaking the sandbox protocol over HTTP
//! - [`watch_tools`] — the agent's watch-management tool set //! - [`watch_tools`] — the agent's watch-management tool set
//! - [`notify_tools`] — the `notify` tool: the queue a device polls //! - [`notify_tools`] — the `notify` tool: the queue a device polls
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task` //! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
@@ -89,6 +91,7 @@ pub mod notifications;
pub mod notify_tools; pub mod notify_tools;
pub mod openai; pub mod openai;
pub mod phone; pub mod phone;
pub mod sandbox;
pub mod settings; pub mod settings;
pub mod steer; pub mod steer;
pub mod task_source; pub mod task_source;
@@ -105,7 +108,7 @@ pub use bootstrap::{
render_system, render_system,
}; };
pub use config::{ClawConfig, ConfigError}; pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, run_once}; pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
pub use environment::write_report; pub use environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes}; pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource; pub use forge::ForgeSource;
@@ -117,6 +120,7 @@ pub use interactive::InteractiveHandler;
pub use mock::MockLoop; pub use mock::MockLoop;
pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError}; pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError};
pub use rhema_forge_integration::{ForgeKind, resolve_token}; pub use rhema_forge_integration::{ForgeKind, resolve_token};
pub use sandbox::{SandboxChoice, SandboxError, SandboxKind, SandboxState};
pub use settings::SettingsStore; pub use settings::SettingsStore;
pub use task_source::{TASKS_SOURCE, TaskScheduler}; pub use task_source::{TASKS_SOURCE, TaskScheduler};
pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError}; pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError};
+5 -5
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use clap::Parser; use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once}; use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::{DispatcherConfig, Outcome}; use rhema_rsd::Outcome;
/// `rhema-claw` — the resident forge-watching agent daemon. /// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@@ -74,9 +74,9 @@ async fn main() {
} }
if let Some(Command::Vision { args: rest }) = &args.command { if let Some(Command::Vision { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1); let mut argv = Vec::with_capacity(rest.len() + 1);
argv.push(std::ffi::OsString::from(rhema_agent_tools::vision::MODE)); argv.push(std::ffi::OsString::from(rhema_bash::vision::MODE));
argv.extend(rest.iter().cloned()); argv.extend(rest.iter().cloned());
std::process::exit(rhema_agent_tools::vision::cli_run(&argv)); std::process::exit(rhema_bash::vision::cli_run(&argv));
} }
if let Err(err) = run(args).await { if let Err(err) = run(args).await {
eprintln!("error: {err}"); eprintln!("error: {err}");
@@ -135,7 +135,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on. // reads it next to the config that turns it on.
config.validate_surface()?; config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts"); eprintln!("[claw] note: resident sessions run tool calls without approval prompts");
let daemon = Daemon::build(&config, backends, DispatcherConfig::default())?; let daemon = Daemon::build(&config, backends, forge_dispatch())?;
daemon.run().await daemon.run().await
} }
} }
+8 -3
View File
@@ -9,7 +9,7 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use rhema_coding_agent::CodingAgentConfig; use rhema_host_agent::HostAgentConfig;
/// What one wiring produced, held for the process. /// What one wiring produced, held for the process.
struct Wired { struct Wired {
@@ -61,7 +61,7 @@ fn wired() -> Option<&'static Wired> {
/// init file, the socket, the token), the prompt's `mcp` lines, and /// init file, the socket, the token), the prompt's `mcp` lines, and
/// the persisted off switch. A frontend without wiring changes /// the persisted off switch. A frontend without wiring changes
/// nothing. /// nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) { pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else { let Some(wired) = wired() else {
return; return;
}; };
@@ -82,7 +82,12 @@ mod tests {
/// same map). /// same map).
#[test] #[test]
fn apply_without_any_wiring_leaves_the_config_alone() { fn apply_without_any_wiring_leaves_the_config_alone() {
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp")); let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
let before = config.shell_env.clone(); let before = config.shell_env.clone();
apply(&mut config); apply(&mut config);
// The wiring only appears when the machine's global mcp.yaml // The wiring only appears when the machine's global mcp.yaml
+1
View File
@@ -65,6 +65,7 @@ impl ModelProvider for MockLoop {
message: Message { message: Message {
role: Role::Assistant, role: Role::Assistant,
content: vec![Content::Text(text)], content: vec![Content::Text(text)],
annotations: Default::default(),
}, },
stop_reason: StopReason::EndTurn, stop_reason: StopReason::EndTurn,
usage: Usage::default(), usage: Usage::default(),
+1
View File
@@ -259,6 +259,7 @@ pub async fn chat_completions(
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event( if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
key.as_str(), key.as_str(),
&input.text, &input.text,
&[],
&input.images, &input.images,
)) { )) {
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()); return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
+577
View File
@@ -0,0 +1,577 @@
//! Where the claw's `bash` runs: this host's processes, or a daemon
//! speaking the sandbox protocol over HTTP.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
//! and gives the handlers a `ShellSandbox` executor over it. The tool
//! spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes `/workspace` and, when it is empty,
//! sends the host workspace as a tarball through the protocol's seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use base64::Engine as _;
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path a remote sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
const PROBE_TIMEOUT: Duration = Duration::from_secs(20);
/// Which machine runs the shell.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxKind {
/// The daemon's own host, the original path.
#[default]
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
}
impl SandboxKind {
/// The stored spelling.
pub fn as_str(self) -> &'static str {
match self {
Self::Local => "local",
Self::Http => "http",
}
}
/// Parses a stored spelling. Anything else is `None`, which every
/// caller turns into the local default.
pub fn parse(value: &str) -> Option<Self> {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
_ => None,
}
}
}
/// One sandbox choice: the kind and whatever it needs. `local` needs
/// nothing; `http` needs a base URL and may carry a token.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct SandboxChoice {
/// The machine kind.
pub kind: SandboxKind,
/// The `http` sandbox's base URL, no trailing slash after
/// normalization.
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
impl SandboxChoice {
/// Trims the strings, drops blank ones, and validates what `http`
/// needs to run. A choice that fails reads as a 400 at the route,
/// never as a silent fallback.
pub fn normalized(mut self) -> Result<Self, SandboxError> {
self.url = self
.url
.map(|url| url.trim().trim_end_matches('/').to_owned())
.filter(|url| !url.is_empty());
self.token = self
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
if self.kind == SandboxKind::Http {
let url = self
.url
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the http sandbox needs a url".to_owned()))?;
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err(SandboxError::Invalid(
"the http sandbox url must start with http:// or https://".to_owned(),
));
}
}
Ok(self)
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind == SandboxKind::Http
}
}
/// Why a sandbox choice or operation failed.
#[derive(Debug, thiserror::Error)]
pub enum SandboxError {
/// The choice cannot run as written.
#[error("{0}")]
Invalid(String),
/// The settings table failed.
#[error("sandbox store failed: {0}")]
Store(String),
}
/// The chosen sandbox and the executors built over it, shared by every
/// handler so a switch takes effect on the next turn without a restart.
pub struct SandboxState {
choice: RwLock<SandboxChoice>,
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
}
impl SandboxState {
/// The state over `settings`, seeded by `seed` when no choice was
/// stored. `local_workspace` is the chat workspace the settings
/// surface reports; `shell_env` is layered over local commands.
pub fn load(
settings: Arc<SettingsStore>,
seed: Option<SandboxChoice>,
local_workspace: PathBuf,
shell_env: &BTreeMap<String, String>,
) -> Result<Self, SandboxError> {
let stored = settings
.get(SANDBOX_KEY)
.map_err(|err| SandboxError::Store(err.to_string()))?;
let choice = stored
.as_deref()
.and_then(|raw| serde_json::from_str::<SandboxChoice>(raw).ok())
.and_then(|choice| choice.normalized().ok())
.or_else(|| seed.and_then(|choice| choice.normalized().ok()))
.unwrap_or_default();
Ok(Self {
choice: RwLock::new(choice),
settings,
local_workspace,
local: default_executor_with(shell_env),
remote: Mutex::new(HashMap::new()),
})
}
/// The current choice.
pub fn choice(&self) -> SandboxChoice {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.is_remote()
}
/// Saves and applies a choice. The next turn reads it; nothing is
/// rebuilt in place. Answers the normalized choice that was stored.
pub fn set(&self, choice: SandboxChoice) -> Result<SandboxChoice, SandboxError> {
let choice = choice.normalized()?;
let raw =
serde_json::to_string(&choice).map_err(|err| SandboxError::Store(err.to_string()))?;
self.settings
.set(SANDBOX_KEY, &raw)
.map_err(|err| SandboxError::Store(err.to_string()))?;
*self.choice.write().unwrap_or_else(PoisonError::into_inner) = choice.clone();
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
Ok(choice)
}
/// The workspace a handler should name and start commands in: the
/// host path locally, `/workspace` on a remote sandbox.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
if self.is_remote() {
PathBuf::from(REMOTE_WORKSPACE)
} else {
host.to_path_buf()
}
}
/// The chat workspace under the current choice, for the settings
/// surface.
pub fn workspace(&self) -> PathBuf {
self.workspace_for(&self.local_workspace)
}
/// The host workspace path, whatever the current choice.
pub fn local_workspace(&self) -> &Path {
&self.local_workspace
}
/// An executor for one host workspace. Remote sessions are derived
/// from the workspace path, so two workspaces never share a root.
pub fn executor(
self: &Arc<Self>,
host_workspace: impl Into<PathBuf>,
) -> Arc<dyn ShellExecutor> {
Arc::new(ClawShell {
state: Arc::clone(self),
host_workspace: host_workspace.into(),
local: self.local.clone(),
seeded: AtomicBool::new(false),
last: Mutex::new(None),
})
}
/// The cached HTTP client for one session. The map is cleared
/// whenever the choice changes, so a new URL or token builds a new
/// client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<HttpSandbox>, ShellError> {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(sandbox) = remote.get(&session) {
return Ok(sandbox.clone());
}
}
let token = choice.token.as_deref().unwrap_or("");
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(session, sandbox.clone());
Ok(sandbox)
}
}
/// One handler's view of the choice: local commands go straight to the
/// host executor; remote commands go through the sandbox, seeded from
/// the host workspace once per choice.
struct ClawShell {
state: Arc<SandboxState>,
host_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
seeded: AtomicBool,
last: Mutex<Option<SandboxChoice>>,
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty `/workspace` gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox.
async fn seed(
&self,
sandbox: &Arc<HttpSandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let mut sink = |_line: &str| {};
let probe = sandbox
.exec(
ExecRequest {
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
cwd: REMOTE_WORKSPACE.to_owned(),
timeout: PROBE_TIMEOUT,
},
cancelled,
&mut sink,
)
.await
.map_err(protocol_error)?;
if !probe.stdout.is_empty() {
return Ok(());
}
let root = self.host_workspace.clone();
let archive = tokio::task::spawn_blocking(move || tarball(&root))
.await
.map_err(|err| {
ShellError::Failed(format!("the workspace archive task failed: {err}"))
})??;
let Some(tar_gz_base64) = archive else {
return Ok(());
};
sandbox
.seed(&WorkspaceSeed::Tarball {
name: "workspace.tar.gz".to_owned(),
tar_gz_base64,
})
.await
.map_err(protocol_error)?;
Ok(())
}
}
#[async_trait]
impl ShellExecutor for ClawShell {
async fn run(
&self,
command: &str,
cwd: &Path,
timeout: Duration,
cancelled: &AtomicBool,
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
) -> Result<Executed, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self
.local
.run(command, cwd, timeout, cancelled, progress)
.await;
}
{
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
if last.as_ref() != Some(&choice) {
*last = Some(choice.clone());
self.seeded.store(false, Ordering::Relaxed);
}
}
let sandbox = self.state.remote_sandbox(&choice, &self.host_workspace)?;
if !self.seeded.load(Ordering::Relaxed) {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let sandbox: Arc<dyn Sandbox> = sandbox;
ShellSandbox::new(sandbox)
.run(
command,
Path::new(REMOTE_WORKSPACE),
timeout,
cancelled,
progress,
)
.await
}
}
/// Maps a protocol failure onto the shell error the tool shapes into an
/// `is_error` result.
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still
// a failure, reported in-band with its own text.
_ => ShellError::Failed(err.to_string()),
}
}
/// The sandbox session name for one host workspace: a stable FNV-1a
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
fn session_name(host: &Path) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in host.to_string_lossy().as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("rhema-claw-{hash:016x}")
}
/// One host workspace as a gzipped tar, base64 for the protocol.
/// `None` when the directory is missing or empty: nothing to seed.
fn tarball(root: &Path) -> Result<Option<String>, ShellError> {
if !root.is_dir() {
return Ok(None);
}
let mut entries = std::fs::read_dir(root)
.map_err(|err| ShellError::Failed(format!("cannot read the workspace {root:?}: {err}")))?;
if entries.next().is_none() {
return Ok(None);
}
let output = std::process::Command::new("tar")
.arg("-czf")
.arg("-")
.arg("-C")
.arg(root)
.arg(".")
.output()
.map_err(|err| {
ShellError::Failed(format!("cannot archive the workspace with tar: {err}"))
})?;
if !output.status.success() {
let detail = String::from_utf8_lossy(&output.stderr);
let detail = detail.trim();
return Err(ShellError::Failed(if detail.is_empty() {
"tar failed to archive the workspace".to_owned()
} else {
format!("tar failed to archive the workspace: {detail}")
}));
}
Ok(Some(
base64::engine::general_purpose::STANDARD.encode(output.stdout),
))
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn state(choice: SandboxChoice) -> Arc<SandboxState> {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
Arc::new(
SandboxState::load(
settings,
Some(choice),
PathBuf::from("/state/claw/workspaces/interactive"),
&BTreeMap::new(),
)
.expect("the state loads"),
)
}
#[test]
fn a_bare_choice_is_local() {
let choice = SandboxChoice::default().normalized().unwrap();
assert_eq!(choice.kind, SandboxKind::Local);
assert!(!choice.is_remote());
assert_eq!(choice.kind.as_str(), "local");
}
#[test]
fn an_http_choice_needs_an_absolute_url() {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
token: None,
}
.normalized();
assert!(missing.is_err(), "a URL is required");
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
token: None,
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
token: None,
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
state.choice().url.as_deref(),
Some("http://box:7600"),
"the trailing slash is trimmed"
);
}
#[test]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
assert_eq!(state.choice().kind, SandboxKind::Local);
state
.set(SandboxChoice {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Http);
assert_eq!(reloaded.choice().url.as_deref(), Some("https://box:7600"));
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
// The emptiness probe: nothing at /workspace.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "",
"stderr": "",
"timed_out": false
})))
.up_to_n_times(1)
.mount(&server)
.await;
// The command itself.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "hi\n",
"stderr": "",
"timed_out": false
})))
.mount(&server)
.await;
// The seed: accepted, and the host workspace is not empty.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/seed$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"error": null
})))
.expect(1)
.mount(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("README.md"), "seed me").expect("the file writes");
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
token: None,
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = |_line: &str| {};
let executed = executor
.run(
"echo hi",
Path::new(REMOTE_WORKSPACE),
Duration::from_secs(5),
&cancelled,
&mut sink,
)
.await
.expect("the remote command answers");
assert_eq!(executed.stdout, b"hi\n");
assert_eq!(executed.code, Some(0));
}
}
+3 -1
View File
@@ -325,6 +325,7 @@ mod tests {
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new(), images: Vec::new(),
pastes: Vec::new(),
}, },
text_delta("hi"), text_delta("hi"),
], ],
@@ -348,7 +349,8 @@ mod tests {
0, 0,
TurnEvent::UserMessage { TurnEvent::UserMessage {
text: "hello".into(), text: "hello".into(),
images: Vec::new() images: Vec::new(),
pastes: Vec::new()
} }
), ),
(1, text_delta("hi")), (1, text_delta("hi")),
+14 -15
View File
@@ -9,21 +9,15 @@
#![forbid(unsafe_code)] #![forbid(unsafe_code)]
use std::sync::{Arc, OnceLock}; use std::sync::Arc;
use rhema_coding_agent::CodingAgentConfig; use rhema_host_agent::HostAgentConfig;
static WIRED: OnceLock<Option<Arc<rhema_agent_tools::vision::Wiring>>> = OnceLock::new(); /// The daemon's wiring, provisioned at first use and kept for the
/// process's life — the toolkit's own process-wide cache holds it, so
/// The daemon's wiring, established at first use and kept for the /// `None` only when provisioning failed, and a failure does not retry.
/// process's life. `None` only when provisioning failed, cached like pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
/// every answer this static gives. rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
pub(crate) fn wired() -> Option<&'static Arc<rhema_agent_tools::vision::Wiring>> {
WIRED
.get_or_init(|| {
rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV")).map(Arc::clone)
})
.as_ref()
} }
/// The init file a later provisioner chains through — `None` when the /// The init file a later provisioner chains through — `None` when the
@@ -36,7 +30,7 @@ pub(crate) fn init_path() -> Option<std::ffi::OsString> {
/// Layers the wiring onto one agent config: the shell env map (the /// Layers the wiring onto one agent config: the shell env map (the
/// init file, the binary, the staging directory) and the prompt's /// init file, the binary, the staging directory) and the prompt's
/// vision section. A frontend without wiring changes nothing. /// vision section. A frontend without wiring changes nothing.
pub(crate) fn apply(config: &mut CodingAgentConfig) { pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else { let Some(wired) = wired() else {
return; return;
}; };
@@ -52,7 +46,12 @@ mod tests {
/// values are constants, so extending twice is the same map. /// values are constants, so extending twice is the same map.
#[test] #[test]
fn apply_twice_is_apply_once() { fn apply_twice_is_apply_once() {
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp")); let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
apply(&mut config); apply(&mut config);
let once = config.shell_env.clone(); let once = config.shell_env.clone();
apply(&mut config); apply(&mut config);
+1
View File
@@ -93,6 +93,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None, tools_bin: None,
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
+1
View File
@@ -59,6 +59,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None, tools_bin: None,
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), disabled_mcp_servers: std::collections::BTreeSet::new(),
} }
} }
+193
View File
@@ -34,6 +34,7 @@ fn reply(text: &str) -> ModelOutput {
fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput { fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput {
ModelOutput { ModelOutput {
message: Message { message: Message {
annotations: Default::default(),
role: Role::Assistant, role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall { content: vec![Content::ToolCall(rhema_core::ToolCall {
id: id.to_owned(), id: id.to_owned(),
@@ -65,6 +66,7 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
tools_bin: None, tools_bin: None,
ingest_token: None, ingest_token: None,
transcript: None, transcript: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), 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 /// A turn nobody watched is still replayable: a client arriving after
/// the fact — a reloaded browser, a reopened phone — subscribes cold and /// the fact — a reloaded browser, a reopened phone — subscribes cold and
/// gets the finished turns back before the live feed. The same holds /// gets the finished turns back before the live feed. The same holds
@@ -2238,6 +2311,126 @@ async fn providers_gain_and_lose_backends_over_the_surface() {
assert_eq!(gone.status(), 400); assert_eq!(gone.status(), 400);
} }
/// The sandbox surface: the default is this host, a remote choice
/// persists across a rebuild, the token is write-only, and a choice
/// without a URL or with an unknown kind is refused.
#[tokio::test]
async fn the_sandbox_choice_is_listed_and_switchable() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let listed: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(listed["kind"], "local");
assert_eq!(listed["token_set"], false);
assert_eq!(listed["remote_workspace"], "/workspace");
assert!(
listed["workspace"]
.as_str()
.is_some_and(|path| !path.is_empty())
);
// A remote choice: the URL and token go in, the token never comes
// back.
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "http",
"url": "https://box.example:7600/",
"token": "s3cret"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "http");
assert_eq!(switched["url"], "https://box.example:7600");
assert_eq!(switched["token_set"], true);
assert_eq!(switched["workspace"], "/workspace");
assert!(
switched.get("token").is_none(),
"the token stays write-only"
);
// A remote choice without a URL is a 400, and an unknown kind too.
let missing = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "http", "url": ""}))
.send()
.await
.expect("the refusal posts");
assert_eq!(missing.status(), 400);
let unknown = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "quantum"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(unknown.status(), 400);
// Back to this host: the remote fields stay staged for the next
// switch, and the workspace path flips with the choice.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["token_set"], true);
// The persisted choice wins after a restart.
drop(base);
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon rebuilds");
let base = serve(&daemon).await;
let reloaded: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(reloaded["kind"], "local");
assert_eq!(reloaded["token_set"], true);
// `clear_token` drops the stored secret without moving the URL.
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local", "clear_token": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["token_set"], false);
assert_eq!(cleared["url"], "https://box.example:7600");
}
/// The agent identity surface: the text fields round-trip with /// The agent identity surface: the text fields round-trip with
/// partial-save semantics (an absent field is left alone, an empty one /// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type, /// clears), the avatar uploads and serves back with its content type,
+1
View File
@@ -66,6 +66,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None, tools_bin: None,
transcript: None, transcript: None,
ingest_token: None, ingest_token: None,
sandbox: None,
disabled_mcp_servers: std::collections::BTreeSet::new(), 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 # bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces. # out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \ && apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name. # Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+1 -1
View File
@@ -67,7 +67,7 @@ FROM debian:stable-slim
# load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need # load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
# neither). # neither).
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends bash git ca-certificates \ && apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name. # Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+2 -2
View File
@@ -3,5 +3,5 @@ name: rhema-claw
description: "The resident forge-watching agent daemon: forge watches and a description: "The resident forge-watching agent daemon: forge watches and a
chat HTTP surface over one SQLite store." chat HTTP surface over one SQLite store."
type: application type: application
version: 0.1.0 version: 0.4.0
appVersion: "0.1.0" appVersion: "0.4.0"
@@ -15,10 +15,10 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] } rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped # The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's # like the task scheduler's
rhema-autonomous-agent = "0.2.3" rhema-autonomous-agent = "0.4.0"
# The reminder source ingests its slots into a `Dispatcher`; the event # The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's # and key-function shapes are the dispatcher's
rhema-rsd = "0.2.3" rhema-rsd = "0.4.0"
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
@@ -13,7 +13,7 @@ publish = false
[dependencies] [dependencies]
# The dispatch seam: watches ingest into a Dispatcher # The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = "0.2.3" rhema-rsd = "0.4.0"
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
@@ -287,7 +287,9 @@ struct WireComment {
/// One row of the account notifications feed. /// One row of the account notifications feed.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
struct WireNotification { struct WireNotification {
#[serde(default)] /// GitHub sends this one as a JSON string, unlike every other id in
/// this adapter; see [`lenient_id`].
#[serde(default, deserialize_with = "lenient_id")]
id: Option<i64>, id: Option<i64>,
#[serde(default)] #[serde(default)]
reason: Option<String>, reason: Option<String>,
@@ -452,6 +454,32 @@ fn parent_number(url: &str) -> Option<u64> {
url.trim_end_matches('/').rsplit('/').next()?.parse().ok() url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
} }
/// An id that arrives as either a JSON number or a JSON string.
///
/// GitHub's notifications feed is the odd one out: `id` there is a
/// string (`"27210544329"`), while issues, comments and reviews send
/// numbers. One row that refuses to decode fails the whole page, so the
/// notification id is read leniently.
fn lenient_id<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum IdWire {
Number(i64),
Text(String),
}
match Option::<IdWire>::deserialize(deserializer)? {
None => Ok(None),
Some(IdWire::Number(n)) => Ok(Some(n)),
Some(IdWire::Text(text)) => text.trim().parse().map(Some).map_err(|_| {
serde::de::Error::custom(format!("notification id is not a number: {text}"))
}),
}
}
/// The notification a notifications row carries. GitHub's `reason` field /// The notification a notifications row carries. GitHub's `reason` field
/// is the row's whole why; the subject's API URL yields the thread. /// is the row's whole why; the subject's API URL yields the thread.
fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> { fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> {
@@ -870,4 +898,61 @@ mod tests {
assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3"); assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3");
assert!(event.raw.get("title").is_none()); assert!(event.raw.get("title").is_none());
} }
fn notification(json: &str) -> WireNotification {
serde_json::from_str(json).expect("notification fixture parses")
}
// Captured from the live feed on 2026-11-21: `id` there is a string,
// and one such row used to fail the whole page's decode.
#[test]
fn a_notification_id_sent_as_a_string_decodes() {
let row = notification(
r#"{"id": "27210544329", "unread": true, "reason": "mention",
"updated_at": "2026-11-21T22:33:00Z", "last_read_at": null,
"subject": {"title": "Snap build failed for v2.5.1",
"url": "https://api.github.com/repos/acme/widgets/issues/10",
"latest_comment_url": "https://api.github.com/repos/acme/widgets/issues/comments/7070",
"type": "Issue"},
"repository": {"id": 1239653662, "full_name": "acme/widgets"},
"url": "https://api.github.com/notifications/threads/27210544329"}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 10);
assert_eq!(notification.repo, RepoRef::new("acme", "widgets"));
assert_eq!(notification.reason, NotificationReason::Mention);
assert!(!notification.is_pr);
assert_eq!(
notification.id,
"github:notification:27210544329@2026-11-21T22:33:00Z"
);
}
#[test]
fn a_notification_id_sent_as_a_number_still_decodes() {
let row = notification(
r#"{"id": 42188, "reason": "review_requested",
"updated_at": "2026-10-08T12:00:00Z",
"subject": {"title": "tidy the parser", "type": "PullRequest",
"url": "https://api.github.com/repos/acme/widgets/pulls/8"},
"repository": {"full_name": "acme/widgets"}}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 8);
assert!(notification.is_pr);
assert_eq!(
notification.id,
"github:notification:42188@2026-10-08T12:00:00Z"
);
}
#[test]
fn a_notification_id_that_is_not_a_number_is_a_parse_error() {
let err = serde_json::from_str::<WireNotification>(r#"{"id": "not-a-number"}"#)
.expect_err("a junk id is loud, not silently dropped");
assert!(err.to_string().contains("not-a-number"), "got: {err}");
}
} }
+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 ## What the transcript does with the stream
- **Replies, asks and files only.** The stream carries tool calls and
the model's thinking trace; this surface drops both and renders the
reply. A consent card and an attachment card still appear inline,
because the reader has to answer or open them. The mirror still
folds those other events; only the render ignores them.
- **Long pastes travel as chips.** A paste over three lines (the TUI's - **Long pastes travel as chips.** A paste over three lines (the TUI's
`PASTE_INLINE_LINES`) never lands in the composer; it stages as a `PASTE_INLINE_LINES`) never lands in the composer; it stages as a
droppable chip (`▣1 42L`) and embeds into the sent text as droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s the plain draft — the claw composes the record (the payload in
`paste::embed` keeps — so the transcript renders each embed back as place, the span note beside it) — so no mark ever crosses the wire.
a chip in place of the payload. An unpaired mark is literal text. The `user_message` echo names each chip as the byte span it stands
for (the session record's own shape, `paste::PasteSpan`), and the
transcript renders from that. Rows recorded before spans rode the
stream carry the legacy mark form in the text instead; the render
still scans for those, and an unpaired mark stays literal.
- **The agent can ask.** A `consent_request` event renders as an - **The agent can ask.** A `consent_request` event renders as an
inline card: kind `secret` gets a password input plus submit, kind inline card: kind `secret` gets a password input plus submit, kind
`phone` gets Approve/Deny, and both carry a deny link `phone` gets Approve/Deny, and both carry a deny link
@@ -175,10 +184,10 @@ app/
raw HTML escaped, styles in main.css .md) raw HTML escaped, styles in main.css .md)
ClawBanner.vue the one error/notice banner surface ClawBanner.vue the one error/notice banner surface
ChatPanel.vue transcript: sent lines (paste chips), ChatPanel.vue transcript: sent lines (paste chips),
streamed turns as bash shell lines and streamed turns as reply text plus
glyph rows, consent + attachment consent + attachment cards; the growing
cards; the growing composer; agent composer; agent replies render through
replies render through AppMarkdown AppMarkdown
SessionsSidebar.vue conversable dispatch keys (phone status SessionsSidebar.vue conversable dispatch keys (phone status
keys hidden), interactive first; the keys hidden), interactive first; the
+ form creates a session + form creates a session
@@ -193,7 +202,8 @@ app/
composables/ composables/
useClaw.ts the typed API client + fetch-based SSE useClaw.ts the typed API client + fetch-based SSE
useTranscript.ts folds TurnEvents into renderable turn useTranscript.ts folds TurnEvents into renderable turn
blocks; owns the paste-embed text form blocks; owns the paste span record (and
the legacy mark form old rows carry)
server/ server/
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
``` ```
+55 -8
View File
@@ -17,9 +17,11 @@ import type {
NewAccount, NewAccount,
ProviderCredentials, ProviderCredentials,
ProvidersState, ProvidersState,
SandboxSelection,
SandboxState,
StreamStatus, StreamStatus,
} from '~/composables/useClaw' } from '~/composables/useClaw'
import { useTranscript } from '~/composables/useTranscript' import { composeChips, useTranscript } from '~/composables/useTranscript'
import type { StagedImage } from '~/composables/useTranscript' import type { StagedImage } from '~/composables/useTranscript'
const TOKEN_STORE_KEY = 'claw.token' 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: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] },
{ label: 'System', entries: [{ id: 'about', label: 'About' }] }, {
label: 'System',
entries: [
{ id: 'sandbox', label: 'Sandbox' },
{ id: 'about', label: 'About' },
],
},
] ]
function parseHash(): Route { function parseHash(): Route {
@@ -265,6 +273,8 @@ const mutatingIdentity = ref(false)
const accounts = ref<ClawAccount[] | null>(null) const accounts = ref<ClawAccount[] | null>(null)
const accountsLoading = ref(false) const accountsLoading = ref(false)
const mutatingAccounts = ref(false) const mutatingAccounts = ref(false)
const sandboxState = ref<SandboxState | null>(null)
const savingSandbox = ref(false)
const streamStatus = ref<StreamStatus>('connecting') const streamStatus = ref<StreamStatus>('connecting')
const busy = ref(false) const busy = ref(false)
const authRequired = ref(false) const authRequired = ref(false)
@@ -499,21 +509,50 @@ async function removeProvider(id: string): Promise<void> {
} }
} }
async function send(message: { text: string; images: StagedImage[] }): Promise<void> { async function refreshSandbox(): Promise<void> {
// The optimistic row renders the staged previews; the stream's try {
// user_message echo carries the stored ids and dedupes against it. sandboxState.value = await claw.sandbox()
apiError.value = null
} catch (err) {
noteApiError(err)
}
}
async function saveSandbox(choice: SandboxSelection): Promise<void> {
savingSandbox.value = true
try {
sandboxState.value = await claw.setSandbox(choice)
pushNotice(
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine',
)
apiError.value = null
} catch (err) {
noteApiError(err)
} finally {
savingSandbox.value = false
}
}
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews and the composed
// chip record — the same plain text and spans the fold records on
// the other side — so the stream's user_message echo, which
// carries the stored ids beside that record, dedupes against it.
const composed = composeChips(message.text, message.pastes)
const rowId = transcript.addSent( const rowId = transcript.addSent(
message.text, composed.text,
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })), message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
composed.pastes,
) )
busy.value = true busy.value = true
try { try {
// Fire-and-forget by design: the claw answers 202 and the reply // Fire-and-forget by design: the claw answers 202 and the reply
// arrives on the event stream. The body carries the images only // arrives on the event stream. The chips and the images ride the
// when there are some. // body only when there are some.
await claw.sendMessage( await claw.sendMessage(
activeKey.value, activeKey.value,
message.text, message.text,
message.pastes,
message.images.map(({ media_type, data }) => ({ media_type, data })), message.images.map(({ media_type, data }) => ({ media_type, data })),
) )
apiError.value = null apiError.value = null
@@ -581,6 +620,7 @@ function saveToken(): void {
void refreshSessions() void refreshSessions()
void refreshIdentity() void refreshIdentity()
void refreshAccounts() void refreshAccounts()
void refreshSandbox()
} }
// --- the one live subscription --------------------------------------- // --- the one live subscription ---------------------------------------
@@ -657,6 +697,7 @@ onMounted(() => {
void refreshIdentity() void refreshIdentity()
void refreshProviders() void refreshProviders()
void refreshAccounts() void refreshAccounts()
void refreshSandbox()
void refreshSessions() void refreshSessions()
healthTimer = setInterval(checkHealth, 30000) healthTimer = setInterval(checkHealth, 30000)
sessionsTimer = setInterval(() => void refreshSessions(), 20000) sessionsTimer = setInterval(() => void refreshSessions(), 20000)
@@ -789,6 +830,12 @@ onUnmounted(() => {
@add="addProvider" @add="addProvider"
@remove="removeProvider" @remove="removeProvider"
/> />
<SettingsSandboxPage
v-show="route.section === 'sandbox'"
:state="sandboxState"
:saving="savingSandbox"
@save="saveSandbox"
/>
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" /> <SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
</template> </template>
</main> </main>
+34 -19
View File
@@ -10,12 +10,14 @@
import { import {
PASTE_INLINE_LINES, PASTE_INLINE_LINES,
chipLabel, chipLabel,
embedPastes, byteToIndex,
chipLinesLabel,
lineCount, lineCount,
normalizePaste, normalizePaste,
pasteParts, pasteParts,
} from '~/composables/useTranscript' } from '~/composables/useTranscript'
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw' import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
import type { PasteSpan } from '~/composables/useClaw'
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript' import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
const props = defineProps<{ const props = defineProps<{
@@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
* the staged images, previews included for the optimistic row. */ * the staged images, previews included for the optimistic row. */
interface SendPayload { interface SendPayload {
text: string text: string
/** The chip payloads, in staging order — the wire carries them
* beside the plain draft; the fold composes the record. */
pastes: string[]
images: StagedImage[] images: StagedImage[]
} }
@@ -136,20 +141,12 @@ watch(
}, },
) )
// Thinking grows inside the trailing entry without changing the // A consent or attachment card opening inside the trailing turn
// entries length, so its total length joins the watch to keep the // changes the rendered height, so the reply length and the entries
// stream pinned at the bottom. // length both join the watch that keeps the stream pinned at the
function liveThinkingLength(): number { // bottom.
return (
props.live?.entries.reduce(
(count, entry) => (entry.kind === 'thinking' ? count + entry.text.length : count),
0,
) ?? 0
)
}
watch( watch(
() => [props.items.length, props.live?.reply.length, liveThinkingLength(), props.live?.entries.length], () => [props.items.length, props.live?.reply.length, props.live?.entries.length],
async () => { async () => {
if (!pinned.value) return if (!pinned.value) return
await nextTick() await nextTick()
@@ -165,7 +162,7 @@ function submit(): void {
// answers 202 at once) — a running turn never blocks the composer, // answers 202 at once) — a running turn never blocks the composer,
// because a send into one steers it. // because a send into one steers it.
if (!text || !props.canSend || props.busy) return if (!text || !props.canSend || props.busy) return
emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value }) emit('send', { text, pastes: pastes.value, images: stagedImages.value })
stageGeneration++ stageGeneration++
draft.value = '' draft.value = ''
pastes.value = [] pastes.value = []
@@ -367,8 +364,12 @@ function storedImageName(image: SentImage): string {
type MessageSegment = PastePart | { kind: 'chip'; label: string } type MessageSegment = PastePart | { kind: 'chip'; label: string }
/** The message's render pieces: literal text and resolved chips, the /** The message's render pieces: literal text and resolved chips, the
* chips' one-based ids counted across the message. */ * chips' one-based ids counted across the message. The chips come
function messageSegments(text: string): MessageSegment[] { * from the row's span record — the plain text sliced at the spans'
* byte boundaries — and a row from before spans rode the wire
* carries none; that one still scans the mark form in its text. */
function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] {
if (pastes.length === 0) {
const segments: MessageSegment[] = [] const segments: MessageSegment[] = []
let chip = 0 let chip = 0
for (const part of pasteParts(text)) { for (const part of pasteParts(text)) {
@@ -379,6 +380,21 @@ function messageSegments(text: string): MessageSegment[] {
} }
} }
return segments 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:/, '')) const displayName = computed(() => props.activeKey.replace(/^interactive:/, ''))
@@ -453,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
</button> </button>
</div> </div>
<div class="reply plain"> <div class="reply plain">
<template v-for="(segment, index) in messageSegments(item.text)" :key="index"> <template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span> <span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
<template v-else>{{ segment.text }}</template> <template v-else>{{ segment.text }}</template>
</template> </template>
@@ -498,7 +514,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="who">{{ agentName }}</div> <div class="who">{{ agentName }}</div>
<TurnEntries <TurnEntries
:entries="live.entries" :entries="live.entries"
:open-thinking="true"
@consent-answer="(id, answer) => emit('consentAnswer', id, answer)" @consent-answer="(id, answer) => emit('consentAnswer', id, answer)"
@consent-deny="(id) => emit('consentDeny', id)" @consent-deny="(id) => emit('consentDeny', id)"
@download-attachment="(id, name) => emit('downloadAttachment', id, name)" @download-attachment="(id, name) => emit('downloadAttachment', id, name)"
+16 -39
View File
@@ -1,17 +1,22 @@
<script setup lang="ts"> <script setup lang="ts">
// A turn's stream-ordered middle: tool rows, pieces of the thinking // The turn's middle, as the web surface shows it: the agent's asks
// trace, the agent's asks, its handovers — each at the position the // (consent cards) and its handovers (attachment cards), each at the
// stream delivered it, so an ask sits at the tool call that raised it // position the stream delivered it. Tool calls and the thinking trace
// and thinking sits between the calls it precedes. // stay off this surface; the reply is what it shows, and these two
// cards are the only things the reader must act on or can open.
import { computed } from 'vue'
import type { TurnEntry } from '~/composables/useTranscript' import type { TurnEntry } from '~/composables/useTranscript'
import type { ConsentAnswer } from '~/composables/useClaw' import type { ConsentAnswer } from '~/composables/useClaw'
defineProps<{ const props = defineProps<{
entries: TurnEntry[] entries: TurnEntry[]
/** A live turn's thinking blocks start expanded; finished ones collapse. */
openThinking?: boolean
}>() }>()
/** Cards only: a turn's tool rows and thinking blocks never render. */
const cards = computed(() =>
props.entries.filter((entry) => entry.kind === 'consent' || entry.kind === 'attachment'),
)
const emit = defineEmits<{ const emit = defineEmits<{
consentAnswer: [id: string, answer: ConsentAnswer] consentAnswer: [id: string, answer: ConsentAnswer]
consentDeny: [id: string] consentDeny: [id: string]
@@ -20,21 +25,16 @@ const emit = defineEmits<{
</script> </script>
<template> <template>
<div v-if="entries.length > 0" class="entries"> <div v-if="cards.length > 0" class="entries">
<template v-for="(entry, index) in entries" :key="index"> <template v-for="(entry, index) in cards" :key="index">
<TurnToolRow v-if="entry.kind === 'tool'" :row="entry.row" />
<details v-else-if="entry.kind === 'thinking'" class="thinking" :open="openThinking">
<summary>thinking</summary>
<pre>{{ entry.text }}</pre>
</details>
<TurnConsentCard <TurnConsentCard
v-else-if="entry.kind === 'consent'" v-if="entry.kind === 'consent'"
:consent="entry.consent" :consent="entry.consent"
@answer="(id, answer) => emit('consentAnswer', id, answer)" @answer="(id, answer) => emit('consentAnswer', id, answer)"
@deny="(id) => emit('consentDeny', id)" @deny="(id) => emit('consentDeny', id)"
/> />
<TurnAttachmentCard <TurnAttachmentCard
v-else v-else-if="entry.kind === 'attachment'"
:attachment="entry.attachment" :attachment="entry.attachment"
@download="(id, name) => emit('downloadAttachment', id, name)" @download="(id, name) => emit('downloadAttachment', id, name)"
/> />
@@ -49,27 +49,4 @@ const emit = defineEmits<{
gap: 4px; gap: 4px;
margin-bottom: 10px; margin-bottom: 10px;
} }
.thinking {
color: var(--text3);
}
.thinking summary {
cursor: pointer;
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.thinking pre {
margin: 6px 0 0;
padding: 8px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text3);
font-style: italic;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style> </style>
-102
View File
@@ -1,102 +0,0 @@
<script setup lang="ts">
// One tool call in a turn: running, completed, or failed — shell lines
// for bash (the TUI's tool_row), glyph rows for everything else.
import type { ToolRow } from '~/composables/useTranscript'
defineProps<{ row: ToolRow }>()
/** Command rows render as shell lines, not glyph rows; run_command is
* the bash tool's other name. */
function isShellTool(name: string): boolean {
return name === 'bash' || name === 'run_command'
}
</script>
<template>
<div class="tool-row" :class="{ error: row.isError === true }">
<template v-if="isShellTool(row.name)">
<span class="shell-mark" aria-hidden="true">$ </span>
<span class="shell-command mono">{{ row.command ?? '…' }}</span>
<span
v-if="typeof row.code === 'number'"
class="shell-code mono"
:class="row.code === 0 ? 'ok' : 'failed'"
>[{{ row.code }}]</span>
<span v-else-if="row.isError === true" class="shell-code failed">✗</span>
</template>
<template v-else>
<span class="glyph" aria-hidden="true">{{
row.isError === null ? '…' : row.isError ? '✗' : '✓'
}}</span>
<span class="name mono">{{ row.name }}</span>
<span v-if="row.summary" class="summary mono">{{ row.summary }}</span>
</template>
</div>
</template>
<style scoped>
.tool-row {
display: flex;
gap: 8px;
align-items: baseline;
padding: 5px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-left: 3px solid var(--ok);
border-radius: 6px;
}
.tool-row.error {
border-left-color: var(--error);
}
.glyph {
flex: none;
color: var(--ok);
}
.tool-row.error .glyph {
color: var(--error);
}
.name {
color: var(--text);
}
.summary {
color: var(--text3);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A bash row reads as the shell line it ran: dim $ prefix, the
command, and the exit code pushed to the row's right end. */
.shell-mark {
flex: none;
color: var(--text3);
white-space: pre;
}
.shell-command {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text);
}
.shell-code {
flex: none;
font-size: 11px;
}
.shell-code.ok {
color: var(--ok);
}
.shell-code.failed {
color: var(--error);
}
</style>
@@ -0,0 +1,259 @@
<script setup lang="ts">
// The Sandbox page: where the agent's `bash` runs. The choice saves as
// a whole; the token is write-only, so an empty field keeps whatever
// the claw already stored. Presentational: data flows in as props,
// intent flows up as events.
import type { SandboxKind, SandboxSelection, SandboxState } from '~/composables/useClaw'
const props = defineProps<{
state: SandboxState | null
saving: boolean
}>()
const emit = defineEmits<{
save: [choice: SandboxSelection]
}>()
const kind = ref<SandboxKind>('local')
const url = ref('')
const token = ref('')
const clearToken = ref(false)
const dirty = computed(() => {
const state = props.state
if (!state) return false
if (kind.value !== state.kind) return true
if (kind.value !== 'http') return false
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const ready = computed(() => kind.value !== 'http' || urlValid.value)
const urlHint = computed(() =>
url.value.trim() && !urlValid.value
? 'The URL must start with http:// or https://.'
: 'The sandboxd base URL, for example https://box.example:7600.',
)
function sync(): void {
const state = props.state
if (!state) return
kind.value = state.kind
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
}
watch(
() => props.state,
(state) => {
if (state) sync()
},
{ immediate: true },
)
function discard(): void {
sync()
}
function save(): void {
if (!dirty.value || props.saving || !ready.value) return
const choice: SandboxSelection = { kind: kind.value }
if (kind.value === 'http') {
choice.url = url.value.trim()
if (token.value.trim() !== '') {
choice.token = token.value.trim()
} else if (clearToken.value) {
choice.clear_token = true
}
}
emit('save', choice)
}
// The path the staged choice would use, not the saved one.
const workspacePath = computed(() => {
const state = props.state
if (!state) return ''
return kind.value === 'http' ? state.remote_workspace : state.local_workspace
})
</script>
<template>
<div class="page">
<PageHeader title="Sandbox" subtitle="Where the agent's bash runs.">
<template #actions>
<button :disabled="!dirty || saving" @click="discard">Discard</button>
<button class="primary" :disabled="!dirty || saving || !ready" @click="save">
{{ saving ? 'Saving…' : 'Save' }}
</button>
</template>
</PageHeader>
<div class="scroll">
<p v-if="!state" class="muted">loading sandbox…</p>
<template v-else>
<SettingCard title="Execution" meta="applies on the next turn">
<label class="option" :class="{ selected: kind === 'local' }">
<input v-model="kind" type="radio" value="local" :disabled="saving" />
<span class="option-text">
<span class="option-title">
This machine
<span v-if="state.kind === 'local'" class="current">current</span>
</span>
<span class="option-detail">
Commands run as processes on the daemon's host.
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'http' }">
<input v-model="kind" type="radio" value="http" :disabled="saving" />
<span class="option-text">
<span class="option-title">
Remote sandbox
<span v-if="state.kind === 'http'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a host that speaks the sandbox protocol over HTTP.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
<SettingRow
title="URL"
:description="urlHint"
>
<input
v-model="url"
type="text"
class="mono"
placeholder="https://box.example:7600"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Token"
:description="state.token_set
? 'A token is stored. Leave this blank to keep it.'
: 'The shared secret the daemon checks. Leave it blank when the daemon has none.'"
>
<input
v-model="token"
type="password"
:placeholder="state.token_set ? 'stored' : 'optional'"
autocomplete="off"
:disabled="saving || clearToken"
/>
</SettingRow>
<SettingRow
v-if="state.token_set"
title="Stored token"
:description="clearToken
? 'The stored token is removed when you save.'
: 'The token stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearToken = !clearToken">
{{ clearToken ? 'Keep token' : 'Forget token' }}
</button>
</SettingRow>
</SettingCard>
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy">
On first use the claw sends the local workspace to the sandbox as a tarball.
Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout>
<SettingCard title="Workspace">
<SettingRow
title="Path"
description="Where the agent's bash starts under this choice."
>
<code>{{ workspacePath }}</code>
</SettingRow>
</SettingCard>
</template>
</div>
</div>
</template>
<style scoped>
.page {
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
flex: 1;
}
.scroll {
flex: 1;
overflow-y: auto;
padding: 0 24px 24px;
display: flex;
flex-direction: column;
gap: 16px;
max-width: 860px;
}
.muted {
color: var(--text3);
padding: 8px 2px;
}
.option {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 13px 16px;
cursor: pointer;
}
.option:hover {
background: var(--elevated);
}
.option.selected {
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
}
.option input[type='radio'] {
flex: none;
margin: 3px 0 0;
accent-color: var(--accent);
}
.option-text {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
.option-title {
display: flex;
align-items: baseline;
gap: 8px;
color: var(--text);
font-weight: 600;
}
.option-detail {
color: var(--text3);
font-size: 12.5px;
}
.current {
color: var(--accent-text);
font-size: 12px;
font-weight: 500;
}
</style>
+130 -9
View File
@@ -56,9 +56,20 @@ export interface UserImage {
media_type: string media_type: string
} }
/** One paste chip a `user_message` carries: the record the session's
* `rhema-code` annotation holds — the byte range in the plain text the
* chip stands for (UTF-8 offsets; see useTranscript's
* `byteToIndex`), plus the payload's line count for the chip's label
* (rhema-core `PasteSpan`). */
export interface PasteSpan {
start: number
end: number
lines: number
}
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */ /** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
export type TurnEvent = export type TurnEvent =
| { type: 'user_message'; text: string; images: UserImage[] } | { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
| { type: 'thinking_delta'; text: string } | { type: 'thinking_delta'; text: string }
| { type: 'text_delta'; text: string } | { type: 'text_delta'; text: string }
| { type: 'tool_start'; name: string } | { type: 'tool_start'; name: string }
@@ -220,6 +231,34 @@ export interface ActiveBackend {
active: { provider: string; model: string } active: { provider: string; model: string }
} }
/** Where the agent's `bash` runs: this host or a daemon speaking the
* sandbox protocol over HTTP. */
export type SandboxKind = 'local' | 'http'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */
export interface SandboxState {
kind: SandboxKind
url: string | null
token_set: boolean
/** Where `bash` starts under the current choice. */
workspace: string
/** The daemon's chat workspace, whatever the choice. */
local_workspace: string
/** The path a remote sandbox exposes. */
remote_workspace: string
}
/** The body `PUT /v1/sandbox` takes. `token` is write-only, and
* `clear_token` drops the stored one. An omitted `url` keeps the
* current one. */
export interface SandboxSelection {
kind: SandboxKind
url?: string
token?: string
clear_token?: boolean
}
/** A failed API call: the status plus the claw's `error` string when it sent one. */ /** A failed API call: the status plus the claw's `error` string when it sent one. */
export class ClawError extends Error { export class ClawError extends Error {
/** HTTP status; 0 when the claw was unreachable at all. */ /** HTTP status; 0 when the claw was unreachable at all. */
@@ -240,7 +279,9 @@ const INTERACTIVE_PREFIX = 'interactive:'
* connection and reconnects: the claw sends a keep-alive comment every * connection and reconnects: the claw sends a keep-alive comment every
* fifteen seconds (hub.rs), so three missed ones means the path is * fifteen seconds (hub.rs), so three missed ones means the path is
* black-holed — a half-open TCP after a laptop sleep shows the same * black-holed — a half-open TCP after a laptop sleep shows the same
* 'live' badge a healthy stream does without this check. */ * 'live' badge a healthy stream does without this check. The watchdog
* is paused while the tab is hidden: browsers throttle timers and can
* stall the reader there, and a tab switch is not a dead stream. */
const STREAM_SILENCE_TIMEOUT_MS = 45000 const STREAM_SILENCE_TIMEOUT_MS = 45000
/** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */ /** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */
@@ -368,8 +409,8 @@ export interface ClawApi {
* a plain src will not do). Cached per id: attachments are immutable, * a plain src will not do). Cached per id: attachments are immutable,
* so a replayed event never refetches. */ * so a replayed event never refetches. */
attachmentUrl(id: string): Promise<string> attachmentUrl(id: string): Promise<string>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */ /** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
/** `GET /v1/providers` — the constructible backends and the active pair. */ /** `GET /v1/providers` — the constructible backends and the active pair. */
providers(): Promise<ProvidersState> providers(): Promise<ProvidersState>
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */ /** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
@@ -383,6 +424,11 @@ export interface ClawApi {
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers /** `DELETE /v1/providers/{id}` — remove a backend instance; answers
* the new providers state. The last backend is refused claw-side. */ * the new providers state. The last backend is refused claw-side. */
removeProvider(id: string): Promise<ProvidersState> removeProvider(id: string): Promise<ProvidersState>
/** `GET /v1/sandbox`: where the agent's `bash` runs. */
sandbox(): Promise<SandboxState>
/** `PUT /v1/sandbox`: switch the sandbox, persisted claw-side. The
* choice applies on the next turn. */
setSandbox(choice: SandboxSelection): Promise<SandboxState>
/** `GET /v1/accounts` — the stored accounts, redacted. */ /** `GET /v1/accounts` — the stored accounts, redacted. */
accounts(): Promise<ClawAccount[]> accounts(): Promise<ClawAccount[]>
/** `POST /v1/accounts` — store an account (the secret is write-only), /** `POST /v1/accounts` — store an account (the secret is write-only),
@@ -498,11 +544,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
}) })
} }
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> { async function sendMessage(
key: string,
text: string,
pastes?: string[],
images?: OutboundImage[],
): Promise<void> {
const body: { text: string; pastes?: string[]; images?: OutboundImage[] } = { text }
if (pastes?.length) body.pastes = pastes
if (images?.length) body.images = images
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, { await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) }, headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(images?.length ? { text, images } : { text }), body: JSON.stringify(body),
}) })
} }
@@ -563,6 +617,18 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})) as ProvidersState })) as ProvidersState
} }
async function sandbox(): Promise<SandboxState> {
return (await get('/v1/sandbox', token.value)) as SandboxState
}
async function setSandbox(choice: SandboxSelection): Promise<SandboxState> {
return (await send('/v1/sandbox', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(choice),
})) as SandboxState
}
async function accounts(): Promise<ClawAccount[]> { async function accounts(): Promise<ClawAccount[]> {
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] } const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
return body.accounts return body.accounts
@@ -639,11 +705,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
* notice says so instead of naming an opaque abort error. */ * notice says so instead of naming an opaque abort error. */
let timedOut = false let timedOut = false
let silence: ReturnType<typeof setTimeout> | null = null let silence: ReturnType<typeof setTimeout> | null = null
const isHidden = (): boolean =>
typeof document !== 'undefined' && document.hidden
/** Whether the attempt in flight crossed a hidden tab: a drop there
* is a backgrounded connection, not a stream the user needs a notice
* about. */
let hiddenDuringAttempt = isHidden()
const rearmSilence = (): void => { const rearmSilence = (): void => {
if (silence !== null) clearTimeout(silence) if (silence !== null) clearTimeout(silence)
silence = null
if (closed || isHidden()) return
silence = setTimeout(() => { silence = setTimeout(() => {
if (closed) return if (closed || isHidden()) return
timedOut = true timedOut = true
current?.abort() current?.abort()
}, STREAM_SILENCE_TIMEOUT_MS) }, STREAM_SILENCE_TIMEOUT_MS)
@@ -652,6 +726,23 @@ export function useClaw(token: Ref<string | null>): ClawApi {
if (silence !== null) clearTimeout(silence) if (silence !== null) clearTimeout(silence)
silence = null silence = null
} }
/** A frame or keep-alive proved this attempt alive: from here on a
* drop is real, even if the tab was hidden earlier. */
const noteActivity = (): void => {
hiddenDuringAttempt = false
rearmSilence()
}
const visibility = (): void => {
if (isHidden()) {
hiddenDuringAttempt = true
stopSilence()
return
}
if (current !== null && !current.signal.aborted) rearmSilence()
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', visibility)
}
const status = (next: StreamStatus) => { const status = (next: StreamStatus) => {
if (!closed) handlers.onStatus?.(next) if (!closed) handlers.onStatus?.(next)
@@ -663,6 +754,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const controller = new AbortController() const controller = new AbortController()
current = controller current = controller
timedOut = false timedOut = false
hiddenDuringAttempt = isHidden()
rearmSilence() rearmSilence()
try { try {
const resume = cursor === null ? '' : `?since=${cursor}` const resume = cursor === null ? '' : `?since=${cursor}`
@@ -684,7 +776,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
await readFrames( await readFrames(
response.body, response.body,
(data, id) => { (data, id) => {
rearmSilence() noteActivity()
const event = parseTurnEvent(data) const event = parseTurnEvent(data)
if (!event) return if (!event) return
const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null
@@ -694,7 +786,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
(comment) => { (comment) => {
// Keep-alives come through here too; each one proves the // Keep-alives come through here too; each one proves the
// path alive. // path alive.
rearmSilence() noteActivity()
// The record lost what this mirror holds: drop the cursor // The record lost what this mirror holds: drop the cursor
// so the next open asks for the tail, and let the consumer // so the next open asks for the tail, and let the consumer
// drop its items before the tail that already followed // drop its items before the tail that already followed
@@ -720,11 +812,16 @@ export function useClaw(token: Ref<string | null>): ClawApi {
// Backoff caps at 15s: a live stream of a running turn is the // Backoff caps at 15s: a live stream of a running turn is the
// UI's whole job, so retries stay eager but not tight-looped. // UI's whole job, so retries stay eager but not tight-looped.
const backoff = Math.min(15000, 1000 * 2 ** attempt++) const backoff = Math.min(15000, 1000 * 2 ** attempt++)
// 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?.( handlers.onNotice?.(
timedOut timedOut
? `the event stream went quiet (no keep-alive for ${STREAM_SILENCE_TIMEOUT_MS / 1000}s); reconnecting in ${backoff / 1000}s` ? `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`, : `event stream dropped (${cause instanceof Error ? cause.message : String(cause)}); retrying in ${backoff / 1000}s`,
) )
}
status('reconnecting') status('reconnecting')
await new Promise((resolve) => setTimeout(resolve, backoff)) await new Promise((resolve) => setTimeout(resolve, backoff))
} finally { } finally {
@@ -738,6 +835,9 @@ export function useClaw(token: Ref<string | null>): ClawApi {
close() { close() {
closed = true closed = true
stopSilence() stopSilence()
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', visibility)
}
current?.abort() current?.abort()
}, },
} }
@@ -757,6 +857,8 @@ export function useClaw(token: Ref<string | null>): ClawApi {
models, models,
setCredentials, setCredentials,
removeProvider, removeProvider,
sandbox,
setSandbox,
accounts, accounts,
addAccount, addAccount,
removeAccount, removeAccount,
@@ -836,6 +938,24 @@ function parseUserImages(raw: unknown): UserImage[] {
return images return images
} }
/** The paste chips a `user_message` carries: rows recorded before
* chips rode as spans carry the mark form in the text instead and no
* field at all — empty, the render falls back to scanning — and a
* span without whole-number bounds or a line count is not one. */
function parseUserPastes(raw: unknown): PasteSpan[] {
if (!Array.isArray(raw)) return []
const pastes: PasteSpan[] = []
for (const entry of raw) {
const span = entry as Record<string, unknown>
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
if (typeof span.lines !== 'number') continue
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
pastes.push({ start: span.start, end: span.end, lines: span.lines })
}
return pastes
}
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */ /** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
function parseTurnEvent(data: string): TurnEvent | null { function parseTurnEvent(data: string): TurnEvent | null {
try { try {
@@ -846,6 +966,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'user_message', type: 'user_message',
text: String(raw.text ?? ''), text: String(raw.text ?? ''),
images: parseUserImages(raw.images), images: parseUserImages(raw.images),
pastes: parseUserPastes(raw.pastes),
} }
case 'thinking_delta': case 'thinking_delta':
case 'text_delta': case 'text_delta':
+50 -16
View File
@@ -6,7 +6,7 @@
// mirror when the stream reopens and folds what arrives, never the other // mirror when the stream reopens and folds what arrives, never the other
// way around. // way around.
import { ref } from 'vue' import { ref } from 'vue'
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw' import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
/** One tool call inside a turn: started, then completed by its result. */ /** One tool call inside a turn: started, then completed by its result. */
export interface ToolRow { export interface ToolRow {
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
/** A transcript line: a message the local user sent, or one streamed turn. */ /** A transcript line: a message the local user sent, or one streamed turn. */
export type TranscriptItem = export type TranscriptItem =
| { kind: 'sent'; id: number; text: string; images: SentImage[] } | { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
| { kind: 'turn'; id: number; turn: TurnBlock } | { kind: 'turn'; id: number; turn: TurnBlock }
| { kind: 'consent'; id: number; consent: ConsentCard } | { kind: 'consent'; id: number; consent: ConsentCard }
| { kind: 'attachment'; id: number; attachment: AttachmentCard } | { kind: 'attachment'; id: number; attachment: AttachmentCard }
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
return lines.length return lines.length
} }
/** A chip's label: `▣1 5L` — the anchor's one-based id and the /** A chip's label from its line count: `▣1 5L` — the chip's
* payload's line count (the TUI's chip_label). */ * one-based id and the payload's line count (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string { export function chipLinesLabel(lines: number, index: number): string {
return `▣${index + 1} ${lineCount(paste)}L` return `▣${index + 1} ${lines}L`
} }
/** Appends each paste as one MARK-payload-MARK embed, in order — the /** A chip's label from its payload (the TUI's chip_label). */
* session's record of the prompt (paste::embed; a web draft holds no export function chipLabel(paste: string, index: number): string {
* anchors, so every payload lands at the end). */ return chipLinesLabel(lineCount(paste), index)
export function embedPastes(draft: string, pastes: string[]): string { }
return (
draft + /** The modern record the wire carries: each paste a byte span in the
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('') * plain text (the `rhema-code` annotation's own shape), one walk over
) * the composed text mapping every code-point boundary — a span that
* splits a code point maps to none, the render skips it. */
export function byteToIndex(text: string): (byte: number) => number {
const at = new Map<number, number>([[0, 0]])
const bytesOf = new TextEncoder()
let bytes = 0
let units = 0
for (const cp of text) {
bytes += bytesOf.encode(cp).length
units += cp.length
at.set(bytes, units)
}
return (byte) => at.get(byte) ?? -1
}
/** Composes a send the way the fold composes its record: each paste's
* normalized payload appends to the draft, its chip's span measured
* over the composed plain text. The same form the `user_message`
* echo carries, so the optimistic row and the replay render rows of
* one shape and the echo dedupes against what this surface sent. */
export function composeChips(
draft: string,
pastes: string[],
): { text: string; pastes: PasteSpan[] } {
const bytesOf = new TextEncoder()
let text = draft
const spans: PasteSpan[] = []
for (const paste of pastes) {
const payload = normalizePaste(paste)
const start = bytesOf.encode(text).length
text += payload
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
}
return { text, pastes: spans }
} }
/** One scanned piece of embedded-form text. */ /** One scanned piece of embedded-form text. */
@@ -244,6 +277,7 @@ export function useTranscript() {
id: nextId++, id: nextId++,
text: event.text, text: event.text,
images: event.images.map((image) => ({ ...image, url: null, name: null })), images: event.images.map((image) => ({ ...image, url: null, name: null })),
pastes: event.pastes,
}) })
break break
} }
@@ -356,10 +390,10 @@ export function useTranscript() {
* Its images render from the staged previews — the claw stores them * Its images render from the staged previews — the claw stores them
* and the stream's echo dedupes against this row. Returns the row's * and the stream's echo dedupes against this row. Returns the row's
* id, so a failed POST can retract it. */ * id, so a failed POST can retract it. */
function addSent(text: string, images: SentImage[] = []): number { function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
const id = nextId++ const id = nextId++
pendingSent.push({ text, images: images.length, itemId: id }) pendingSent.push({ text, images: images.length, itemId: id })
items.value.push({ kind: 'sent', id, text, images }) items.value.push({ kind: 'sent', id, text, images, pastes })
return id return id
} }