Compare commits

..
6 Commits
Author SHA1 Message Date
kosmos ba258a1f50 fix(claw): a repo watch resumes from its durable cursor, or starts now
android / release (pull_request) Skipped
android / debug (pull_request) Successful in 2m17s
ci / chart (pull_request) Successful in 5s
ci / checks (pull_request) Failing after 24s
ci / test (pull_request) Failing after 27s
ci / docker (pull_request) Failing after 59s
ci / web (pull_request) Successful in 12s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
The watcher kept one cursor per repo in a `Mutex<HashMap>`, so every
daemon restart began with no cursor — and `Watcher::poll` reads "no
cursor" as "feed everything the forge returns". A restart therefore
replayed the repository's whole history: every old thread a dispatch, and
every dispatch a comment posted on a thread nobody had just touched. The
dispatcher's dedup lane does not save this: it dedups against the pending
inbox, and a drained event re-ingests clean.

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

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

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

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

    malformed forge response: comment issue_url without a thread number:

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

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

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

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

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

No files matched your search

-1
View File
@@ -1,2 +1 @@
/target/
.rhema/
Generated
+143 -1799
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*", "integrations/*"]
[workspace.package]
version = "0.4.1"
version = "0.2.3"
edition = "2024"
rust-version = "1.89"
license = "MIT"
+1 -1
View File
@@ -11,7 +11,7 @@ surface over HTTP — native routes plus an OpenAI-compatible shim,
with a web UI and an Android client talking to it.
The framework it embeds (the crates under `crates/` it pulls from
crates.io: `rhema-autonomous-agent`, `rhema-host-agent`,
crates.io: `rhema-autonomous-agent`, `rhema-coding-agent`,
`rhema-rsd`, and friends) lives in the
[rhema repository](https://git.vhaudiquet.fr/vhaudiquet/rhema).
+2 -5
View File
@@ -77,11 +77,8 @@ manages the device fleet the claw keeps.
**subscribe first, then POST**, the reply arrives on the stream. Thinking
deltas render dim and collapsible, tool rows show name/summary with error
coloring (bash-like tools render as shell lines instead: dim `$` prefix,
the command line, and an exit-code badge), a message's paste chips render
as compact `▣N 5L` labels sliced from the span record its
`user_message` carries beside the plain text (rows recorded before
spans rode the stream still scan the legacy paired-`U+FFFC` form in
the text), and
the command line, and an exit-code badge), pasted payloads embedded in a
message as paired `U+FFFC` marks render as compact `▣N 5L` chips, and
`attachment` events render as cards: file name, size, caption, an inline
preview for small (≤ 2 MB) images, and a download-and-open row (bytes
from `GET /v1/attachments/{id}` land in the app cache and open through a
@@ -11,7 +11,6 @@ import rs.rhema.phone.net.ClawApi
import rs.rhema.phone.net.ClawEvent
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.OutboundImage
import rs.rhema.phone.net.PasteSpan
import rs.rhema.phone.net.SseFrame
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -62,10 +61,6 @@ class ChatController(
override val id: Long,
val text: String,
val images: List<SentImage> = emptyList(),
// The chip record this surface's rows never carry (its
// composer sends plain text) but a replayed row — a web user's
// chips in this conversation — does; the render slices on it.
val pastes: List<PasteSpan> = emptyList(),
) : Item
data class Thinking(override val id: Long, val text: String) : Item
data class ToolCall(
@@ -360,15 +355,14 @@ class ChatController(
is ClawEvent.UserMessage -> {
// The recorded question — replayed on reload, echoed live
// for a message this surface just sent. An identical last
// row — same text, same image count, same chip record —
// is that echo's stand-in; skip it, previews and all.
// row — same text, same image count — is that echo's
// stand-in; skip it, previews and all.
val last = list.lastOrNull()
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size && last.pastes == event.pastes)) {
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size)) {
list = list + UserMessage(
newId(),
event.text,
event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) },
event.pastes,
)
}
}
@@ -117,13 +117,6 @@ data class RhemaNotification(
@Serializable
data class UserImage(val id: String, @SerialName("media_type") val mediaType: String)
// One paste chip a user_message records: the byte span (UTF-8) of the
// payload in the message's plain text, plus the payload's line count
// — the session annotation's own shape (rhema-core `PasteSpan`), so a
// chip renders from the record instead of rebuilding the wire form.
@Serializable
data class PasteSpan(val start: Int = 0, val end: Int = 0, val lines: Int = 0)
// One event of GET /v1/sessions/{key}/history: the record's seq for it,
// beside the event itself. Seq order is the wire order.
@Serializable
@@ -145,13 +138,11 @@ data class HistoryPage(val events: List<HistoryEvent> = emptyList(), val more: B
sealed interface ClawEvent {
@Serializable
@SerialName("user_message")
// Rows recorded before images — and then before chips — rode the
// stream carry no field at all; absent folds to none, never a
// guessed shape.
// Rows recorded before images rode the stream carry no field at
// all; absent folds to none, never a guessed shape.
data class UserMessage(
val text: String = "",
val images: List<UserImage> = emptyList(),
val pastes: List<PasteSpan> = emptyList(),
) : ClawEvent
@Serializable
@@ -261,7 +252,6 @@ data class CommandResult(val ok: Boolean, val detail: String? = null)
@Serializable
data class AgentIdentity(
val name: String? = null,
val email: String? = null,
val mark: String? = null,
val initials: String? = null,
val tagline: String? = null,
@@ -82,7 +82,6 @@ import rs.rhema.phone.chat.MAX_STAGED_IMAGES
import rs.rhema.phone.data.AgentIdentityCache
import rs.rhema.phone.di.AppContainer
import rs.rhema.phone.net.ClawResult
import rs.rhema.phone.net.PasteSpan
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
@@ -439,7 +438,6 @@ private sealed interface TurnGroup {
val id: Long,
val text: String,
val images: List<ChatController.SentImage>,
val pastes: List<PasteSpan> = emptyList(),
) : TurnGroup {
override val key: String = "u$id"
}
@@ -453,7 +451,7 @@ private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
val groups = mutableListOf<TurnGroup>()
for (item in items) {
when (item) {
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images, item.pastes)
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images)
else -> {
val last = groups.lastOrNull()
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item))
@@ -503,13 +501,10 @@ private fun TurnGroupRow(
}
}
}
// Chips render as chips, not payloads; the text
// around them stays verbatim. The row's chip record
// slices them out of the plain text; a row from
// before the record rode the stream carries none
// and still scans the mark form in the text.
// Embedded pastes render as chips, not payloads; the
// text around them stays verbatim.
var chip = 0
messageParts(group.text, group.pastes).forEach { part ->
pasteParts(group.text).forEach { part ->
when (part) {
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
is PastePart.Paste -> {
@@ -745,67 +740,20 @@ private fun PasteChip(label: String) {
)
}
// --- paste chips ------------------------------------------------------
// A long paste rides as a chip the render stands in for its payload.
// The record is the span list a user_message carries (the session
// annotation's own shape); the marks in the text are the record's
// legacy spelling, kept for rows that predate it — a mark with no
// partner is literal text (rhema-core's paste module is the
// definition; these are its client-side shape).
// --- embedded pastes --------------------------------------------------
// The wire form a long paste travels in: MARK, payload, MARK — one
// logical unit inside otherwise plain text (rhema-core's paste module
// is the definition; these are its client-side shape). A mark with no
// partner is literal text.
private const val PASTE_MARK = '\uFFFC'
/** One piece of a rendered message: literal text, or a chip standing
* for its payload. */
/** One scanned piece of embedded-form text. */
private sealed interface PastePart {
data class Text(val text: String) : PastePart
data class Paste(val payload: String) : PastePart
}
/** A message's parts. The chip record is the modern form — each span
* names the payload's byte range in the plain text — and rows recorded
* before it rode the stream carry none; those still scan the legacy
* mark form in the text itself. */
private fun messageParts(text: String, pastes: List<PasteSpan> = emptyList()): List<PastePart> =
if (pastes.isEmpty()) pasteParts(text) else spanParts(text, pastes)
/** Splits a record-carrying message into its parts, left to right. The
* spans' offsets are UTF-8 bytes, the plain form the fold measured —
* every character boundary is mapped in one walk, and a span that
* splits a character maps to none: the render skips it rather than cut
* one in half. Malformed input never throws. */
private fun spanParts(text: String, pastes: List<PasteSpan>): List<PastePart> {
var bytes = 0
var units = 0
val at = mutableMapOf(0 to 0)
var index = 0
while (index < text.length) {
val codePoint = text.codePointAt(index)
val width = Character.charCount(codePoint)
index += width
units = index
bytes += when {
codePoint < 0x80 -> 1
codePoint < 0x800 -> 2
codePoint < 0x10000 -> 3
else -> 4
}
at[bytes] = units
}
val parts = mutableListOf<PastePart>()
var cut = 0
for (span in pastes.sortedBy { it.start }) {
val start = at[span.start]
val end = at[span.end]
if (start == null || end == null || start < cut || end < start) continue
if (start > cut) parts += PastePart.Text(text.substring(cut, start))
parts += PastePart.Paste(text.substring(start, end))
cut = end
}
if (cut < text.length) parts += PastePart.Text(text.substring(cut))
return parts
}
/** Splits embedded-form text into its parts, left to right. A mark with
* no partner is literal text; malformed input never throws. */
private fun pasteParts(text: String): List<PastePart> {
+16 -29
View File
@@ -26,40 +26,29 @@ mock = ["rhema-core/mock"]
[dependencies]
# The shared toolkit: the resident agent assembles its agent from the
# shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.2"
rhema-prompt = "0.4.2"
rhema-host-agent = "0.4.2"
rhema-autonomous-agent = "0.4.2"
rhema-config = "0.4.2"
rhema-core = "0.4.2"
# shell, the approval seam, paste expansion, and revive-on-resume
rhema-agent-tools = "0.2.3"
rhema-autonomous-agent = "0.2.3"
rhema-coding-agent = "0.2.3"
rhema-config = "0.2.3"
rhema-core = "0.2.3"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.4.2"
rhema-transcript = "0.2.3"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat
rhema-identity = "0.4.2"
rhema-rsd = "0.4.2"
# The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box.
# The choice carries an ssh private key as text, so a store-held
# credential has no file to stage; that is the seam the 0.4.2 line adds,
# and the family moves to it together.
rhema-sandbox = "0.4.2"
rhema-sandbox-http = "0.4.2"
rhema-sandbox-ssh = "0.4.2"
rhema-identity = "0.2.3"
rhema-rsd = "0.2.3"
# The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain
rhema-memory = "0.4.2"
rhema-memory = "0.2.3"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.4.2"
rhema-provider-registry = "0.4.2"
rhema-provider = "0.2.3"
rhema-provider-registry = "0.2.3"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -70,8 +59,6 @@ thiserror = { workspace = true }
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
# concurrent handler runs share it. `net` is the HTTP listener.
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] }
# The sandbox executor implements the shell seam
async-trait = { workspace = true }
# The chat surface: native routes plus SSE, and the OpenAI shim
axum = { workspace = true }
# Broadcast receivers as SSE bodies
@@ -83,20 +70,20 @@ rusqlite = { version = "0.40", features = ["bundled"] }
time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.23"
rhema-mcp = "0.4.2"
base64 = "0.22"
rhema-mcp = "0.2.3"
[dev-dependencies]
tempfile = "3"
# In-process HTTP mocks for the offline e2e: zero network
wiremock = "0.6"
# The HTTP client for the surface tests, SSE bodies included
reqwest = { version = "0.13", features = ["json", "stream"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
# Naming the SSE chunks' type in the surface tests
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.4.2", features = ["mock"] }
rhema-core = { version = "0.2.3", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+1 -2
View File
@@ -8,8 +8,7 @@ questions, spread across turns.
Write SOUL.md (your name, tone, purpose) and USER.md (who the user
is) with the bootstrap_save tool as facts arrive; incrementally is
fine. Set what you learn about your own presentation with the
identity_set tool as well — your name, a mark or initials, a tagline, an
email to commit as.
identity_set tool as well — your name, a mark or initials, a tagline.
An avatar only if the user hands you an image file; they can also
upload one in the web interface's settings, and saying so beats
hunting one down. Never invent facts the user did not give.
+21 -81
View File
@@ -69,12 +69,6 @@ listen: 127.0.0.1:7799
token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: ssh # local (default), http, or ssh
host: me@box.example # the ssh destination: an alias or user@host
workspace: /srv/claw # ssh only: the workspace base, default /root
# http instead speaks the sandbox protocol (rhema-sandboxd):
# kind: http, url: https://box.example:7600, token: sandbox-secret
poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty
@@ -102,19 +96,6 @@ unattended for a long time, so a cap this deep is a runaway guard, not
a work timer — a turn that hits it ends with a failed outcome and the
conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. `kind: ssh` runs commands on a login the local `ssh`
config resolves (`host`, any alias or `user@host`), nothing installed
on the far end; `workspace` names the remote directory the claw's
workspaces live under, `/root` by default, one directory per claw
workspace under it. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
workspace root. Later edits stay there; the claw does not copy them
back.
The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer
token is what stands between it and the agent's tools. Set a token, or
@@ -142,13 +123,10 @@ The native surface:
```
GET /healthz GET /v1/sessions
POST /v1/sessions {"name"} — create an empty interactive session
POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?} -> 202
POST /v1/sessions/{key}/messages {"text": "..."} -> 202
GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
DELETE /v1/sessions/{key} drop a session and its turn history
POST /v1/sessions/{key}/pause hold the key's dispatch; queued work waits
POST /v1/sessions/{key}/resume lift the hold
POST /v1/sessions/{key}/abort cut the live turn, or drop the queued work
GET /v1/watches POST /v1/watches DELETE /v1/watches/{forge}/{repo}
GET /v1/bootstrap {"soul": bool, "user": bool}
POST /v1/ingest {"source","key","payload"} -> 202
@@ -159,8 +137,6 @@ DELETE /v1/consents/{id} deny a pending ask
GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?,"host"?,"workspace"?}, switch and persist
GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
@@ -193,10 +169,7 @@ lets a UI badge setup state.
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
`turn_done`. 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
`turn_done`. Every streamed event is persisted as it streams, so both a
reload and a daemon restart rebuild the transcript, and a session that
runs for weeks keeps all of it.
@@ -204,26 +177,14 @@ The seq is the record's dense per-key number for the event, and it is
the client's cursor. A subscription opens with a replay cut atomically
against the live feed, and the frames of both carry their seqs, so a
client that reconnects sends `?since=<last seq it saw>` and receives
exactly the gap. With no cursor the replay is the tail: the newest 400
events, cut back to the first turn boundary in them. The window widens
by doubling while it sits inside one turn, because a long agent turn
streams hundreds of deltas and a reload that opened mid-reply would
drop what the turn began with. A weeks-old session thus paints its
latest turn at once instead of replaying everything, and the turns
above it come from the history route, one whole turn per page, each
ending exactly where the previous page began. A cursor the
exactly the gap. With no cursor the replay is the tail — the newest 400
events, cut back to the first turn boundary in them — so a weeks-old
session paints its latest turn at once instead of replaying everything;
the turns above it come from the history route, one whole turn per
page, each ending exactly where the previous page began. A cursor the
record can no longer serve (a wiped table) answers with a `reset;`
comment and the tail, and the client rebuilds rather than splice.
The history route answers for every key in the inventory, not only the
resident prefixes. A key outside them — a forge thread, a finished
coding job — has no turn record to subscribe to, but the engine
checkpoints its session after every step. The route reads that stash
back as the same event shapes, cut into the same pages, and marks the
response `read_only: true`: the transcript a client can render, with no
stream to follow and no message the daemon would take. A key with no
stash yet answers an empty page.
A chat UI subscribes once, POSTs messages, and resets its mirror
whenever the stream (re)opens, letting the replay rebuild it; the daemon
owns the conversation, so the client mirrors the stream rather than
@@ -283,21 +244,7 @@ tool wakes with the account id, never the secret, and a denial or a
15-minute silence comes back in-band so the turn can say so and move
on. A watch with no token of its own polls — and replies — as the
matching saved account: the same forge, and on a self-hosted forge the
same base URL.
A repo watch is a feed, not an invitation. The daemon answers a thread
when somebody there addresses it — a comment whose body names the handle
its credential speaks as (`@kosmos`), written by anyone but itself — and
otherwise drains the news and runs nothing: no snapshot, no turn, no
comment on somebody else's conversation. (Its own replies quote the
mention they answer, so they never reopen the gate.) Notifications are
the other door and are adjudicated before they arrive — assigned, review
requested, @-mentioned — so those always run. The handle is the account
identity's when the token has one, and the forge's own `/user` answer
when it does not; a credential the forge will not name leaves the gate
open, with a warning in the log, rather than silently muting a watch.
Acting with a stored account is `identity_exec`: it runs one shell
same base URL. Acting with a stored account is `identity_exec`: it runs one shell
command in the session workspace with the secret injected —
`ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/
`GITLAB_TOKEN`, and a git credential helper — so `git clone` and API
@@ -358,26 +305,19 @@ same host serves both: the browser gets the web UI on `/`, the daemon
answers `/v1` and `/healthz`; one address for the browser and the
phone app, no CORS anywhere.
The image is the daemon plus what the agent's shell needs: `bash` and
`git` (the shell is load-bearing, the agent clones in its workspaces),
`curl` for a turn that fetches a URL, and `gob` for a command that
outlives the turn. The agent starts a build or a dev server with `gob
add` and reads its logs and ports on a later one. The chart runs
exactly one replica, the claw is single-node by design: one SQLite
store, one dispatcher. Single-node is what makes restarts instant: at
boot the daemon releases every lease the previous process left —
outright, not at the dead lease's TTL — so a turn an update cut
mid-flight answers its next message instead of stalling behind a ghost
(the committed tool call revives at the top of that next dispatch). The
cut turn is released as superseded on the way, so a thread it never
finished reads as aborted instead of wearing the outcome of the turn
before it. Nothing re-runs it: the mention was drained before the turn
ran, and the thread waits for the next activity.
The store and workspaces live on a PVC, `claw.yaml` in a ConfigMap (db
and workspace paths are pinned to the mounted volume), credentials in
a Secret, and the bearer token is the `token` value, required since
the daemon binds all interfaces in-cluster.
`persistence.enabled=false` trades restart survival for disposability.
The image is the daemon plus `bash` and `git` (the agent's shell is
load-bearing); the chart runs exactly one replica, the claw is
single-node by design: one SQLite store, one dispatcher. Single-node
is what makes restarts instant: at boot the daemon releases every
lease the previous process left — outright, not at the dead lease's
TTL — so a turn an update cut mid-flight answers its next message
instead of stalling behind a ghost (the committed tool call revives
at the top of that next dispatch). The
store and workspaces live on a PVC, `claw.yaml` in a ConfigMap (db and
workspace paths are pinned to the mounted volume), credentials in a
Secret, and the bearer token is the `token` value, required since the
daemon binds all interfaces in-cluster. `persistence.enabled=false`
trades restart survival for disposability.
The UI in `web/claw` is one client of the same surface: `npm run dev`
proxies to a local claw, `npm run build` emits the static bundle an
+3 -32
View File
@@ -1,15 +1,8 @@
You are the resident agent on this machine. This session's key is {{ session }}.
Your shell runs in the workspace at {{ workspace }}.
You answer chat here. Your shell runs in the workspace at {{ workspace }}.
Keep replies concrete. Do the work with tools instead of narrating it.
{% if surface == 'forge' %}
You answer forge threads — review requests, assignments, and mentions on
the repositories you watch. Your final message, the one you end the turn
on with no tool calls after it, is the comment posted to the thread
verbatim.
{% else %}
You answer chat here. Your final message, the one you end the turn on
with no tool calls after it, is the reply the user sees.
{% endif %}
Your final message, the one you end the turn on with no tool calls after
it, is the reply the user sees.
## Soul
@@ -43,27 +36,6 @@ what it is for. The arguments are the JSON schema a call must satisfy.
{{ vision }}
{% endif %}
{% if mcp %}
## MCP servers
Available MCP servers:
{% for server in mcp %}- {{ server.name }} (server: {{ server.server }}): {{ server.description }}
{% endfor %}
MCP servers are reachable through bash commands (**not** direct tool calls).
Usage:
{{ mcp[0].name }} --help # a server's tools
{{ mcp[0].name }} <tool> --help # one tool's arguments
{{ mcp[0].name }} <tool> --schema # one tool's exact input JSON
{{ mcp[0].name }} --flag value # a call; --prop_json for nested values
{{ mcp[0].name }} --json - <<'EOF' ... EOF # nested payloads: heredoc, no quoting
mcp servers | mcp tools <server> | mcp call <server> <tool> <json>
{% endif %}
{% if memory %}
## Memory
You keep persistent memory across sessions. memory_save stores what is
@@ -71,7 +43,6 @@ worth remembering: decisions, conventions, corrections, pointers.
memory_search recalls it; search before asking the user for something
they have likely said before. memory_forget removes a record on
request. Never save secrets into memory.
{% endif %}
{% if onboarding %}
{{ onboarding }}
-175
View File
@@ -1,175 +0,0 @@
//! The abort registry: a running turn the operator cut — the kill that
//! pairs with the pause gate ([`crate::pause`]).
//!
//! Pause holds what has not started; abort stops what has. A live turn
//! is minutes of tool rounds deep in a dispatch nobody watches, and the
//! only thing that can end it early is the dispatch itself: the turn's
//! own future, dropped at its current await — a streaming request, or a
//! running shell command, whose child dies with the drop. So each
//! handler holds a listener for its key across the dispatch (the lease
//! guarantees at most one dispatch per key, so entries never collide),
//! and the abort route signals through this registry; the handler
//! repairs the dangling calls, stashes what the turn committed, and
//! releases the lease as superseded.
//!
//! The mechanics are [`crate::steer`]'s — the same per-key channel, the
//! same signal-after-ingest ordering logic — with a different contract
//! on the far side: a steer signal loops the dispatch onto its next
//! round, an abort signal ends it. Signalling a key with no live
//! dispatch is a no-op (`false`), which makes the route's call
//! unconditional: the route's own idle path drains whatever is queued,
//! and the signal covers only the turn that runs.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use tokio::sync::mpsc;
/// The per-key abort registry. The daemon builds one and shares it with
/// the HTTP surface; every handler listens on it.
#[derive(Default)]
pub struct AbortRegistry {
/// One sender per key with a dispatch in flight; the guard's `Drop`
/// removes its own.
live: Mutex<HashMap<String, mpsc::Sender<()>>>,
}
impl AbortRegistry {
/// An empty registry.
pub fn new() -> Self {
Self::default()
}
/// Aborts the live dispatch on `key`, if there is one. `true` when a
/// listener took the signal; `false` when no dispatch runs (or its
/// channel is already full — one pending abort is enough; the turn
/// ends either way).
pub fn signal(&self, key: &str) -> bool {
let listener = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(key)
.cloned();
match listener {
Some(sender) => sender.try_send(()).is_ok(),
None => false,
}
}
/// Arms a listener for `key`. The guard is the dispatch's side: hold
/// it across the whole dispatch chain, drop it to unregister.
pub fn listen(self: &Arc<Self>, key: &str) -> AbortGuard {
let (sender, receiver) = mpsc::channel(1);
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned(), sender.clone());
AbortGuard {
registry: Arc::clone(self),
key: key.to_owned(),
sender,
receiver: Some(receiver),
}
}
}
/// One dispatch's listener: the receiver the select waits on, plus
/// enough identity to unregister only its own entry. The receiver sits
/// in an `Option` because `recv` consumes it; the borrow hands it back
/// after every await, so the guard stays the one object the dispatch
/// carries from round to round.
pub struct AbortGuard {
registry: Arc<AbortRegistry>,
key: String,
/// The guard's own sender, kept only so `Drop` can tell its entry
/// from a later dispatch's.
sender: mpsc::Sender<()>,
receiver: Option<mpsc::Receiver<()>>,
}
impl AbortGuard {
/// Whether an abort is pending. The dispatch checks this between
/// rounds: an abort carries no inbox message of its own, so unlike
/// steer's stale-signal clear, a pending abort here is honored, not
/// dropped.
pub fn take(&mut self) -> bool {
match self.receiver.as_mut() {
Some(receiver) => receiver.try_recv().is_ok(),
None => false,
}
}
/// Resolves once an abort arrives. A closed channel — impossible
/// while this guard lives, since its own sender sits in the
/// registry — parks forever rather than resolving empty, so the
/// select's abort arm goes silent instead of spinning.
pub async fn wait(&mut self) {
loop {
let received = match self.receiver.as_mut() {
Some(receiver) => receiver.recv().await,
None => std::future::pending::<Option<()>>().await,
};
if received.is_some() {
return;
}
}
}
}
impl Drop for AbortGuard {
fn drop(&mut self) {
// Only remove the entry this guard inserted: a same-key entry
// from a later dispatch must survive (it cannot coexist with a
// live one — the lease forbids it — but a defensive check keeps
// the registry honest regardless of caller discipline).
let mut live = self
.registry
.live
.lock()
.unwrap_or_else(PoisonError::into_inner);
if live
.get(&self.key)
.is_some_and(|entry| entry.same_channel(&self.sender))
{
live.remove(&self.key);
}
self.receiver = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_signal_with_no_listener_is_a_no_op() {
let registry = Arc::new(AbortRegistry::new());
assert!(!registry.signal("job:rhema#7"));
}
#[tokio::test]
async fn a_listener_takes_the_signal_and_unregisters_on_drop() {
let registry = Arc::new(AbortRegistry::new());
let mut guard = registry.listen("job:rhema#7");
assert!(registry.signal("job:rhema#7"));
guard.wait().await;
// A second signal fills the capacity-one channel and reports as
// not taken — one pending abort is enough.
assert!(registry.signal("job:rhema#7"));
assert!(!registry.signal("job:rhema#7"));
assert!(guard.take());
drop(guard);
assert!(!registry.signal("job:rhema#7"), "the entry is gone");
}
#[test]
fn keys_abort_independently() {
let registry = Arc::new(AbortRegistry::new());
let _guard = registry.listen("job:rhema#7");
assert!(!registry.signal("job:rhema#8"));
assert!(registry.signal("job:rhema#7"));
}
}
+10 -8
View File
@@ -29,8 +29,7 @@ use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::{ToolCall, ToolContext, ToolResolver, ToolResult, ToolSpec};
use rhema_identity::{Account, AccountDraft, IdentityStore, Secret, SecretKind};
use serde::Deserialize;
@@ -284,7 +283,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// The identity tool set over the account store and the watch table —
/// specs from the embedded manifests, operations compiled here.
pub fn registry(accounts: Arc<dyn IdentityStore>, watches: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(accounts, watches));
assert!(
skipped.is_empty(),
"the identity tool manifests must all load: {skipped:?}"
@@ -582,7 +582,7 @@ impl ToolResolver for IdentityExec {
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::ToolOp;
use rhema_autonomous_agent::ToolOp;
fn parts() -> (Arc<dyn IdentityStore>, Arc<ClawStore>) {
(
@@ -598,13 +598,15 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin_and_serves_the_registry() {
let (accounts, watches) = parts();
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(accounts, watches),
);
assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 3);
let (accounts, watches) = parts();
let resolver =
registry(accounts, watches).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = registry(accounts, watches)
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("identity_list"),
rhema_core::ReplaySafety::Safe
+6 -5
View File
@@ -17,8 +17,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -310,8 +309,10 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into(), hub, key));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, workspace.into(), hub, key),
);
assert!(
skipped.is_empty(),
"the attach_file tool manifest must load: {skipped:?}"
@@ -326,7 +327,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+11 -149
View File
@@ -26,10 +26,9 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_agent_tools::render_template;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json};
/// The built-in system prompt, kept as data next to the code and read
@@ -198,32 +197,15 @@ fn section(header: &str, content: Option<&str>, stub: &str) -> String {
format!("{header}\n\n{}", content.unwrap_or(stub))
}
/// Which surface a dispatch answers on: the template's opening and
/// reply contract differ — a chat reply goes to the user, a forge
/// reply goes to the thread — and onboarding is a chat offer only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Surface {
/// The chat surfaces: interactive sessions, tasks, phone, reminders.
Chat,
/// A forge thread dispatch: a watch event answered on the forge.
Forge,
}
/// Renders the system prompt for one dispatch through the agent
/// toolkit's Jinja renderer: `{{ workspace }}` and the three file
/// sections from the live store, `tools` from the dispatch's own
/// resolver specs, `{{ session }}` — the dispatching key, the address
/// the model schedules its own wakes to — and `onboarding`, the offer
/// the template's `{% if %}` shows only while a file is unwritten, and
/// only on a chat surface: a forge dispatch is nobody's first
/// conversation. `mcp` renders the wired servers' section, empty on a
/// surface with none; the memory section renders only when the roster
/// actually carries the memory tools, so a forge prompt never
/// documents tools it does not have. Fallible on purpose — a store
/// that cannot be read surfaces loudly instead of rendering a prompt
/// without it, and a template that cannot render fails the dispatch
/// before any model call.
#[expect(clippy::too_many_arguments, reason = "eight parts, each load-bearing")]
/// the template's `{% if %}` shows only while a file is unwritten.
/// Fallible on purpose — a store that cannot be read surfaces loudly
/// instead of rendering a prompt without it, and a template that
/// cannot render fails the dispatch before any model call.
pub fn render_system(
template: &str,
session: &str,
@@ -231,18 +213,15 @@ pub fn render_system(
bootstrap: &Bootstrap,
tools: &[ToolSpec],
vision: Option<&str>,
mcp: &[rhema_config::mcp::McpServerLine],
surface: Surface,
) -> Result<String, BootstrapError> {
let soul = bootstrap.load(BootstrapKind::Soul)?;
let user = bootstrap.load(BootstrapKind::User)?;
let environment = bootstrap.load(BootstrapKind::Environment)?;
let onboarding = if surface == Surface::Chat && (soul.is_none() || user.is_none()) {
let onboarding = if soul.is_none() || user.is_none() {
ONBOARDING_MD
} else {
""
};
let memory = tools.iter().any(|spec| spec.name == "memory_save");
let context = json!({
"session": session,
"workspace": workspace.display().to_string(),
@@ -252,12 +231,6 @@ pub fn render_system(
"onboarding": onboarding,
"tools": tools,
"vision": vision,
"mcp": mcp,
"memory": memory,
"surface": match surface {
Surface::Chat => "chat",
Surface::Forge => "forge",
},
});
render_template(template, &context).map_err(|err| {
let line = err
@@ -313,7 +286,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// interactive resolver chain composes — its spec from the embedded
/// manifest, the operation compiled here.
pub fn registry(bootstrap: Arc<Bootstrap>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(bootstrap));
assert!(
skipped.is_empty(),
"the bootstrap tool manifest must load: {skipped:?}"
@@ -444,7 +418,7 @@ mod tests {
let tools = registry(Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}))
.resolver_for(&crate::toolkit::Allowlist::permissive())
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive())
.specs();
let prompt = render_system(
DEFAULT_SYSTEM_MD,
@@ -453,8 +427,6 @@ mod tests {
&bootstrap,
&tools,
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(prompt.contains("## SOUL"), "{prompt}");
@@ -467,110 +439,6 @@ mod tests {
assert!(prompt.contains("bootstrap_save"), "{prompt}");
}
#[test]
fn a_fresh_house_on_the_forge_surface_never_carries_the_onboarding() {
let (_dir, bootstrap) = store();
let prompt = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
Path::new("/ws"),
&bootstrap,
&[],
None,
&[],
Surface::Forge,
)
.expect("renders");
assert!(
!prompt.contains("## Onboarding"),
"a forge thread is nobody's first conversation: {prompt}"
);
assert!(
prompt.contains("the comment posted to the thread"),
"the forge branch of the reply contract: {prompt}"
);
assert!(
!prompt.contains("You answer chat here"),
"not the chat branch: {prompt}"
);
assert_eq!(prompt.matches(PENDING).count(), 2, "{prompt}");
}
#[test]
fn the_memory_section_renders_only_when_the_roster_carries_the_tools() {
let (_dir, bootstrap) = store();
let memory = [ToolSpec::new(
"memory_save",
"stores a record",
json!({"type": "object"}),
)];
let with = render_system(
DEFAULT_SYSTEM_MD,
"interactive:web",
Path::new("/ws"),
&bootstrap,
&memory,
None,
&[],
Surface::Chat,
)
.expect("renders");
let without = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
Path::new("/ws"),
&bootstrap,
&[],
None,
&[],
Surface::Forge,
)
.expect("renders");
assert!(with.contains("## Memory"), "{with}");
assert!(
!without.contains("## Memory"),
"no memory tools, no memory section: {without}"
);
}
#[test]
fn the_wired_mcp_servers_render_their_section() {
let (_dir, bootstrap) = store();
let mcp = [rhema_config::mcp::McpServerLine {
name: "acme-mcp".to_owned(),
server: "acme".to_owned(),
description: "the acme tools".to_owned(),
}];
let prompt = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
Path::new("/ws"),
&bootstrap,
&[],
None,
&mcp,
Surface::Forge,
)
.expect("renders");
assert!(prompt.contains("## MCP servers"), "{prompt}");
assert!(
prompt.contains("- acme-mcp (server: acme): the acme tools"),
"{prompt}"
);
let bare = render_system(
DEFAULT_SYSTEM_MD,
"interactive:web",
Path::new("/ws"),
&bootstrap,
&[],
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(!bare.contains("## MCP servers"), "{bare}");
}
#[test]
fn the_full_house_renders_each_file_and_drops_the_onboarding_section() {
let (_dir, bootstrap) = store();
@@ -588,8 +456,6 @@ mod tests {
&bootstrap,
&[],
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(
@@ -618,8 +484,6 @@ mod tests {
&bootstrap,
&[],
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(prompt.contains(content), "{prompt}");
@@ -652,8 +516,6 @@ mod tests {
&bootstrap,
&tools,
None,
&[],
Surface::Chat,
)
.expect("renders");
assert!(prompt.contains("- my_tool | {"), "{prompt}");
@@ -666,7 +528,7 @@ mod tests {
#[tokio::test]
async fn the_tool_writes_through_the_store_and_answers_one_line() {
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
use rhema_core::{ToolCall, ToolContext};
let (_dir, bootstrap) = store();
+6 -145
View File
@@ -13,7 +13,6 @@
//! binary's startup, not here — the daemon library takes the built
//! provider, so tests can inject a mock.
use std::num::NonZeroU32;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -23,13 +22,10 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60;
/// How many tool rounds one chat turn may run, when
/// [`ClawConfig::max_turn_steps`] is unset — the host agent driver's
/// own budget shape and its default: deep enough that a cap is a
/// runaway guard for an agent meant to work unattended, not a work
/// timer. `NonZeroU32`, the driver's own spelling: a turn cannot have
/// no step budget at all, and a config that names zero is refused at
/// load instead of cutting every round dead.
pub const DEFAULT_MAX_TURN_STEPS: NonZeroU32 = NonZeroU32::new(2048).unwrap();
/// [`ClawConfig::max_turn_steps`] is unset — the coding driver's own
/// budget shape and its default: deep enough that a cap is a runaway
/// guard for an agent meant to work unattended, not a work timer.
pub const DEFAULT_MAX_TURN_STEPS: u32 = 2048;
/// Where the HTTP surface listens when [`ClawConfig::listen`] is unset:
/// loopback only — the surface is for the machine's resident user.
@@ -59,9 +55,6 @@ pub enum ConfigError {
"agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
)]
SameAgentToken,
/// The configured sandbox choice cannot run as written.
#[error("sandbox: {0}")]
Sandbox(String),
/// The ingest credential is the same value as the human token or
/// the agent token: boot refuses, because the ingest credential's
/// safety is that it is write-only and the event door only — a
@@ -134,7 +127,7 @@ pub struct ClawConfig {
/// How many tool rounds one chat turn may run before it is cut off
/// with a failed outcome, the conversation intact. A follow-up
/// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset.
pub max_turn_steps: NonZeroU32,
pub max_turn_steps: u32,
/// The handler's model backend: `google`, `llama-cpp`, `openrouter`,
/// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve
/// through the stored rhema config's default profile, env vars
@@ -178,33 +171,6 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still
/// ingest.
pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, a
/// `rhema-sandboxd` over HTTP, or an ssh login on a far box (`kind:
/// ssh`, a `host` destination, and optionally the `private_key`
/// text itself, not a path, the credential stays in this file or
/// the store that holds it). The settings store owns the live
/// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>,
/// The git identity the daemon writes into its user's global git
/// config at boot, so workspace commits carry the agent as author.
/// A field set here wins over the agent's identity (what
/// onboarding and the settings page write); both win over
/// defaults. See [`crate::git_identity`].
pub git: Option<GitIdentity>,
}
/// One git identity as the config states it: both fields optional, a
/// set field winning over the identity store, an unset one falling
/// through.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct GitIdentity {
/// The commit author name.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The commit author address.
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
}
impl ClawConfig {
@@ -232,8 +198,6 @@ impl Default for ClawConfig {
tools_bin: None,
ingest_token: None,
transcript: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -362,12 +326,6 @@ impl ClawConfig {
{
return Err(ConfigError::IngestTokenCollision);
}
if let Some(sandbox) = &self.sandbox {
sandbox
.clone()
.normalized()
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
}
Ok(())
}
}
@@ -464,17 +422,10 @@ model: claude-sonnet-4-5
listen: 192.168.1.10:7800
token: sekrit
ingest_token: door-key
sandbox:
kind: http
url: https://box.example:7600
token: sandbox-secret
git:
name: Bot
email: bot@example.net
";
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
assert_eq!(config.poll_interval_secs, 30);
assert_eq!(config.max_turn_steps, NonZeroU32::new(512).unwrap());
assert_eq!(config.max_turn_steps, 512);
assert_eq!(config.provider.as_deref(), Some("anthropic"));
assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5"));
assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800"));
@@ -487,96 +438,6 @@ git:
config.bootstrap_root.as_deref(),
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap"))
);
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
let git = config.git.expect("the git identity parses");
assert_eq!(git.name.as_deref(), Some("Bot"));
assert_eq!(git.email.as_deref(), Some("bot@example.net"));
let config: ClawConfig = serde_yaml::from_str(
"sandbox:\n kind: ssh\n host: me@box.example\n workspace: /srv/claw\n",
)
.expect("the ssh sandbox parses");
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Ssh);
assert_eq!(sandbox.host.as_deref(), Some("me@box.example"));
assert_eq!(sandbox.workspace.as_deref(), Some("/srv/claw"));
}
#[test]
fn an_http_sandbox_needs_a_url_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"a remote sandbox without a URL is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
fn an_ssh_sandbox_needs_a_host_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"an ssh sandbox without a host is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
host: Some("me@box.example".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a bare login is all ssh needs");
}
#[test]
fn the_git_section_rejects_a_typo_and_carries_partial_identity() {
let err = serde_yaml::from_str::<ClawConfig>(
"git:
nmae: Bot
",
)
.expect_err("a typo inside the section must not read as its default");
assert!(
err.to_string().contains("nmae"),
"the error names the key: {err}"
);
// One field alone is legal: the other falls through to the
// identity store, then defaults.
let config: ClawConfig = serde_yaml::from_str(
"git:
email: bot@example.net
",
)
.expect("parses");
let git = config.git.expect("the section parses");
assert_eq!(git.email.as_deref(), Some("bot@example.net"));
assert_eq!(git.name, None);
}
#[test]
+6 -5
View File
@@ -21,8 +21,7 @@ use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -510,8 +509,10 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(consents, bridge, hub, key));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(consents, bridge, hub, key),
);
assert!(
skipped.is_empty(),
"the ask_secret tool manifest must load: {skipped:?}"
@@ -526,7 +527,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+33 -343
View File
@@ -22,7 +22,6 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use rhema_autonomous_agent::{Driver, Source, SourceError};
@@ -63,9 +62,6 @@ pub enum ClawError {
/// The runtime settings table could not be opened or read.
#[error(transparent)]
Settings(#[from] crate::settings::SettingsError),
/// The sandbox choice could not be loaded or is malformed.
#[error(transparent)]
Sandbox(#[from] crate::sandbox::SandboxError),
/// The notification table could not be opened or read.
#[error(transparent)]
Notifications(#[from] crate::notifications::NotificationStoreError),
@@ -127,83 +123,6 @@ fn interactive_dispatch() -> DispatcherConfig {
}
}
/// The forge dispatcher's timing: the library defaults, except the lease
/// TTL.
///
/// A forge turn is not a chat step. The handler clones a repository,
/// reads it, and may build and test a fix — tens of minutes of wall
/// clock — and nothing renews the lease once the turn is under way:
/// `SessionContext::poll_inbox` renews, and the handler calls it once, at
/// the start; the commit hook that runs between tool calls *checkpoints*,
/// which fails on a lapsed lease instead of extending one. So the TTL is
/// a hard ceiling on a whole turn: cross it and the turn dies on its next
/// tool call, after which the driver's own checkpoint and release both
/// report `Expired` and the key ends with no outcome recorded — a silent
/// kill, indistinguishable from a pass that found nothing.
///
/// `DispatcherConfig::default`'s ten minutes are the spec's example
/// values, sized for a single agent step. An hour matches the
/// interactive lane's choice for the same reason: the work is long.
pub fn forge_dispatch() -> DispatcherConfig {
DispatcherConfig {
lease_ttl_millis: 3_600_000,
..DispatcherConfig::default()
}
}
/// Hands one driver pass to its own task, so a turn does not stop the
/// clock.
///
/// [`Driver::run_once`] awaits every run it admits, which is exactly right
/// for a cron pass and wrong for a resident: a forge turn clones a repo
/// and may build a slicer, a coding job runs a session — tens of minutes
/// either way — and everything else the loop does (detecting, and so
/// polling the forges, recording watch health, firing due tasks, reading
/// the calendar, delivering to the phone) waits behind it. With a 60s
/// tick and a ten-minute turn, the daemon polls once per turn.
///
/// One pass per lane at a time. `busy` is held for the pass's whole
/// duration, and a tick that finds it held leaves its events where they
/// are: the dispatcher's inbox is the queue, so nothing is dropped — the
/// next tick admits them. Starting a second pass anyway would only lose
/// lease acquisitions to the first and log the loss.
fn spawn_pass(driver: Arc<Driver>, label: &'static str, busy: Arc<AtomicBool>) {
if busy.swap(true, Ordering::AcqRel) {
return;
}
let held = BusyFlag(busy);
tokio::spawn(async move {
// Dropped however this task ends, a panic included: a lane whose
// flag never cleared would never run again.
let _held = held;
match driver.run_once().await {
Ok(outcomes) => {
let handled = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Handled))
.count();
let failed = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Failed(_)))
.count();
if handled + failed > 0 {
eprintln!("[claw] {label} pass: {handled} handled, {failed} failed");
}
}
Err(err) => eprintln!("[claw] warning: {label} pass failed: {err}"),
}
});
}
/// Clears a lane's in-flight flag when its spawned pass ends.
struct BusyFlag(Arc<AtomicBool>);
impl Drop for BusyFlag {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
/// The resident daemon: the extension set's sources (the forge watches,
/// the task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface.
@@ -220,10 +139,6 @@ pub struct Daemon {
forge_driver: Arc<Driver>,
interactive_driver: Arc<Driver>,
jobs_driver: Arc<Driver>,
/// Whether a forge pass is running off the tick (see [`spawn_pass`]).
forge_pass_busy: Arc<AtomicBool>,
/// Whether a jobs pass is running off the tick.
jobs_pass_busy: Arc<AtomicBool>,
poll_interval: Duration,
listen: String,
http: ClawState,
@@ -236,8 +151,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// with `--once` zeroing the debounce.
/// the forge dispatcher's timing — the resident loop uses the
/// defaults, `--once` zeroes the debounce.
pub fn build(
config: &ClawConfig,
backends: Arc<BackendRegistry>,
@@ -310,10 +225,6 @@ impl Daemon {
// The forge handler resolves its watches through the table at
// dispatch time, so a watch added mid-run is answerable without a
// restart.
// The runtime settings table, opened before the handlers so the
// sandbox choice and the provider write share one connection.
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The client tools' connection, handed to the agent's shell as
// environment: the URL the surface answers on, the scoped
// agent token (the middleware keeps it to the contract's data
@@ -341,64 +252,25 @@ impl Daemon {
format!("{}:{inherited}", tools_bin.display()),
);
}
// Where `bash` runs: the stored choice wins, the config seeds a
// fresh store. The state is shared by every handler and the
// surface, so a switch is live on the next turn.
let sandbox = Arc::new(crate::sandbox::SandboxState::load(
settings.clone(),
config.sandbox.clone(),
interactive_workspace.clone(),
&tool_env,
)?);
let sandbox_choice = sandbox.choice();
eprintln!(
"[claw] sandbox: {}{}",
sandbox_choice.kind.as_str(),
sandbox_choice
.url
.as_deref()
.map(|url| format!(" ({url})"))
.unwrap_or_default(),
);
// The bootstrap store, before both handlers: the chat renders
// its files per dispatch, and so does the forge one now — the
// persona is shared, the workspaces are not. The environment
// report lands in the store's directory at boot, below.
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
// The pause gate: the keys the drivers hold, loaded from the
// settings table, shared with the HTTP surface's pause route.
let pause = Arc::new(crate::pause::PauseSet::load(settings.clone())?);
// The abort registry: the per-key cut the handlers listen on,
// shared with the HTTP surface's abort route.
let abort = Arc::new(crate::abort::AbortRegistry::new());
let forge_handler = ClawHandler::new(
backends.clone(),
workspace_root,
watches.clone(),
accounts.clone(),
bootstrap.clone(),
config.transcript_enabled(),
tool_env.clone(),
)
.with_sandbox(sandbox.clone())
.with_abort(abort.clone());
);
// Three drivers over one store admit from the same table, so
// each owns its slice of the key space: a forge pass must never
// pick up a resident or job event (it would fail it, and
// consume it), and the others likewise. Paused keys belong to
// no driver: every predicate declines them, pass after pass,
// until resume lifts the hold.
// consume it), and the others likewise.
let forge_driver = Arc::new(
Driver::new(forge_dispatcher.clone(), Arc::new(forge_handler))
.with_holder("rhema-claw")
.owning({
let pause = pause.clone();
Arc::new(move |key: &ResourceKey| {
.owning(Arc::new(|key: &ResourceKey| {
!crate::interactive::is_resident_key(key.as_str())
&& !crate::jobs::is_job_key(key.as_str())
&& !pause.is_paused(key.as_str())
})
}),
})),
);
// The consent table and its wake bridge: the `ask_secret` tool
@@ -419,6 +291,8 @@ impl Daemon {
// `phone` tool queues behind a consent.
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
// The identity store shares the settings table and keeps its
// images beside the database.
let identity = Arc::new(crate::identity::IdentityStore::new(
@@ -487,22 +361,16 @@ impl Daemon {
extensions.clone(),
config.transcript_enabled(),
)
.with_steer(steer.clone())
.with_abort(abort.clone())
.with_sandbox(sandbox.clone());
.with_steer(steer.clone());
let interactive_driver = Arc::new(
Driver::new(
interactive_dispatcher.clone(),
Arc::new(interactive_handler),
)
.with_holder("rhema-claw-interactive")
.owning({
let pause = pause.clone();
Arc::new(move |key: &ResourceKey| {
.owning(Arc::new(|key: &ResourceKey| {
crate::interactive::is_resident_key(key.as_str())
&& !pause.is_paused(key.as_str())
})
}),
})),
);
// The coding jobs: one handler, one driver, one source. The
// final text of a job's turn notifies the user's device, so the
@@ -513,18 +381,13 @@ impl Daemon {
notifications.clone(),
config.max_turn_steps,
config.transcript_enabled(),
)
.with_sandbox(sandbox.clone())
.with_abort(abort.clone());
);
let jobs_driver = Arc::new(
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
.with_holder("rhema-claw-jobs")
.owning({
let pause = pause.clone();
Arc::new(move |key: &ResourceKey| {
crate::jobs::is_job_key(key.as_str()) && !pause.is_paused(key.as_str())
})
}),
.owning(Arc::new(|key: &ResourceKey| {
crate::jobs::is_job_key(key.as_str())
})),
);
crate::interactive::register_user(&interactive_dispatcher);
@@ -539,9 +402,6 @@ impl Daemon {
bootstrap,
hub,
steer,
pause,
abort,
jobs,
backends.clone(),
settings.clone(),
identity,
@@ -550,7 +410,6 @@ impl Daemon {
bridge,
attachments,
phone,
sandbox,
config.token.clone(),
config.agent_token.clone(),
config.ingest_token.clone(),
@@ -565,8 +424,6 @@ impl Daemon {
forge_driver,
interactive_driver,
jobs_driver,
forge_pass_busy: Arc::new(AtomicBool::new(false)),
jobs_pass_busy: Arc::new(AtomicBool::new(false)),
// A zero poll interval would spin detect passes against the
// forge API; one second is the floor.
poll_interval: Duration::from_secs(config.poll_interval_secs.max(1)),
@@ -606,52 +463,25 @@ impl Daemon {
// is failed interrupted before anything re-runs, and a
// still-queued row is re-armed with a fresh dedup id.
self.extensions.boot()?;
// The leases still in the store name the turns this restart cut.
// The three dispatchers share one store, so one read sees them
// all. Read before the sweep forgets, recover, then release each
// one as superseded: a record keeps the outcome of its last
// release, so a cut turn would otherwise wear the previous
// turn's word, and the read-only transcript would print
// "handled" beside text the turn never finished.
let cut: Vec<ResourceKey> = self
.forge_dispatcher
.list_active()?
.into_iter()
// An empty inbox is the turn that had already drained its
// news, which is the one a restart strands. A key with items
// waiting re-acquires on its own and records its own outcome.
.filter(|status| status.inbox_depth == 0)
.map(|status| status.key)
.collect();
self.forge_dispatcher.recover_all()?;
self.jobs_dispatcher.recover_all()?;
self.interactive_dispatcher.recover_all()?;
for key in cut {
let acquired = self.forge_dispatcher.acquire(key.clone(), "claw-boot");
let lease = match acquired {
Ok((lease, _)) => lease,
Err(err) => {
eprintln!("[claw] warning: {key}: cut turn not marked aborted: {err}");
continue;
}
};
if let Err(err) = self.forge_dispatcher.release(&lease, Outcome::Superseded) {
eprintln!("[claw] warning: {key}: cut turn not marked aborted: {err}");
}
}
Ok(())
}
/// One pass, awaited to the end: every source detects (due tasks
/// first — a reminder is the user-facing clock), the forge driver
/// runs every key the debounce released, and the interactive driver
/// drains as a backstop. The shape a `--once` run and the tests
/// drive, where "the pass is over" has to mean the work is over.
///
/// The resident loop uses [`Daemon::resident_tick`] instead: same
/// detection, but the long lanes are not awaited.
/// One pass: every source detects (due tasks first — a reminder is
/// the user-facing clock), the forge driver runs every key the
/// debounce released, and the interactive driver drains as a
/// backstop — a message delivered live into a running turn waits at
/// the key for a pass like this one.
pub async fn tick(&self) -> Result<TickReport, ClawError> {
let detected = self.detect().await?;
// The tick only detects — every timer here drives
// deterministic detection, and the set's order is the contract:
// due tasks before the calendar reminders that fire for them.
let mut detected = 0usize;
for source in &self.sources {
detected += source.detect().await?;
}
// A queued coding job starts before the forge pass: it is the
// thing someone just asked for.
if let Err(err) = self.jobs_driver.run_once().await {
@@ -671,50 +501,6 @@ impl Daemon {
"[claw] pass: {detected} event(s) detected, {handled} handled, {failed} failed"
);
}
self.drain_interactive().await;
Ok(TickReport { detected, outcomes })
}
/// The resident loop's pass: the same detection, with the two lanes
/// whose runs last minutes or hours handed to their own tasks.
///
/// Detection is the part that must keep its cadence — the forge polls
/// and the health rows they write, the due tasks, the calendar
/// reminders, the phone delivery all ride it — and detection alone is
/// quick. Awaiting a turn inside it means every one of those timers
/// stops for as long as the turn runs. See [`spawn_pass`].
pub async fn resident_tick(&self) -> Result<(), ClawError> {
self.detect().await?;
// A queued coding job starts before the forge pass: it is the
// thing someone just asked for.
spawn_pass(
self.jobs_driver.clone(),
"jobs",
self.jobs_pass_busy.clone(),
);
spawn_pass(
self.forge_driver.clone(),
"forge",
self.forge_pass_busy.clone(),
);
self.drain_interactive().await;
Ok(())
}
/// Detection only: every source, in set order. The tick's order is
/// the contract — due tasks before the calendar reminders that fire
/// for them — and the sources carry it.
async fn detect(&self) -> Result<usize, ClawError> {
let mut detected = 0usize;
for source in &self.sources {
detected += source.detect().await?;
}
Ok(detected)
}
/// The interactive driver, drained as a backstop: a message delivered
/// live into a running turn waits at the key for a pass like this one.
async fn drain_interactive(&self) {
match self.interactive_driver.run_once().await {
Ok(runs) if !runs.is_empty() => {
eprintln!("[claw] interactive: {} queued run(s) drained", runs.len());
@@ -722,13 +508,13 @@ impl Daemon {
Ok(_) => {}
Err(err) => eprintln!("[claw] warning: interactive pass failed: {err}"),
}
Ok(TickReport { detected, outcomes })
}
/// The resident loop: the HTTP surface comes up first (a resident is
/// talked to), then detect, hand the long lanes to their own tasks,
/// sleep, until ctrl-c. A failed pass is logged, not fatal — a forge
/// outage or a dead backend must not end a daemon whose next pass may
/// simply succeed.
/// talked to), then detect, run, sleep, until ctrl-c. A failed pass
/// is logged, not fatal — a forge outage or a dead backend must not
/// end a daemon whose next pass may simply succeed.
pub async fn run(&self) -> Result<(), ClawError> {
self.bootstrap().await?;
let listener = tokio::net::TcpListener::bind(&self.listen).await?;
@@ -741,7 +527,7 @@ impl Daemon {
});
eprintln!("[claw] http listening on {addr}");
loop {
if let Err(err) = self.resident_tick().await {
if let Err(err) = self.tick().await {
eprintln!("[claw] warning: pass failed: {err}");
}
tokio::select! {
@@ -765,7 +551,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig {
debounce_window_millis: 0,
..forge_dispatch()
..DispatcherConfig::default()
};
let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?;
@@ -776,102 +562,6 @@ pub async fn run_once(
mod tests {
use super::*;
/// A handler that holds its key until the test lets it go, and counts
/// the runs it served.
struct GatedHandler {
runs: std::sync::atomic::AtomicUsize,
started: tokio::sync::Semaphore,
release: tokio::sync::Semaphore,
}
#[rhema_autonomous_agent::async_trait]
impl rhema_autonomous_agent::Handler for GatedHandler {
async fn handle(&self, _ctx: &mut rhema_autonomous_agent::SessionContext) -> Outcome {
self.runs.fetch_add(1, Ordering::SeqCst);
self.started.add_permits(1);
let _ = self.release.acquire().await;
Outcome::Handled
}
}
/// A pass handed to its own task keeps the tick free, holds its lane
/// while it runs, and does not stack: a tick that fires mid-pass
/// leaves its events in the dispatcher's inbox for the next one.
#[tokio::test]
async fn a_spawned_pass_holds_its_lane_instead_of_stacking() {
let dispatcher = Arc::new(Dispatcher::new(
DispatcherConfig {
debounce_window_millis: 0,
..DispatcherConfig::default()
},
Arc::new(SystemClock),
Arc::new(rhema_rsd::VolatileStore::new()),
));
let handler = Arc::new(GatedHandler {
runs: std::sync::atomic::AtomicUsize::new(0),
started: tokio::sync::Semaphore::new(0),
release: tokio::sync::Semaphore::new(0),
});
// The dispatcher resolves an event's key through its source's key
// function; nothing ingests before its source is registered.
dispatcher.register_source(
"test",
Arc::new(|event: &rhema_rsd::Event| {
rhema_rsd::ResourceKey::from(format!("test:{}", event.id))
}),
);
let driver = Arc::new(Driver::new(dispatcher.clone(), handler.clone()));
dispatcher
.ingest(rhema_rsd::Event {
id: "e1".to_owned(),
source: "test".to_owned(),
payload: serde_json::json!({}),
received_at: 0,
})
.expect("event lands");
let busy = Arc::new(AtomicBool::new(false));
spawn_pass(driver.clone(), "test", busy.clone());
// The pass runs on its own task: the caller is already back, and
// the lane reads as held while the turn is under way.
tokio::time::timeout(Duration::from_secs(5), handler.started.acquire())
.await
.expect("the pass starts within five seconds")
.expect("the pass starts")
.forget();
assert!(
busy.load(Ordering::SeqCst),
"the lane is held for the whole pass"
);
spawn_pass(driver.clone(), "test", busy.clone());
handler.release.add_permits(1);
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while busy.load(Ordering::SeqCst) {
assert!(
tokio::time::Instant::now() < deadline,
"the flag clears when the pass ends"
);
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert_eq!(handler.runs.load(Ordering::SeqCst), 1, "one pass, not two");
}
#[test]
fn the_forge_dispatcher_leases_for_a_turn_not_a_step() {
let dispatch = forge_dispatch();
assert_eq!(
dispatch.lease_ttl_millis, 3_600_000,
"an hour: a turn clones, reads, builds and tests"
);
assert_eq!(
dispatch.debounce_window_millis,
DispatcherConfig::default().debounce_window_millis,
"the rest stays the library's defaults"
);
}
#[test]
fn the_interactive_dispatcher_dispatches_now_and_leases_long() {
let dispatch = interactive_dispatch();
+1 -1
View File
@@ -213,7 +213,7 @@ fn bound(raw: &str) -> String {
/// The hostname: `/etc/hostname`'s first line, else the `hostname`
/// command, else a stand-in — the file is not portable and the command
/// is not guaranteed, so absence is a report line.
pub(crate) fn hostname() -> String {
fn hostname() -> String {
if let Ok(raw) = std::fs::read_to_string("/etc/hostname") {
let name = bound(&raw);
if !name.is_empty() {
+4 -5
View File
@@ -32,18 +32,17 @@
use std::path::PathBuf;
use std::sync::Arc;
use rhema_autonomous_agent::Source;
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_autonomous_agent::{Allowlist, Source, ToolRegistry};
use rhema_core::ToolResolver;
use rhema_forge_integration::ForgeKind;
use rhema_rsd::{Dispatcher, ResourceKey, SystemClock};
use crate::consents::WaitBridge;
use crate::daemon::ClawError;
use crate::forge::ForgeSource;
use crate::hub::EventHub;
use crate::toolkit::{Allowlist, ToolRegistry};
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_forge_integration::ForgeKind;
/// The store handles the standard set is assembled over. One struct,
/// so a new extension is a field plus a constructor line, not another
+25 -258
View File
@@ -24,10 +24,9 @@ use std::sync::{Arc, Mutex, PoisonError};
use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_forge_integration::forge_key_fn;
use rhema_forge_integration::triage::{self, Role, Triage};
use rhema_forge_integration::triage::{self, Triage};
use rhema_forge_integration::{
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, NotificationReason, RepoRef,
Timestamp, Watcher, register_forge,
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, Timestamp, Watcher, register_forge,
};
use rhema_identity::{IdentityStore, SecretKind};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
@@ -219,6 +218,8 @@ pub struct ForgeSource {
/// The device-notification queue a [`Triage::Surface`] lands in.
notifications: Arc<crate::notifications::NotificationStore>,
clients: Mutex<HashMap<ClientKey, Arc<dyn Forge>>>,
/// One notifications cursor per account id.
account_cursors: Mutex<HashMap<String, rhema_forge_integration::Timestamp>>,
}
impl ForgeSource {
@@ -243,6 +244,7 @@ impl ForgeSource {
accounts,
notifications,
clients: Mutex::new(HashMap::new()),
account_cursors: Mutex::new(HashMap::new()),
}
}
@@ -388,7 +390,7 @@ impl ForgeSource {
if let Some(since) = stored.as_deref().and_then(Timestamp::parse) {
return Ok(since);
}
let now = Timestamp::from_epoch_millis(SystemClock.now_millis() as i64)
let now = Timestamp::from_epoch_millis(SystemClock.now_millis())
.ok_or_else(|| SourceError::Backend("cannot spell this instant".to_owned()))?;
self.store
.set_cursor(SCOPE_REPO, &record.forge, &record.repo, now.raw())
@@ -498,18 +500,12 @@ impl ForgeSource {
};
let client = record_client(kind, watch.host.as_deref(), &credential);
// The cursor this poll asks from: the durable one when the watch
// has one, absent on its first pass — an unread feed is news. An
// unreadable row reads as absent, like a repo watch's: a
// corrupted cursor must not fire a backlog. The map that used to
// hold it was per-process, so every restart asked from nothing
// and re-decided the whole unread feed; the row is what a
// restart resumes from.
let stored = self
.store
.cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id)
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
let since = stored.as_deref().and_then(Timestamp::parse);
let since = self
.account_cursors
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&watch.account_id)
.cloned();
let page = client
.notifications(since.as_ref())
.await
@@ -517,7 +513,7 @@ impl ForgeSource {
let now = SystemClock.now_millis();
let mut fed = 0;
for notification in &page.notifications {
match claw_triage(notification) {
match triage::classify(notification) {
Triage::Ignore => {}
Triage::Surface => {
if let Err(err) = self.notifications.push(
@@ -568,55 +564,17 @@ impl ForgeSource {
fed += 1;
}
}
// The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning
// it, and the durable cursor is what stops the poll asking
// for it again. Deciding without consuming is a loop: a row
// the forge still considers unread comes back every pass —
// re-decided and re-dispatched as a fresh turn for a thread
// that already has one — until the cursor passes it.
//
// Best-effort: an unread row costs a repeat, never a lost
// event, so a failed call is logged and the poll carries on.
if let Err(err) = client.mark_read(notification).await {
eprintln!(
"[claw] warning: mark-read of {} failed: {err}",
notification.id
);
}
}
// Advance the durable cursor to wherever this poll got to. The
// in-memory map this replaces was per-process: a restart that
// lost it replayed the whole unread feed. A failed write is one
// pass's replay — dedup ids absorb it — so it reads as a poll
// failure, like the repo watch's cursor does.
if let Some(cursor) = page.cursor {
self.store
.set_cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id, cursor.raw())
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
self.account_cursors
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(watch.account_id.clone(), cursor);
}
Ok(fed)
}
}
/// [`triage::classify`], plus the one reclassification a resident agent
/// owes its own name: an @-mention of the daemon is an ask.
///
/// The shared vocabulary reads a mention as [`Triage::Surface`] — right
/// for a consumer that only notifies its human, since a mention is not an
/// assignment. This daemon is the party named: somebody typed `@handle` on
/// a thread and is waiting for an answer, which is the same ask an
/// assignment is. Left as a surface, a mention would be a phone buzz and
/// nothing else — this loop never dispatches for a surface, so the turn
/// that reads the thread would never run and the mention would go
/// unanswered.
fn claw_triage(notification: &Notification) -> Triage {
match &notification.reason {
NotificationReason::Mention => Triage::Agent(Role::Implementer),
_ => triage::classify(notification),
}
}
/// The device-notification text a [`Triage::Surface`] lands: the reason
/// and the thread title, so the human can judge without opening the
/// forge.
@@ -661,7 +619,13 @@ mod tests {
.add("gitea", "acme/barn", Some(&server.uri()), "tok")
.expect("add");
let (dispatcher, accounts, notifications) = test_parts(store.clone());
let source = ForgeSource::new(&dispatcher, "gitea", store.clone(), accounts, notifications);
let source = ForgeSource::new(
&dispatcher,
"gitea",
store.clone(),
accounts,
notifications,
);
assert_eq!(
source.detect().await.expect("the pass runs"),
@@ -703,159 +667,13 @@ mod tests {
Some(cursor)
);
assert_eq!(
store
.health(SCOPE_REPO, "gitea", "acme/barn")
.expect("health reads")
store.health(SCOPE_REPO, "gitea", "acme/barn").expect("health reads")
.map(|health| health.consecutive_failures),
Some(0),
"the watch polled cleanly"
);
}
/// The account poll consumes what it decides. The feed is
/// at-least-once — the cursor never passes a row the forge still
/// considers unread, so a row that is triaged but not marked read
/// comes back with the same dedup id on the next pass, and every
/// pass dispatches a fresh turn for a thread that already has one.
#[tokio::test]
async fn a_triaged_account_notification_is_marked_read() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"id": 42188,
"unread": true,
"reason": "mention",
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": "https://api.github.com/repos/acme/widgets/pulls/142",
"type": "PullRequest"
},
"repository": { "full_name": "acme/widgets" }
}
])))
.mount(&server)
.await;
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let (dispatcher, accounts, notifications) = test_parts(store.clone());
// The store mints the id; the watch row is what names it.
let account = accounts
.put(rhema_identity::AccountDraft::new(
"forge bot",
"github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
))
.expect("account lands");
store
.add_account_watch("github", Some(&server.uri()), &account.id)
.expect("account watch lands");
let source = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
assert_eq!(
source.detect().await.expect("the pass runs"),
1,
"a mention dispatches a turn"
);
// The read route keys on the notification, not the thread.
let requests = server.received_requests().await.expect("recording is on");
let reads: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(reads.len(), 1, "one mark-read per triaged row");
assert_eq!(reads[0].url.path(), "/notifications/threads/42188");
}
/// The account cursor is durable. The pass that decides rows leaves
/// where it got to in the store, and a source built fresh over the
/// same store — the shape every restart takes — asks from that row
/// rather than from nothing: the in-memory map this replaces died
/// with the process, and every restart re-decided the whole unread
/// feed.
#[tokio::test]
async fn an_account_cursor_survives_a_restart() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"id": 42188,
"unread": true,
"reason": "mention",
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": "https://api.github.com/repos/acme/widgets/pulls/142",
"type": "PullRequest"
},
"repository": { "full_name": "acme/widgets" }
}
])))
.mount(&server)
.await;
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let (dispatcher, accounts, notifications) = test_parts(store.clone());
let account = accounts
.put(rhema_identity::AccountDraft::new(
"forge bot",
"github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
))
.expect("account lands");
store
.add_account_watch("github", Some(&server.uri()), &account.id)
.expect("account watch lands");
let source = ForgeSource::new(
&dispatcher,
"github",
store.clone(),
accounts.clone(),
notifications.clone(),
);
source.detect().await.expect("the pass runs");
// Where the poll got to is in the store, spelled like the feed's
// own instants.
let cursor = store
.cursor(SCOPE_ACCOUNT, "github", &account.id)
.expect("cursor reads")
.expect("the pass persisted a cursor");
assert_eq!(
cursor, "2026-10-05T12:00:00Z",
"the cursor is the newest instant the poll saw"
);
// The restart: a fresh source over the same store polls from the
// row, not from nothing.
let reborn = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
reborn.detect().await.expect("the restarted pass runs");
let requests = server.received_requests().await.expect("recording is on");
let polls: Vec<_> = requests
.iter()
.filter(|request| {
request.method.as_str() == "GET" && request.url.path() == "/notifications"
})
.collect();
assert_eq!(polls.len(), 2, "one poll per pass");
let since = polls[1].url.query_pairs().find_map(|(key, value)| {
if key.as_ref() == "since" {
Some(value.into_owned())
} else {
None
}
});
assert_eq!(
since.as_deref(),
Some(cursor.as_str()),
"the restart asks from the durable cursor"
);
}
/// The parts a test source polls through, all in memory.
fn test_parts(
store: Arc<ClawStore>,
@@ -1139,7 +957,6 @@ mod tests {
title: Some("Add the flange".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
};
let payload = |notification: &Notification| {
@@ -1171,54 +988,4 @@ mod tests {
});
assert_eq!(key.as_str(), "github:issue:acme/widgets#142");
}
/// The notification fixture the reclassification tests classify: one
/// plain issue thread, the reason the only thing that varies.
fn triaged_notification(reason: NotificationReason) -> Notification {
Notification {
id: format!("github:notification:1@{}", reason.as_str()),
reason,
repo: RepoRef::new("acme", "widgets"),
number: 7,
is_pr: false,
actor: Some("stranger".to_owned()),
title: Some("a title".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-11-21T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
}
}
/// A mention of the daemon is an ask: this daemon is the party named,
/// so the feed dispatches a turn that reads the thread — not a phone
/// buzz that leaves the mention unanswered.
#[test]
fn a_mention_of_the_daemon_dispatches_instead_of_surfacing() {
assert_eq!(
claw_triage(&triaged_notification(NotificationReason::Mention)),
Triage::Agent(Role::Implementer),
"somebody addressed the daemon and is waiting"
);
}
/// Every other reason keeps the shared vocabulary's verdict — the
/// reclassification is one row, not a second opinion.
#[test]
fn every_other_reason_keeps_the_shared_verdict() {
for reason in [
NotificationReason::ReviewRequested,
NotificationReason::Assigned,
NotificationReason::ReviewFeedback,
NotificationReason::Author,
NotificationReason::CiActivity,
NotificationReason::Other("subscribed".to_owned()),
] {
assert_eq!(
claw_triage(&triaged_notification(reason.clone())),
triage::classify(&triaged_notification(reason.clone())),
"{} keeps the base verdict",
reason.as_str()
);
}
}
}
-472
View File
@@ -1,472 +0,0 @@
//! The workspace git identity: `user.name` and `user.email` in the
//! daemon user's global git config, written at boot so every commit a
//! workspace makes carries the agent as its author — before any
//! conversation happened, on a machine nobody onboarded.
//!
//! Like the environment report this is deterministic boot code, and
//! like every boot probe its failure is one log line, never a failed
//! boot. Each field resolves from three sources, first set wins: the
//! config file's `git` section (the operator's choice), the agent's
//! own presentation identity (`identity.name`, `identity.email` —
//! what onboarding and the settings page write), then defaults. The
//! values land in the git config the daemon user's `git` reads, so
//! thread workspaces, chat scratch repos, and anything the agent
//! inits itself all inherit them.
//!
//! The write is guarded. The settings store remembers the last pair
//! the daemon wrote; boot rewrites a field only when git's global
//! scope still holds that pair, or nothing at all. A value anyone
//! else set wins outright — the daemon is a tenant of its user's
//! machine, not the owner of its git config. The scope is git's own:
//! reads and writes run through `git config --global`, so whatever
//! file the user's git actually reads — `.gitconfig`, the XDG
//! `~/.config/git/config`, or the `GIT_CONFIG_GLOBAL` override — is
//! what the guard sees, not a guessed path that shadows it. An ssh
//! sandbox runs git on another host, so it stays out of scope here:
//! those workspaces remain unprovisioned until a later story pushes
//! the values remotely.
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::config::{ClawConfig, GitIdentity};
use crate::identity::{AgentIdentity, IdentityStore};
use crate::settings::SettingsStore;
/// The fallback author name, when the config and the identity are
/// both silent. Lowercase on purpose: a stand-in, not a persona.
pub const DEFAULT_NAME: &str = "claw";
/// The settings keys recording the last pair the daemon wrote. The
/// guard reads them back on every boot; a mismatch means the field
/// was hand-edited and is left alone.
const WRITTEN_NAME: &str = "git_identity_written_name";
const WRITTEN_EMAIL: &str = "git_identity_written_email";
/// The per-call budget: a local `git config` is a file operation; the
/// budget only bounds a wedged `git`, like any other boot probe.
const GIT_BUDGET: Duration = Duration::from_secs(2);
/// One resolved field: the value and where it came from, for the boot
/// log line.
pub struct ResolvedField {
/// The resolved value, ready for the config file.
pub value: String,
/// Where it came from: `config`, `identity`, or `default`, for
/// the boot log line.
pub source: &'static str,
}
/// Resolves both fields: config, then identity, then defaults. The
/// fields resolve independently — a config name beside an identity
/// email is a legal pair.
pub fn resolve(
git: Option<&GitIdentity>,
identity: &AgentIdentity,
hostname: &str,
) -> (ResolvedField, ResolvedField) {
let field = |configured: Option<String>, presented: Option<String>, default: String| {
if let Some(value) = configured {
ResolvedField {
source: "config",
value,
}
} else if let Some(value) = presented {
ResolvedField {
source: "identity",
value,
}
} else {
ResolvedField {
source: "default",
value: default,
}
}
};
let name = field(
git.and_then(|git| git.name.clone()),
identity.name.clone(),
DEFAULT_NAME.to_owned(),
);
let email = field(
git.and_then(|git| git.email.clone()),
identity.email.clone(),
format!("{}@{}", DEFAULT_NAME, hostname),
);
(name, email)
}
/// The boot entry point: opens the stores the daemon built, resolves,
/// provisions, and returns the log line. Nothing here is fatal — every
/// failure becomes the line the caller prints.
pub fn boot(config: &ClawConfig) -> String {
let outcome = (|| -> Result<String, String> {
// The scope rides the environment override when the caller set
// one — the tests' isolation — and is otherwise git's own
// global scope, resolved by git, not guessed here.
let scope = std::env::var("GIT_CONFIG_GLOBAL")
.ok()
.filter(|path| !path.trim().is_empty())
.map(PathBuf::from);
let db = config.db_path().map_err(|err| err.to_string())?;
let settings = Arc::new(SettingsStore::open(&db).map_err(|err| err.to_string())?);
let dir = db
.parent()
.ok_or("the database has no parent directory")?
.join("identity");
let who = IdentityStore::new(settings.clone(), dir)
.get()
.map_err(|err| err.to_string())?;
Ok(provision(
scope.as_deref(),
config.git.as_ref(),
&who,
&settings,
))
})();
outcome.unwrap_or_else(|reason| format!("git identity not provisioned: {reason}"))
}
/// Provisions both fields into the git global scope — `scope`, when
/// given, pins `GIT_CONFIG_GLOBAL` for the child `git` calls (the
/// tests' isolation); otherwise git resolves its own. Returns the log
/// line. The guard is per field: a hand-edited name beside an email
/// the daemon wrote is updated on the email side and left alone on
/// the name side.
pub fn provision(
scope: Option<&Path>,
git: Option<&GitIdentity>,
identity: &AgentIdentity,
settings: &SettingsStore,
) -> String {
let (name, email) = resolve(git, identity, &crate::environment::hostname());
let mut parts = Vec::new();
field(
scope,
"user.name",
WRITTEN_NAME,
&name,
settings,
&mut parts,
);
field(
scope,
"user.email",
WRITTEN_EMAIL,
&email,
settings,
&mut parts,
);
format!("git identity: {}", parts.join(", "))
}
/// One field's guard, write, and log phrase:
/// - the config file holds someone else's value → kept, untouched;
/// - it already holds the resolved value → aligned (the marker too,
/// so a later resolution can still update it — a hand edit that
/// matches what the daemon resolved counts as the daemon's);
/// - it is unset, or it is exactly what the daemon wrote last time →
/// written, and the marker follows.
fn field(
scope: Option<&Path>,
key: &str,
setting_key: &str,
want: &ResolvedField,
settings: &SettingsStore,
parts: &mut Vec<String>,
) {
let mut summary = |action: String| {
parts.push(format!(
"{} {:?} from {}: {}",
key.rsplit_once('.').map(|(_, n)| n).unwrap_or(key),
want.value,
want.source,
action
))
};
let written = settings.get(setting_key).ok().flatten();
match read(scope, key) {
Err(reason) => summary(format!("unreadable ({reason}), left alone")),
Ok(Some(current))
if Some(current.as_str()) != written.as_deref() && current != want.value =>
{
summary("kept a hand-edited value".to_owned())
}
Ok(Some(current)) if current == want.value => {
if written.as_deref() != Some(current.as_str()) {
record(settings, setting_key, &current);
}
summary("already current".to_owned())
}
Ok(_) => match write(scope, key, &want.value) {
Ok(()) => {
record(settings, setting_key, &want.value);
summary("wrote".to_owned())
}
Err(reason) => summary(format!("not written ({reason})")),
},
}
}
/// Records the pair the daemon wrote, so the next boot can tell its
/// own values from a hand edit. A store failure leaves the guard
/// conservative: the field reads as foreign next boot and is kept.
fn record(settings: &SettingsStore, key: &str, value: &str) {
let _ = settings.set(key, value);
}
/// One `git` invocation: fixed argv, no shell, stdin null, a short
/// budget. The exit code travels — a read's `1` means the key is
/// unset, which is an answer, not an error.
enum GitRun {
Completed { code: i32, stdout: String },
NotFound,
TimedOut,
}
fn git_scoped(scope: Option<&Path>, args: &[&str]) -> GitRun {
let mut command = Command::new("git");
command.args(args);
if let Some(path) = scope {
// The child only: the caller's environment stays untouched,
// and parallel scopes in tests cannot see each other.
command.env("GIT_CONFIG_GLOBAL", path);
}
let mut child = match command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return GitRun::NotFound,
Err(_) => return GitRun::NotFound,
};
let deadline = Instant::now() + GIT_BUDGET;
let code = loop {
match child.try_wait() {
Ok(Some(status)) => break status.code(),
Ok(None) if Instant::now() >= deadline => break None,
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => break None,
}
};
let Some(code) = code else {
let _ = child.kill();
let _ = child.wait();
return GitRun::TimedOut;
};
let stdout = child
.stdout
.take()
.map(|mut pipe| {
let mut buf = Vec::new();
use std::io::Read;
let _ = pipe.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
})
.unwrap_or_default();
GitRun::Completed { code, stdout }
}
/// Reads one key from the git global scope: `Some` when set, `None`
/// when unset (git exits 1 for that), an error when the read cannot be
/// trusted (a missing git, a multi-valued key) — and an untrusted read
/// is never written over. Git resolves the scope itself, so the value
/// seen is the value a commit would carry, from whichever file holds
/// it.
fn read(scope: Option<&Path>, key: &str) -> Result<Option<String>, String> {
match git_scoped(scope, &["config", "--global", "--get", key]) {
GitRun::Completed { code: 0, stdout } => {
Ok(Some(stdout.trim().to_owned()).filter(|value| !value.is_empty()))
}
GitRun::Completed { code: 1, .. } => Ok(None),
GitRun::Completed { code, .. } => Err(format!("exit {code}")),
GitRun::NotFound => Err("git not found".to_owned()),
GitRun::TimedOut => Err("no exit in time".to_owned()),
}
}
/// Writes one key into the git global scope, replacing every value
/// the key carries (`--replace-all` keeps the field single-valued even
/// over a strange starting file). Git picks the file — its own write
/// rule, the XDG config when that is the established one, `.gitconfig`
/// otherwise, the `GIT_CONFIG_GLOBAL` the scope pins.
fn write(scope: Option<&Path>, key: &str, value: &str) -> Result<(), String> {
match git_scoped(scope, &["config", "--global", "--replace-all", key, value]) {
GitRun::Completed { code: 0, .. } => Ok(()),
GitRun::Completed { code, .. } => Err(format!("exit {code}")),
GitRun::NotFound => Err("git not found".to_owned()),
GitRun::TimedOut => Err("no exit in time".to_owned()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::GitIdentity;
use crate::identity::IdentityTexts;
/// The fixture: a temp file standing in as the git global scope
/// (`GIT_CONFIG_GLOBAL` for the child `git` calls), an in-memory
/// settings store, and a fresh store handle per test.
struct Fixture {
file: PathBuf,
settings: SettingsStore,
#[allow(dead_code)]
dir: tempfile::TempDir,
}
fn fixture() -> Fixture {
let dir = tempfile::tempdir().expect("tempdir");
let file = dir.path().join("gitconfig");
Fixture {
file,
settings: SettingsStore::in_memory().expect("the store opens"),
dir,
}
}
/// Provisions inside the fixture's scope.
fn run(fix: &Fixture, git: Option<&GitIdentity>, who: &AgentIdentity) -> String {
provision(Some(&fix.file), git, who, &fix.settings)
}
fn identity(name: Option<&str>, email: Option<&str>) -> AgentIdentity {
let store_settings = crate::settings::SettingsStore::in_memory().expect("the store opens");
let images = tempfile::tempdir().expect("tempdir");
let store = IdentityStore::new(Arc::new(store_settings), images.path().join("identity"));
store
.set_texts(&IdentityTexts {
name: name.map(str::to_owned),
mark: None,
initials: None,
tagline: None,
signoff: None,
email: email.map(str::to_owned),
})
.expect("the identity saves")
}
fn config_git(name: Option<&str>, email: Option<&str>) -> Option<GitIdentity> {
Some(GitIdentity {
name: name.map(str::to_owned),
email: email.map(str::to_owned),
})
}
fn value_of(file: &Path, key: &str) -> Option<String> {
read(Some(file), key).expect("the key reads")
}
#[test]
fn defaults_land_when_nothing_is_set() {
let fix = fixture();
let who = identity(None, None);
let line = run(&fix, None, &who);
assert_eq!(value_of(&fix.file, "user.name").as_deref(), Some("claw"));
assert_eq!(
value_of(&fix.file, "user.email").as_deref(),
Some(format!("claw@{}", crate::environment::hostname()).as_str()),
);
assert!(line.contains("from default"), "{line}");
assert!(line.contains("wrote"), "{line}");
}
#[test]
fn config_beats_identity_beats_default() {
let fix = fixture();
let who = identity(Some("Kosmos"), Some("kosmos@example.net"));
run(&fix, config_git(Some("Bot"), None).as_ref(), &who);
assert_eq!(value_of(&fix.file, "user.name").as_deref(), Some("Bot"));
assert_eq!(
value_of(&fix.file, "user.email").as_deref(),
Some("kosmos@example.net"),
"the fields resolve independently"
);
let other = fixture();
run(&other, None, &who);
assert_eq!(
value_of(&other.file, "user.name").as_deref(),
Some("Kosmos")
);
}
#[test]
fn a_hand_edited_value_wins_and_is_recorded_as_foreign() {
let fix = fixture();
write(Some(&fix.file), "user.name", "The Operator").expect("the seed writes");
let who = identity(Some("Kosmos"), None);
let line = run(&fix, None, &who);
assert_eq!(
value_of(&fix.file, "user.name").as_deref(),
Some("The Operator")
);
assert!(line.contains("kept"), "{line}");
// The daemon did not write it, so no marker was recorded.
assert_eq!(fix.settings.get(WRITTEN_NAME).unwrap(), None);
// The unset email beside it still provisions: the guard is per field.
assert!(value_of(&fix.file, "user.email").is_some());
}
#[test]
fn reruns_update_what_the_daemon_wrote() {
let fix = fixture();
let first = identity(Some("Kosmos"), None);
run(&fix, None, &first);
let second = identity(Some("Kosmos Prime"), None);
let line = run(&fix, None, &second);
assert_eq!(
value_of(&fix.file, "user.name").as_deref(),
Some("Kosmos Prime"),
"the daemon rewrites its own values"
);
assert!(line.contains("wrote"), "{line}");
// And a rerun over an already-current pair is a no-op.
let before = std::fs::read_to_string(&fix.file).expect("the file reads");
let line = run(&fix, None, &second);
let after = std::fs::read_to_string(&fix.file).expect("the file reads");
assert_eq!(before, after, "nothing to do, nothing written");
assert!(line.contains("already current"), "{line}");
}
#[test]
fn a_config_change_flows_through_on_the_next_boot() {
let fix = fixture();
let who = identity(None, None);
run(
&fix,
config_git(Some("Bot"), Some("bot@example.net")).as_ref(),
&who,
);
run(
&fix,
config_git(Some("Renamed"), Some("moved@example.net")).as_ref(),
&who,
);
assert_eq!(value_of(&fix.file, "user.name").as_deref(), Some("Renamed"));
assert_eq!(
value_of(&fix.file, "user.email").as_deref(),
Some("moved@example.net"),
);
}
#[test]
fn a_hand_edit_that_matches_the_resolution_counts_as_the_daemons() {
let fix = fixture();
let who = identity(Some("Kosmos"), None);
write(Some(&fix.file), "user.name", "Kosmos").expect("the seed writes");
run(&fix, None, &who);
// The marker was aligned, so a later resolution updates the field.
let renamed = identity(Some("Kosmos II"), None);
run(&fix, None, &renamed);
assert_eq!(
value_of(&fix.file, "user.name").as_deref(),
Some("Kosmos II")
);
}
}
+44 -511
View File
@@ -10,7 +10,7 @@
//!
//! Session continuity rides the dispatcher, not the filesystem: the
//! agent's session JSON is stashed into `ctx.session.core.driver_state`
//! before the run returns and restored with [`HostAgent::from_session`]
//! before the run returns and restored with [`CodingAgent::from_session`]
//! on the next dispatch of the same key, so a resumed thread keeps its
//! conversation. Commit-before-execute rides it too: the run installs the
//! context's commit hook, so the intent is in the store before the first
@@ -23,11 +23,11 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, Surface};
use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore;
use rhema_agent_tools::AllowAll;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_coding_agent::{CodingAgent, CodingAgentConfig};
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
use rhema_forge_integration::ForgeKind;
use rhema_forge_integration::triage::Role;
@@ -35,13 +35,10 @@ use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode,
parse_key,
};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_identity::IdentityStore;
use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell;
use crate::backends::BackendRegistry;
use crate::sandbox::SandboxState;
/// The handler's tool permissions, resolved deterministically before the
/// agent's first step (spec §8) — never by the model, never mid-run. V1
@@ -50,25 +47,14 @@ use crate::sandbox::SandboxState;
/// [`Role`] is the seam it hangs on, a reviewer dispatch deserving a
/// narrower policy than an implementer's — and a policy that refuses the
/// shell refuses the run (see [`ClawHandler::dispatch`]).
fn allowlist() -> crate::toolkit::Allowlist {
crate::toolkit::Allowlist::permissive()
fn allowlist() -> rhema_autonomous_agent::Allowlist {
rhema_autonomous_agent::Allowlist::permissive()
}
/// The coding agent over one watch: a provider, a model, a workspace
/// root, and the watch table the dispatch keys resolve through — live,
/// so a watch added at runtime is answerable without a restart.
///
/// The agent is the resident's: every dispatch renders the same
/// bootstrap prompt the chat surfaces render — SOUL.md, USER.md, the
/// environment report — over the thread's workspace, so the claw that
/// answers a review or a mention is the character the user chats with,
/// not a nameless delegate. The tools stay the coding set (shell,
/// vision, MCP); the chat-only rosters (memory, notifications, the
/// key-scoped asks) do not ride a forge dispatch.
pub struct ClawHandler {
/// The bootstrap store the persona renders from, per dispatch, so
/// a SOUL.md the chat wrote is live on the next forge answer.
bootstrap: Arc<Bootstrap>,
/// The deployment's providers and the active pair, read per dispatch.
backends: Arc<BackendRegistry>,
/// Whether the sessions run the bounded request view (the config's
@@ -84,17 +70,7 @@ pub struct ClawHandler {
/// agent shell: the daemon URL, the scoped agent token, the tools'
/// bin dir on PATH. Empty when the config issues no agent token.
tool_env: std::collections::BTreeMap<String, String>,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per dispatch.
sandbox: Option<Arc<SandboxState>>,
/// The abort registry the sessions' abort route signals: a live
/// turn cut at its await stashes what it committed and ends the
/// dispatch as superseded, its comment never posted (see
/// [`crate::abort`]). Private by default — a handler nobody shared
/// a registry with never receives a signal — and shared through
/// [`ClawHandler::with_abort`].
abort: Arc<crate::abort::AbortRegistry>,
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
clients: Mutex<HashMap<String, Arc<dyn Forge>>>,
}
impl ClawHandler {
@@ -105,7 +81,6 @@ impl ClawHandler {
workspace_root: impl Into<PathBuf>,
watches: Arc<ClawStore>,
accounts: Arc<dyn IdentityStore>,
bootstrap: Arc<Bootstrap>,
transcript: bool,
tool_env: std::collections::BTreeMap<String, String>,
) -> Self {
@@ -115,29 +90,11 @@ impl ClawHandler {
workspace_root: workspace_root.into(),
watches,
accounts,
bootstrap,
tool_env,
sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
clients: Mutex::new(HashMap::new()),
}
}
/// Shares the deployment's sandbox choice: a forge turn's commands
/// run where it says, seeded from the thread's host workspace.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// Shares the abort registry with the HTTP surface: the abort route
/// signals it, and every forge dispatch this handler runs listens
/// on it.
pub fn with_abort(mut self, abort: Arc<crate::abort::AbortRegistry>) -> Self {
self.abort = abort;
self
}
/// The forge client a dispatch key answers to:
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
/// table at dispatch time — the table is the source of truth, not a
@@ -163,18 +120,6 @@ impl ClawHandler {
key: &ResourceKey,
as_account: Option<&str>,
) -> Result<Arc<dyn Forge>, String> {
Ok(self.watch_client(key, as_account)?.forge.clone())
}
/// [`Self::watch_forge_as`] with the handle the credential speaks as
/// kept beside the client: the mention gate needs to recognize its own
/// name, and asking the forge is a request worth spending once per
/// credential, not once per dispatch.
fn watch_client(
&self,
key: &ResourceKey,
as_account: Option<&str>,
) -> Result<Arc<WatchClient>, String> {
let watch = watch_key(key)
.ok_or_else(|| format!("resource key {key} is not a forge thread key"))?;
let (forge, repo) = watch
@@ -247,7 +192,7 @@ impl ClawHandler {
kind: ForgeKind,
host: Option<&str>,
credential: &WatchCredential,
) -> Arc<WatchClient> {
) -> Arc<dyn Forge> {
// Everything that changes the client: the kind, its host, and the
// credential — the login included, since one value sent two ways
// is two credentials.
@@ -261,10 +206,7 @@ impl ClawHandler {
let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner);
clients
.entry(cache_key)
.or_insert_with(|| {
let forge = record_client(kind, host, credential);
Arc::new(WatchClient::new(forge, credential.login.clone()))
})
.or_insert_with(|| record_client(kind, host, credential))
.clone()
}
@@ -282,22 +224,7 @@ impl ClawHandler {
// that account — a thread the account's feed delivered may have no
// repo watch row at all.
let news = self.drain_news(ctx, &key).await?;
let client = self.watch_client(&ctx.key, delivery_account(&news))?;
// The mention gate, before anything is fetched or run: the news is
// already drained, and this decides whether it asks anything of
// the daemon at all.
let handle = client.handle().await;
if handle.is_none() && news.iter().any(|item| matches!(item, InboxNews::Event(_))) {
eprintln!(
"[claw] warning: {key}: the forge would not name this credential; \
every event on the watch dispatches"
);
}
if !addressed(&news, handle.as_deref()) {
return Ok(Outcome::Superseded);
}
let forge = client.forge.clone();
let forge = self.watch_forge_as(&ctx.key, delivery_account(&news))?;
let snapshot = forge
.snapshot(&repo, thread_kind, number)
@@ -324,28 +251,10 @@ impl ClawHandler {
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
let mut sink = TurnSink;
// The abort listener rides the turn: a signal drops the future
// at its current await — a streaming request, or a running
// shell command, whose child dies with the drop. What the turn
// committed so far is already the session (the commit hook),
// so the stash below hands it to the next dispatch.
let mut abort = self.abort.listen(&key);
let turned = tokio::select! {
output = agent.turn(prompt, &mut sink) => {
Some(output.map_err(|err| format!("turn for {key} failed: {err}")))
}
_ = abort.wait() => None,
};
let output = match turned {
Some(output) => output?,
None => {
// Cut, not failed: the thread gets no half-answer, and
// the session keeps whatever the turn committed.
ctx.session.core.driver_state = serde_json::to_value(agent.session())
.map_err(|err| format!("session for {key} does not serialize: {err}"))?;
return Ok(Outcome::Superseded);
}
};
let output = agent
.turn(prompt, &mut sink, Arc::new(AllowAll))
.await
.map_err(|err| format!("turn for {key} failed: {err}"))?;
// Stash before posting: the turn's work survives a failed comment.
ctx.session.core.driver_state = serde_json::to_value(agent.session())
@@ -390,87 +299,36 @@ impl ClawHandler {
ctx: &SessionContext,
workspace: &Path,
key: &str,
) -> Result<HostAgent, String> {
) -> Result<CodingAgent, String> {
let (provider, model) = self.backends.current();
let config = self.agent_config(provider, &model, workspace, key)?;
let config = self.agent_config(&model, workspace);
let agent = match &ctx.session.core.driver_state {
// A never-dispatched key carries no stash: start clean.
serde_json::Value::Null => HostAgent::new(config),
serde_json::Value::Null => CodingAgent::new(provider, config),
stashed => {
let session: Session = serde_json::from_value(stashed.clone())
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
HostAgent::from_session(config, session)
CodingAgent::from_session(provider, config, session)
}
};
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
}
/// The config one dispatch's agent runs on: the resident's own
/// prompt — the bootstrap template rendered per dispatch over the
/// thread's workspace, SOUL.md and USER.md live — with the bounded
/// request view when the config has it on and a remote shell when
/// the sandbox choice says so. A forge thread answers for as long
/// as the thread lives; without the view its history would ride
/// whole on every step.
fn agent_config(
&self,
provider: Arc<dyn rhema_core::ModelProvider>,
model: &str,
workspace: &Path,
key: &str,
) -> Result<HostAgentConfig, String> {
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(workspace),
None => workspace.to_path_buf(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
/// The config one dispatch's agent runs on: the default coding
/// agent's, with the bounded request view when the config has it on.
/// A forge thread answers for as long as the thread lives; without
/// the view its history would ride whole on every step.
fn agent_config(&self, model: &str, workspace: &Path) -> CodingAgentConfig {
let mut config = CodingAgentConfig::new(model, workspace);
// Write the resolved value, not an override: the coding agent's
// own default is on now, and the config's `false` must win.
config.transcript = self
.transcript
.then(rhema_transcript::TranscriptSettings::default);
config.shell_env = self.tool_env.clone();
// The prompt names the workspace the model sees and documents
// exactly what the request advertises: the shell built-ins plus
// the transcript's zoom when the view is on — the same assembly
// the host agent does for its own default prompt. A verbatim
// prompt ignores the config's template sections, so the vision
// and MCP documentation render here from the same wired values;
// a remote sandbox wires neither.
let mut vision = None;
let mut mcp = Vec::new();
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display.clone(),
sandbox.executor(workspace.to_path_buf()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
vision = config.vision.clone();
mcp = config.mcp_servers.clone();
}
}
let mut specs = ShellTools::builtin_specs();
if config.transcript.is_some() {
specs.push(rhema_transcript::Zoom::spec());
}
config.system = Some(
crate::bootstrap::render_system(
DEFAULT_SYSTEM_MD,
key,
&display,
&self.bootstrap,
&specs,
vision.as_deref(),
&mcp,
Surface::Forge,
)
.map_err(|err| format!("cannot render the forge system prompt for {key}: {err}"))?,
);
Ok(config)
config
}
/// The per-thread workspace: one directory under the root, created on
@@ -485,45 +343,6 @@ impl ClawHandler {
}
}
/// One cached forge client, with the handle it speaks as.
///
/// The credential a watch resolves carries a login only when an account
/// identity supplied the token; a token pasted into the watch row, or a
/// forge environment variable, names nobody. The mention gate still has to
/// recognize the daemon's own name — to see an @-mention in a body, and to
/// leave its own replies alone — so the forge is asked who it is, once per
/// credential, the first time a dispatch needs to know.
struct WatchClient {
forge: Arc<dyn Forge>,
/// The login the credential itself carries.
login: Option<String>,
/// The forge's own answer, asked at most once.
viewer: OnceCell<Option<String>>,
}
impl WatchClient {
fn new(forge: Arc<dyn Forge>, login: Option<String>) -> Self {
Self {
forge,
login,
viewer: OnceCell::new(),
}
}
/// The handle this client speaks as: the credential's when it has one,
/// else the forge's own answer. `None` when neither can name it — a
/// forge that is down, or a backend with no `/user`.
async fn handle(&self) -> Option<String> {
if let Some(login) = &self.login {
return Some(login.clone());
}
self.viewer
.get_or_init(|| async { self.forge.viewer_login().await.ok().flatten() })
.await
.clone()
}
}
#[async_trait]
impl Handler for ClawHandler {
async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
@@ -621,60 +440,6 @@ fn delivery_account(news: &[InboxNews]) -> Option<&str> {
})
}
/// Whether `news` asks anything of the daemon — the mention gate.
///
/// A triaged notification answered this question on the way in: the
/// notifications feed handed the row over because it was assigned, a
/// review was requested, or someone @-mentioned the account, and
/// [`triage`](rhema_forge_integration::triage) let it through. It always
/// runs.
///
/// A plain repo event has been through nothing: a repo watch sees every
/// issue, pull request, review and comment on the repository. Running a
/// turn for each of them would burn a model call per comment and post an
/// unasked-for reply on threads nobody addressed the daemon in — the
/// difference between watching a repository and answering it. So a plain
/// event runs only when it addresses the daemon: a body that names the
/// handle we speak as, written by somebody else.
///
/// With no handle to look for, nothing is gated: a filter that silently
/// turns a watch off is worse than one that occasionally over-answers, and
/// the dispatch says so in the log.
fn addressed(news: &[InboxNews], handle: Option<&str>) -> bool {
if news
.iter()
.any(|news| matches!(news, InboxNews::Notified { .. }))
{
return true;
}
let Some(handle) = handle else {
return true;
};
news.iter().any(|news| match news {
InboxNews::Notified { .. } => true,
InboxNews::Event(event) => mentions(event, handle),
})
}
/// Whether `event` addresses `handle`: its body names `@handle`, and the
/// event is not the daemon's own writing. Our replies quote the mentions
/// they answer, so an event written by the handle counts as addressed by
/// nobody — otherwise every answer would feed the next turn.
fn mentions(event: &ForgeEvent, handle: &str) -> bool {
let own = event
.actor
.as_deref()
.is_some_and(|actor| actor.eq_ignore_ascii_case(handle));
if own {
return false;
}
let Some(body) = event.body.as_deref() else {
return false;
};
let needle = format!("@{}", handle.to_lowercase());
body.to_lowercase().contains(needle.as_str())
}
/// The batch's dominant role, for the prompt's persona framing:
/// implementing subsumes reviewing — a batch that asks for both is a
/// dispatch where the work is the point. Plain events imply no persona:
@@ -705,31 +470,30 @@ fn dominant_role(news: &[InboxNews]) -> Option<Role> {
}
}
/// The task framing a dispatched role opens the prompt with. Who is
/// answering lives in the system prompt — SOUL.md, the same file every
/// chat dispatch renders; this is only what the job is. The key stays
/// the thread, so a role change across dispatches is the session's
/// The persona framing a dispatched role opens the prompt with. The key
/// stays the thread, so a role change across dispatches is the session's
/// continuity, not a new conversation.
fn task_text(role: Role) -> &'static str {
fn persona_text(role: Role) -> &'static str {
match role {
Role::Reviewer => {
"This dispatch is a review request. Check the change out in the \
workspace when you can, read the diff, and judge it: correctness, tests, \
edge cases, fit with the surrounding code. Make the reply the review — \
findings first, ordered by severity, concrete and actionable; if there is \
nothing to fix, say so plainly and say what you checked."
"You are acting as this pull request's reviewer. Check the change \
out in the workspace when you can, read the diff, and judge it: correctness, \
tests, edge cases, fit with the surrounding code. Your final reply is the \
review — findings first, ordered by severity, concrete and actionable; if \
there is nothing to fix, say so plainly and say what you checked."
}
Role::Implementer => {
"This dispatch asks for work. Address the review feedback or the \
assigned issue by changing the code in the workspace — build and test what \
you change. Make the reply a short report of what you changed and why, or, \
when the whole change does not fit one turn, what landed now and the \
concrete plan for the rest."
"You are acting as this thread's implementer. Do the work the new \
activity asks for: address the review feedback or the assigned issue by \
changing the code in the workspace — build and test what you change. Your \
final reply is a short report of what you changed and why, or, when the \
whole change does not fit one turn, what landed now and the concrete plan \
for the rest."
}
}
}
/// The agent's prompt for one dispatch: the task framing (when the
/// The agent's prompt for one dispatch: the persona framing (when the
/// triage dispatched a role), the thread's standing state, the new news,
/// and the posting contract. The final assistant message is the comment
/// — everything else is orientation for the investigation.
@@ -742,7 +506,7 @@ fn build_prompt(
) -> String {
let mut prompt = String::new();
if let Some(role) = role {
prompt.push_str(task_text(role));
prompt.push_str(persona_text(role));
prompt.push_str("\n\n");
}
prompt.push_str(&format!(
@@ -948,89 +712,6 @@ mod tests {
);
}
/// A plain comment that names nobody is the thread's own traffic: the
/// gate stays shut, no turn runs, and nothing is posted.
#[test]
fn a_comment_that_names_nobody_does_not_address_the_daemon() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some("any progress on this?"),
))];
assert!(!addressed(&news, Some("kosmos")));
}
/// Addressed by name, in any case, anywhere in the body — the point of
/// the feature is that the human types a sentence, not a protocol.
#[test]
fn a_comment_that_names_the_handle_addresses_it() {
for body in [
"hey @kosmos can you take a look?",
"@Kosmos, this one is yours",
"I think @kosmos should decide",
] {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some(body),
))];
assert!(addressed(&news, Some("kosmos")), "body: {body}");
}
}
/// Our own replies quote the mention they answer, so they mention the
/// handle on every line — and must never feed the next turn.
#[test]
fn the_daemons_own_comments_never_address_it() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"kosmos",
Some("> @kosmos can you take a look?\n\nDone, see the branch."),
))];
assert!(!addressed(&news, Some("kosmos")));
// Case is the forge's, not the body's: the actor check folds it.
let news = [InboxNews::Event(event(
EventKind::Comment,
"Kosmos",
Some("@kosmos on it"),
))];
assert!(!addressed(&news, Some("kosmos")));
}
/// Thread-level events carry no body, so a mention gate can never pass
/// them: an opened or closed issue is context, not a request.
#[test]
fn an_event_with_no_body_is_not_a_request() {
let news = [InboxNews::Event(event(EventKind::Closed, "dave", None))];
assert!(!addressed(&news, Some("kosmos")));
}
/// A triaged notification was adjudicated on the way in — assigned, a
/// review requested, or a mention — so it runs regardless of bodies.
#[test]
fn a_triaged_notification_always_addresses_the_daemon() {
let notified = decode_news(&triaged_item(
Role::Implementer,
NotificationReason::Assigned,
))
.expect("the triaged payload decodes");
let news = [notified];
assert!(addressed(&news, Some("kosmos")));
assert!(addressed(&news, None), "a notification needs no handle");
}
/// With no handle to look for, the gate stays open: silently turning a
/// watch off is worse than over-answering, and the dispatch logs it.
#[test]
fn an_unnamed_credential_gates_nothing() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some("any progress?"),
))];
assert!(addressed(&news, None));
}
#[test]
fn thread_level_events_carry_no_body_and_the_prompt_says_so() {
let prompt = build_prompt(
@@ -1057,7 +738,6 @@ mod tests {
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-03T09:00:00Z",
"read_key": "42188",
"raw": {},
}))
.expect("notification fixture parses")
@@ -1164,12 +844,8 @@ mod tests {
Some(Role::Reviewer),
);
assert!(
prompt.contains("This dispatch is a review request"),
"task: {prompt}"
);
assert!(
!prompt.contains("You are acting as"),
"who answers is the system prompt's to say, not the task text's: {prompt}"
prompt.contains("acting as this pull request's reviewer"),
"persona: {prompt}"
);
assert!(
prompt.contains("notification (review_requested) on pull request #142"),
@@ -1185,7 +861,6 @@ mod tests {
Content::Text("on it".into()),
Content::Text(" — closing.".into()),
],
annotations: Default::default(),
};
assert_eq!(final_text(&message).as_deref(), Some("on it — closing."));
let tool_only = Message {
@@ -1196,19 +871,10 @@ mod tests {
args: serde_json::json!({}),
provider_data: serde_json::Value::Null,
})],
annotations: Default::default(),
};
assert_eq!(final_text(&tool_only), None, "no text, no reply");
}
/// A throwaway bootstrap store: the persona renders from it, the
/// shape the daemon assembles over the configured directory.
fn bootstrap() -> (tempfile::TempDir, Arc<Bootstrap>) {
let dir = tempfile::tempdir().expect("tempdir");
let store = Bootstrap::new(dir.path().join("bootstrap")).expect("store opens");
(dir, Arc::new(store))
}
#[test]
fn a_key_resolves_to_its_watch_entry_live_from_the_table() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
@@ -1225,13 +891,11 @@ mod tests {
)
.expect("constructs"),
);
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
true,
std::collections::BTreeMap::new(),
);
@@ -1292,13 +956,11 @@ mod tests {
)
.expect("constructs"),
);
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
accounts,
bootstrap,
true,
std::collections::BTreeMap::new(),
);
@@ -1352,14 +1014,11 @@ mod tests {
.expect("constructs"),
);
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
let provider = registry.current().0;
let (_dir, bootstrap) = bootstrap();
let on = ClawHandler::new(
registry.clone(),
"/tmp/w",
watches.clone(),
accounts.clone(),
bootstrap.clone(),
true,
std::collections::BTreeMap::new(),
);
@@ -1368,147 +1027,21 @@ mod tests {
"/tmp/w",
watches,
accounts,
bootstrap,
false,
std::collections::BTreeMap::new(),
);
assert!(
on.agent_config(
provider.clone(),
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7"
)
.expect("renders")
on.agent_config("m", Path::new("/tmp/w"))
.transcript
.is_some()
);
assert!(
off.agent_config(
provider,
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7"
)
.expect("renders")
off.agent_config("m", Path::new("/tmp/w"))
.transcript
.is_none()
);
}
#[test]
fn the_forge_dispatch_renders_the_residents_own_prompt() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
let registry = Arc::new(
crate::backends::BackendRegistry::new(
vec![crate::backends::Backend::headless(
"mock",
Arc::new(NoopProvider),
)],
None,
)
.expect("constructs"),
);
let (_dir, bootstrap) = bootstrap();
bootstrap
.save(
crate::bootstrap::BootstrapKind::Soul,
"I am claw: terse, warm, relentless.",
)
.expect("saves");
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
true,
std::collections::BTreeMap::new(),
);
let provider = handler.backends.current().0;
let config = handler
.agent_config(
provider,
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7",
)
.expect("renders");
let prompt = config.system.expect("the forge prompt is verbatim");
assert!(
prompt.contains("I am claw: terse, warm, relentless."),
"the soul rides the forge prompt: {prompt}"
);
assert!(
prompt.contains("the comment posted to the thread"),
"the forge branch of the reply contract: {prompt}"
);
assert!(
!prompt.contains("You answer chat here"),
"not the chat branch: {prompt}"
);
assert!(
prompt.contains("github:issue:acme/widgets#7"),
"the session key: {prompt}"
);
assert!(
prompt.contains("- bash |"),
"the shell tool is documented: {prompt}"
);
assert!(
prompt.contains("zoom"),
"the transcript view's tool is documented when the view is on: {prompt}"
);
assert!(
!prompt.contains("## Memory"),
"no memory tools, no memory section: {prompt}"
);
}
#[test]
fn a_fresh_house_never_sends_a_forge_dispatch_onboarding() {
let watches = Arc::new(ClawStore::in_memory().expect("store opens"));
let registry = Arc::new(
crate::backends::BackendRegistry::new(
vec![crate::backends::Backend::headless(
"mock",
Arc::new(NoopProvider),
)],
None,
)
.expect("constructs"),
);
// No SOUL.md, no USER.md — the state where chat onboards.
let (_dir, bootstrap) = bootstrap();
let handler = ClawHandler::new(
registry,
"/tmp/w",
watches,
Arc::new(rhema_identity::VolatileIdentityStore::new()),
bootstrap,
false,
std::collections::BTreeMap::new(),
);
let provider = handler.backends.current().0;
let config = handler
.agent_config(
provider,
"m",
Path::new("/tmp/w"),
"github:issue:acme/widgets#7",
)
.expect("renders");
let prompt = config.system.expect("the forge prompt is verbatim");
assert!(
!prompt.contains("## Onboarding"),
"a forge thread is nobody's first conversation: {prompt}"
);
assert!(
prompt.contains("(pending onboarding)"),
"the stub says so honestly: {prompt}"
);
}
#[test]
fn the_workspace_name_flattens_to_filesystem_safe_characters() {
assert_eq!(
+41 -407
View File
@@ -47,7 +47,7 @@ use rhema_claw_tools_contract::CONTRACT_HEADER;
use rhema_claw_tools_contract::CONTRACT_VERSION;
use rhema_core::ImageMediaType;
use rhema_rsd::{
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, Outcome, ResourceKey,
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, ResourceKey,
SqliteStore, Store,
};
use serde::{Deserialize, Deserializer};
@@ -55,13 +55,11 @@ use serde_json::{Value, json};
use tokio::sync::broadcast::error::RecvError;
use tokio_stream::wrappers::ReceiverStream;
use crate::abort::AbortRegistry;
use crate::backends::BackendRegistry;
use crate::bootstrap::Bootstrap;
use crate::hub::{EventHub, TurnEvent};
use crate::interactive::WireImage;
use crate::notifications::NotificationStore;
use crate::pause::PauseSet;
use crate::steer::SteerRegistry;
use crate::task_store::TaskStore;
use crate::watch_store::{ClawStore, validate_watch};
@@ -108,17 +106,6 @@ pub struct ClawState {
/// a chat message into a key whose turn is live cuts that turn
/// short (see [`crate::steer`]).
steer: Arc<SteerRegistry>,
/// The pause gate the pause/resume routes write and every driver's
/// ownership predicate reads: the keys whose dispatch is held (see
/// [`crate::pause`]).
pause: Arc<PauseSet>,
/// The abort registry the abort route signals: the live turn it
/// cuts ends as superseded (see [`crate::abort`]).
abort: Arc<AbortRegistry>,
/// The coding-job table the abort route reads when an idle
/// `job:` key's queue is dropped: the row is the jobs' truth, so
/// the row moves with the abort.
jobs: Arc<crate::job_store::CodingJobStore>,
backends: Arc<BackendRegistry>,
settings: Arc<crate::settings::SettingsStore>,
identity: Arc<crate::identity::IdentityStore>,
@@ -136,9 +123,6 @@ pub struct ClawState {
/// The phone tables: the command queue the device polls and the
/// reported state the ingest door feeds.
phone: Arc<crate::phone::PhoneStore>,
/// Where the agent's `bash` runs: the live choice `/v1/sandbox`
/// edits, shared with every handler.
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>,
/// The scoped agent token the client tools hold: a second bearer
/// answering only the contract's data routes (see
@@ -162,7 +146,7 @@ impl ClawState {
/// `agent_token`.
#[expect(
clippy::too_many_arguments,
reason = "twenty-one parts, each load-bearing"
reason = "eighteen parts, each load-bearing"
)]
pub fn new(
dispatcher: Arc<Dispatcher>,
@@ -175,9 +159,6 @@ impl ClawState {
bootstrap: Arc<Bootstrap>,
hub: Arc<EventHub>,
steer: Arc<SteerRegistry>,
pause: Arc<PauseSet>,
abort: Arc<AbortRegistry>,
jobs: Arc<crate::job_store::CodingJobStore>,
backends: Arc<BackendRegistry>,
settings: Arc<crate::settings::SettingsStore>,
identity: Arc<crate::identity::IdentityStore>,
@@ -186,7 +167,6 @@ impl ClawState {
bridge: Arc<crate::consents::WaitBridge>,
attachments: Arc<crate::attachments::AttachmentStore>,
phone: Arc<crate::phone::PhoneStore>,
sandbox: Arc<crate::sandbox::SandboxState>,
token: Option<String>,
agent_token: Option<String>,
ingest_token: Option<String>,
@@ -202,9 +182,6 @@ impl ClawState {
bootstrap,
hub,
steer,
pause,
abort,
jobs,
backends,
settings,
identity,
@@ -213,7 +190,6 @@ impl ClawState {
bridge,
attachments,
phone,
sandbox,
token,
agent_token,
ingest_token,
@@ -222,8 +198,7 @@ impl ClawState {
}
/// Every dispatch key with a record — interactive and forge alike,
/// both dispatchers share one store — with its status and whether
/// the pause gate holds it.
/// both dispatchers share one store — with its status.
pub fn sessions(&self) -> Result<Vec<Value>, DispatchError> {
let mut sessions = Vec::new();
for key in self.store.keys()? {
@@ -234,7 +209,6 @@ impl ClawState {
"revision": status.revision,
"inbox_depth": status.inbox_depth,
"last_outcome": status.last_outcome,
"paused": self.pause.is_paused(status.key.as_str()),
}));
}
Ok(sessions)
@@ -255,12 +229,6 @@ impl ClawState {
// leaves the transcript alone: the purge below is the one step this
// side cannot undo, and it must never run for a session the 409 kept.
let existed = self.dispatcher.forget(key)?;
// The pause hold goes with the record: a key re-created under
// the same name starts unpaused. Best-effort — the record and
// the transcript are already gone, so a settings-row failure
// here must not pretend the delete failed; a leftover row only
// holds a session that does not exist.
let _ = self.pause.resume(key.as_str());
// Then the history, unconditionally — including the `Ok(false)` path,
// where a record already gone left the transcript behind. Deleting
// that transcript is the repair: a retried DELETE finishes a half-done
@@ -290,17 +258,6 @@ impl ClawState {
&self.steer
}
/// The pause gate: the pause/resume routes write it, the sessions
/// listing reads it.
pub fn pause(&self) -> &PauseSet {
&self.pause
}
/// The abort registry: the abort route signals it.
pub fn aborts(&self) -> &AbortRegistry {
&self.abort
}
/// The configured model — the shim's echo default.
/// The backend registry: the provider list and the active pair.
pub fn backends(&self) -> &BackendRegistry {
@@ -332,11 +289,6 @@ impl ClawState {
pub fn watches(&self) -> &ClawStore {
&self.watches
}
/// Where the agent's `bash` runs.
pub fn sandbox(&self) -> &crate::sandbox::SandboxState {
&self.sandbox
}
}
/// The app router: `/healthz` open, `/v1` behind the bearer check when
@@ -345,9 +297,6 @@ pub fn router(state: ClawState) -> Router {
let v1 = Router::new()
.route("/sessions", get(sessions).post(sessions_create))
.route("/sessions/{key}", delete(session_delete))
.route("/sessions/{key}/pause", post(session_pause))
.route("/sessions/{key}/resume", post(session_resume))
.route("/sessions/{key}/abort", post(session_abort))
.route(
"/sessions/{key}/messages",
post(messages).layer(axum::extract::DefaultBodyLimit::max(MAX_MESSAGE_BODY_BYTES)),
@@ -394,7 +343,6 @@ pub fn router(state: ClawState) -> Router {
)
.route("/providers/{id}", delete(providers_remove))
.route("/providers/{id}/models", get(providers_models))
.route("/sandbox", get(sandbox_get).put(sandbox_put))
.route(
"/chat/completions",
post(crate::openai::chat_completions)
@@ -674,201 +622,6 @@ async fn session_delete(State(state): State<ClawState>, Path(key): Path<String>)
}
}
/// The shared shape of the pause/resume routes' answer.
fn pause_answer(key: &ResourceKey, paused: bool) -> Response {
(
StatusCode::OK,
Json(json!({ "key": key.as_str(), "paused": paused })),
)
.into_response()
}
/// `POST /v1/sessions/{key}/pause`: hold the key's dispatch. Queued
/// work stays in the inbox, new work ingests as always, and every
/// driver passes the key by until resume lifts the hold — a live turn
/// is not cut by this (the lease predates the hold); the abort route
/// is what cuts one. 404 when the inventory has no such key.
async fn session_pause(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
// The key path's shape: one segment is the whole key, trimmed — a
// key carrying `/` arrives only percent-encoded, which is what
// every client of this surface sends. Empty after the trim is the
// 400 the delete route answers too.
let key = key.trim();
if key.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key is required"})),
)
.into_response();
}
let key = ResourceKey::from(key);
match state.store.load(&key) {
Ok(Some(_)) => {}
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": format!("no session {:?}", key.as_str())})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
}
match state.pause.pause(key.as_str()) {
Ok(_) => pause_answer(&key, true),
Err(err) => internal_error(err).into_response(),
}
}
/// `POST /v1/sessions/{key}/resume`: lift the hold. The key's pending
/// work dispatches on the first driver pass after this — the debounce
/// window it may still owe runs first, as it always did. Idempotent:
/// resuming an unheld key answers `{"paused": false}`, and 404s only
/// when the inventory has no such key at all.
async fn session_resume(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
// The key path's shape: one segment is the whole key, trimmed — a
// key carrying `/` arrives only percent-encoded, which is what
// every client of this surface sends. Empty after the trim is the
// 400 the delete route answers too.
let key = key.trim();
if key.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key is required"})),
)
.into_response();
}
let key = ResourceKey::from(key);
match state.store.load(&key) {
Ok(Some(_)) => {}
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": format!("no session {:?}", key.as_str())})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
}
match state.pause.resume(key.as_str()) {
Ok(_) => pause_answer(&key, false),
Err(err) => internal_error(err).into_response(),
}
}
/// `POST /v1/sessions/{key}/abort`: stop the key's work now. Two shapes,
/// one route:
///
/// - a live lease: the dispatch is signalled through the abort registry
/// and its turn is dropped at its current await — the handler repairs
/// the dangling calls, stashes what it committed, and releases the
/// lease as superseded. Work that sat behind the turn in the inbox
/// stays there, still queued.
/// - an idle key with a queue: the queue is drained and dropped under
/// a throwaway lease, so nothing dispatches; a `job:` key's row moves
/// to failed/`aborted` with it, the row being the jobs' truth.
///
/// The answer carries what happened: `{"key", "cut", "dropped"}`. A
/// `cut` of `false` with a zero `dropped` is the idempotent no-op —
/// nothing was running and nothing was queued. The whole route is
/// race-tolerant by construction: a key that leaves the leased state
/// between the read and the signal drains through the idle path, and a
/// key that enters it lands in the dispatcher's own conflicts below.
async fn session_abort(State(state): State<ClawState>, Path(key): Path<String>) -> Response {
// The key path's shape: one segment is the whole key, trimmed — a
// key carrying `/` arrives only percent-encoded, which is what
// every client of this surface sends. Empty after the trim is the
// 400 the delete route answers too.
let key = key.trim();
if key.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key is required"})),
)
.into_response();
}
let key = ResourceKey::from(key);
let record = match state.store.load(&key) {
Ok(Some(record)) => record,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": format!("no session {:?}", key.as_str())})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
};
let leased = record.lease.is_some();
if leased && state.aborts().signal(key.as_str()) {
// A job row moves with its cut: the handler's own abort path
// lands it, so nothing to do here but the answer.
return (
StatusCode::OK,
Json(json!({ "key": key.as_str(), "cut": true, "dropped": 0 })),
)
.into_response();
}
// Idle, or leased-but-unsignalable (the turn released between the
// read and the signal, or the lease lapsed unswept — `acquire`
// sweeps both). Whatever is queued drains and drops; nothing runs.
if record.inbox.is_empty() {
return (
StatusCode::OK,
Json(json!({ "key": key.as_str(), "cut": false, "dropped": 0 })),
)
.into_response();
}
let (lease, _session) = match state.dispatcher.acquire(key.clone(), "claw-abort") {
Ok(acquired) => acquired,
// The key went busy between the read and the acquire: a turn
// holds it now, and that turn is what a retry aborts.
Err(DispatchError::Conflict(_)) | Err(DispatchError::AtCapacity { .. }) => {
return (
StatusCode::CONFLICT,
Json(json!({"error": format!(
"session {:?} took a lease mid-abort; retry to cut it",
key.as_str()
)})),
)
.into_response();
}
Err(err) => return internal_error(err).into_response(),
};
let dropped = match state.dispatcher.poll_inbox(&lease) {
Ok(items) => items.len(),
Err(err) => return internal_error(err).into_response(),
};
if let Err(err) = state.dispatcher.release(&lease, Outcome::Superseded) {
return internal_error(err).into_response();
}
// The jobs' truth moves with the queue it lost: a row whose
// delivery was just dropped is failed, not queued, or it would sit
// live forever with nothing to run it. Quietly — the operator who
// aborted it is the one being told.
if let Some((instance, job_id)) = crate::jobs::parse_job_key(&key)
&& let Ok(Some(job)) = state.jobs.job(job_id)
&& job.status.is_live()
&& let Err(err) = state.jobs.fail(job_id, "aborted")
{
eprintln!("[claw] abort: job {job_id} on {instance:?} could not be failed: {err}");
}
// The transcript shows the cut: the dropped questions are already
// recorded, and without this marker they read as questions the
// daemon ignored.
state.hub.emit(
&key,
TurnEvent::TurnDone {
reply: None,
outcome: "aborted".to_owned(),
},
);
(
StatusCode::OK,
Json(json!({ "key": key.as_str(), "cut": false, "dropped": dropped })),
)
.into_response()
}
/// The setup badge: which of SOUL.md and USER.md exist, read live — a
/// UI badges first-run setup from it while the onboarding offer is
/// still open.
@@ -899,20 +652,12 @@ pub const MAX_INBOUND_IMAGES: usize = 8;
pub const MAX_MESSAGE_BODY_BYTES: usize =
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
/// `{"text": "..."}` — one chat message, plus the images and the chip
/// payloads it carries. A body without `images` or `pastes` is the old
/// shape, unchanged.
/// `{"text": "..."}` — one chat message, plus the images it carries.
/// A body without `images` is the old shape, unchanged.
#[derive(Deserialize)]
pub struct MessageBody {
/// 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.
/// The message text.
pub text: String,
/// The message's staged chips, payloads in order. A sender that
/// mints the legacy mark form sends none; the fold rewrites that
/// form too.
#[serde(default)]
pub pastes: Vec<String>,
/// The message's inline images, each the full MIME type plus bare
/// base64. The route checks the budget, then the dispatch copies
/// the bytes into the attachment store — the stream carries ids,
@@ -984,7 +729,6 @@ async fn messages(
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
key.as_str(),
&body.text,
&body.pastes,
&body.images,
)) {
return (
@@ -1095,14 +839,19 @@ async fn events(
let key = ResourceKey::from(key);
let (replay, mut receiver) = match query.since {
Some(cursor) => state.hub.replay_after(&key, cursor, TAIL_WINDOW),
// A tail window can open mid-turn, and a transcript that opens
// on a reply with no question above it reads as a bug. The hub
// widens the window back to the turn's first event. A cursor
// replay is exact by construction and is never cut.
None => state.hub.replay_tail_turn(&key, TAIL_WINDOW),
None => state.hub.replay_tail(&key, TAIL_WINDOW),
};
let stale = replay.stale;
let history = replay.events;
// A tail window can open mid-turn (the oldest events in it belong
// to a turn that started before the window), and a transcript that
// opens on a reply with no question above it reads as a bug. Cut
// back to the window's first question. A cursor replay is exact by
// construction and is never cut.
let history = if query.since.is_none() {
snap_to_turn(replay.events)
} else {
replay.events
};
// The pump decouples the broadcast channel from the SSE body: the
// client's disconnect closes the body, which fails the send, which
// ends the pump. The stream never ends on its own — a chat UI
@@ -1250,6 +999,21 @@ fn sse_event(seq: i64, turn: TurnEvent) -> SseEvent {
}
}
/// A replay window cut back to its first question: the events before
/// it belong to a turn whose start the window did not reach, and half a
/// turn reads as a bug. A window with no question in it (one turn
/// longer than the window) is returned whole — showing it beats showing
/// nothing, and the walk back through history continues above it.
fn snap_to_turn(mut events: Vec<crate::hub::SeqEvent>) -> Vec<crate::hub::SeqEvent> {
match events
.iter()
.position(|(_, event)| matches!(event, TurnEvent::UserMessage { .. }))
{
Some(index) if index > 0 => events.split_off(index),
_ => events,
}
}
/// The history route's query: the page ends at `before` (the seq of the
/// oldest event the client holds; absent reads from the newest), and
/// `limit` is the most events it may hold before the page is widened
@@ -1267,30 +1031,24 @@ struct HistoryQuery {
/// through a session's history. The page starts on a turn boundary and
/// ends exactly at `before`, so pages stack without gaps or overlaps.
/// The response's `more` says whether anything precedes it: `false`
/// means the client has reached the session's first event, and
/// `read_only` says the page is a snapshot rather than a record a
/// message could extend.
///
/// A key outside the resident context has no hub record: its handler
/// never streams. The daemon still holds the session the engine
/// checkpointed, so the route serves that history instead, through
/// [`crate::thread`] — the same page shape, cut the same way, so a chat
/// surface renders a finished forge thread with the renderer it already
/// has. Those keys take no message ([`messages`] refuses them), which
/// is what `read_only` tells the client.
/// means the client has reached the session's first event.
async fn session_history(
State(state): State<ClawState>,
Path(key): Path<String>,
Query(query): Query<HistoryQuery>,
) -> Response {
if !crate::interactive::is_resident_key(&key) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "key must start with interactive:, task:, or phone:"})),
)
.into_response();
}
let key = ResourceKey::from(key);
let limit = query
.limit
.unwrap_or(HISTORY_PAGE)
.clamp(1, HISTORY_PAGE_MAX);
if !crate::interactive::is_resident_key(key.as_str()) {
return stashed_history(&state, &key, query.before, limit);
}
let page = state.hub.replay_turn_before(&key, query.before, limit);
// Whether anything sits below the page: a lookup, not a read.
let more = match page.first().map(|(seq, _)| *seq) {
@@ -1301,48 +1059,7 @@ async fn session_history(
.into_iter()
.map(|(seq, event)| json!({"seq": seq, "event": event}))
.collect();
Json(json!({"events": events, "more": more, "read_only": false})).into_response()
}
/// The snapshot page for a key the resident context does not own: the
/// record's session stash, turned back into turn events. A key with no
/// record, or a record the engine never checkpointed, has nothing to
/// show and answers an empty page rather than a 404 — the inventory
/// lists the key, and an empty thread is the truth about it.
fn stashed_history(
state: &ClawState,
key: &ResourceKey,
before: Option<i64>,
limit: usize,
) -> Response {
let record = match state.store.load(key) {
Ok(record) => record,
Err(err) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": format!("session lookup for {key} failed: {err}")})),
)
.into_response();
}
};
let (page, more) = match record.as_ref().and_then(|record| record.session.as_ref()) {
Some(session) => {
let outcome = record
.as_ref()
.and_then(|record| record.last_outcome.as_ref());
let leased = record
.as_ref()
.is_some_and(|record| record.state == rhema_rsd::KeyState::Leased);
let events = crate::thread::events(&session.core, outcome, leased);
crate::thread::page(&events, before, limit)
}
None => (Vec::new(), false),
};
let events: Vec<Value> = page
.into_iter()
.map(|(seq, event)| json!({"seq": seq, "event": event}))
.collect();
Json(json!({"events": events, "more": more, "read_only": true})).into_response()
Json(json!({"events": events, "more": more})).into_response()
}
async fn watches_list(State(state): State<ClawState>) -> Result<Json<Value>, (StatusCode, String)> {
@@ -2265,88 +1982,6 @@ pub(crate) async fn drain_owned(
}
}
/// `GET /v1/sandbox`: where the agent's `bash` runs. The token never
/// rides the wire: `token_set` says whether one is stored.
async fn sandbox_get(State(state): State<ClawState>) -> Json<Value> {
Json(sandbox_json(&state))
}
/// The sandbox state as the wire sees it: the shared body of the read
/// and of the write that answers with the new choice.
fn sandbox_json(state: &ClawState) -> Value {
let choice = state.sandbox().choice();
json!({
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"private_key_set": choice
.private_key
.as_deref()
.is_some_and(|key| !key.is_empty()),
"host": choice.host,
"ssh_workspace": choice.workspace,
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
})
}
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` and `private_key` are write-only;
/// `clear_token` and `clear_private_key` drop the stored ones. The
/// choice applies on the next turn, no restart.
async fn sandbox_put(
State(state): State<ClawState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let Some(kind) = body["kind"].as_str() else {
return Err(bad_request("body must carry a sandbox kind"));
};
let kind = crate::sandbox::SandboxKind::parse(kind)
.ok_or_else(|| bad_request(format!("unknown sandbox kind {kind:?}")))?;
let current = state.sandbox().choice();
let clear_token = body["clear_token"].as_bool().unwrap_or(false);
let token = if clear_token {
None
} else {
body["token"]
.as_str()
.map(str::to_owned)
.or_else(|| current.token.clone())
};
let clear_private_key = body["clear_private_key"].as_bool().unwrap_or(false);
let private_key = if clear_private_key {
None
} else {
body["private_key"]
.as_str()
.map(str::to_owned)
.or_else(|| current.private_key.clone())
};
let choice = crate::sandbox::SandboxChoice {
kind,
url: body["url"]
.as_str()
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
host: body["host"]
.as_str()
.map(str::to_owned)
.or_else(|| current.host.clone()),
workspace: body["workspace"]
.as_str()
.map(str::to_owned)
.or_else(|| current.workspace.clone()),
private_key,
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
crate::sandbox::SandboxError::Store(_) => internal_error(err),
})?;
Ok(Json(sandbox_json(&state)))
}
/// `GET /v1/providers`: every constructible backend and the active pair.
/// The active pair is runtime state — the config file seeded it, the
/// settings store owns it now. Each provider is one instance, named by
@@ -2585,7 +2220,6 @@ async fn agent_put(
};
let texts = crate::identity::IdentityTexts {
name: field(body["name"].as_str(), &current.name),
email: field(body["email"].as_str(), &current.email),
mark: field(body["mark"].as_str(), &current.mark),
initials: field(body["initials"].as_str(), &current.initials),
tagline: field(body["tagline"].as_str(), &current.tagline),
+5 -147
View File
@@ -32,7 +32,6 @@ use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
use crate::paste::PasteSpan;
use crate::turn_store::{TurnStore, TurnStoreError};
/// How many events a subscriber may trail by before the oldest drop.
@@ -75,23 +74,13 @@ pub enum TurnEvent {
/// shows its own messages as it sends them, and skips the live
/// echo.
UserMessage {
/// The input text in the plain form the model read — each
/// paste's payload in place, no marks.
/// The input text, verbatim.
text: String,
/// The batch's images, in arrival order, as the attachment
/// store holds them. `default` because rows recorded before
/// images rode the transcript carry no field.
#[serde(default)]
images: Vec<UserImage>,
/// The paste chips the input carried, the same span record the
/// session's `rhema-code` annotation holds: the byte range
/// each chip stands for in `text`, plus its line count for the
/// label. `default` because rows recorded before chips rode
/// as spans carry the marks in the text instead — a client
/// that finds none scans for them; skipped when empty, so
/// rows without chips replay byte-for-byte as they landed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pastes: Vec<PasteSpan>,
},
/// A piece of the model's reasoning trace, in stream order.
ThinkingDelta {
@@ -129,8 +118,7 @@ pub enum TurnEvent {
/// The turn's final assistant text, when it produced one.
reply: Option<String>,
/// `handled` or `failed` — or `steered`, when a chat message
/// cut the turn short and a next turn runs instead of it — or
/// `aborted`, when the operator cut it and nothing follows.
/// cut the turn short and a next turn runs instead of it.
outcome: String,
},
/// The agent asked the human something only they can answer: a
@@ -331,42 +319,6 @@ impl EventHub {
)
}
/// The newest page, cut with the live receiver, starting on a turn's
/// first event: the window a client with no cache opens with. It
/// widens by doubling while the window falls inside one turn, up to
/// [`HISTORY_SCAN_CAP`], and a record that opens inside a turn comes
/// back whole rather than as a fragment. A long agent turn streams
/// hundreds of deltas past the file it handed over, so a reload that
/// landed mid-reply used to drop what the turn began with, images
/// among it.
pub fn replay_tail_turn(
&self,
key: &ResourceKey,
limit: usize,
) -> (Replay, broadcast::Receiver<TurnEvent>) {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
let entry = Self::entry(&mut entries, key, self.capacity);
let store = self.record_store.as_deref();
let mut want = limit.max(1);
let events = loop {
let window = Self::record_tail(store, entry, key, want);
let opens_on_turn = window
.first()
.is_some_and(|(_, event)| matches!(event, TurnEvent::UserMessage { .. }));
if opens_on_turn || window.len() < want || want >= HISTORY_SCAN_CAP {
break window;
}
want = (want * 2).min(HISTORY_SCAN_CAP);
};
(
Replay {
events,
stale: false,
},
entry.sender.subscribe(),
)
}
/// One page of the record older than `before` (`None` reads from the
/// newest), ending exactly at `before` and starting at a turn's
/// first event — the page a client walking backward asks for, so a
@@ -613,27 +565,10 @@ mod tests {
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: Vec::new(),
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[]}"#
);
// The chip record rides only when there is one: the span
// shape is the session annotation's own, byte offsets over
// the plain text.
assert_eq!(
serde_json::to_string(&TurnEvent::UserMessage {
text: "hi".into(),
images: Vec::new(),
pastes: vec![PasteSpan {
start: 3,
end: 9,
lines: 4,
}],
})
.unwrap(),
r#"{"type":"user_message","text":"hi","images":[],"pastes":[{"start":3,"end":9,"lines":4}]}"#
);
assert_eq!(
serde_json::to_string(&TurnEvent::ToolResult {
name: "bash".into(),
@@ -665,8 +600,7 @@ mod tests {
event,
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new()
images: Vec::new()
}
);
}
@@ -680,8 +614,7 @@ mod tests {
assert_eq!(
TurnEvent::UserMessage {
text: "x".into(),
images: Vec::new(),
pastes: Vec::new()
images: Vec::new()
}
.kind(),
"user_message"
@@ -726,7 +659,6 @@ mod tests {
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text("hi"));
@@ -737,8 +669,7 @@ mod tests {
vec![
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new()
images: Vec::new()
},
text("hi"),
],
@@ -864,7 +795,6 @@ mod tests {
TurnEvent::UserMessage {
text: "earlier".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
let (history, mut receiver) = hub.subscribe_with_history(&key);
@@ -952,77 +882,6 @@ mod tests {
assert_eq!(replay.events, vec![(4, text("4")), (5, text("5"))]);
}
/// The tail a fresh client opens with starts on a question even when
/// the newest turn is longer than the window: a reload must not land
/// on the middle of a reply, where the file the turn handed over (and
/// the question that asked for it) are behind the window.
#[test]
fn a_tail_window_inside_one_turn_widens_to_the_question() {
let hub = EventHub::default();
let key = key("longturn");
hub.emit(
&key,
TurnEvent::UserMessage {
text: "q".into(),
images: Vec::new(),
pastes: Vec::new(),
},
);
for n in 0..5 {
hub.emit(&key, text(&n.to_string()));
}
// A window of 2 from the end sits inside the turn; the widened
// one opens on the question and holds the whole turn.
let (replay, _) = hub.replay_tail_turn(&key, 2);
assert!(!replay.stale);
assert_eq!(
replay.events.len(),
6,
"the whole turn: {:?}",
replay.events
);
assert_eq!(replay.events[0].0, 0);
assert!(matches!(replay.events[0].1, TurnEvent::UserMessage { .. }));
}
/// The widening stops at the record's start: a record with no
/// question in it replays whole instead of looping after the cap.
#[test]
fn a_tail_window_with_no_question_replays_the_record_once() {
let hub = EventHub::default();
let key = key("questionless");
for n in 0..6 {
hub.emit(&key, text(&n.to_string()));
}
let (replay, _) = hub.replay_tail_turn(&key, 2);
assert_eq!(replay.events.len(), 6);
assert_eq!(replay.events[0].0, 0, "the record's first event");
}
/// A tail that already opens on a question is left exactly as asked:
/// no widening past the window the store served.
#[test]
fn a_tail_window_on_a_question_is_not_widened() {
let hub = EventHub::default();
let key = key("plain");
for turn in 0..3 {
hub.emit(
&key,
TurnEvent::UserMessage {
text: format!("q{turn}"),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text(&format!("a{turn}")));
hub.emit(&key, done(&format!("a{turn}")));
}
// Seqs 6, 7, 8: the third turn, opening on its question.
let (replay, _) = hub.replay_tail_turn(&key, 3);
assert_eq!(replay.events.len(), 3);
assert_eq!(replay.events[0].0, 6);
}
/// Backward paging: each page ends where the last began and starts
/// on a turn boundary, so a transcript stacks pages without gaps,
/// overlaps, or a fragment at its top.
@@ -1037,7 +896,6 @@ mod tests {
TurnEvent::UserMessage {
text: format!("q{turn}"),
images: Vec::new(),
pastes: Vec::new(),
},
);
hub.emit(&key, text(&format!("a{turn}")));
+7 -24
View File
@@ -14,8 +14,7 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -45,13 +44,9 @@ pub const MAX_IMAGE_BYTES: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentIdentity {
/// The agent's display name: message author, window title,
/// notifications, and the commit author name in workspaces.
/// notifications.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The address commits carry in workspaces; also the mail-like
/// identity other surfaces may quote.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
/// The glyph or emoji in the rail, the favicon, the empty states.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mark: Option<String>,
@@ -74,7 +69,6 @@ pub struct AgentIdentity {
#[derive(Debug, Clone, Default)]
pub struct IdentityTexts {
pub name: Option<String>,
pub email: Option<String>,
pub mark: Option<String>,
pub initials: Option<String>,
pub tagline: Option<String>,
@@ -126,7 +120,6 @@ impl IdentityStore {
pub fn get(&self) -> Result<AgentIdentity, IdentityError> {
Ok(AgentIdentity {
name: self.text("name")?,
email: self.text("email")?,
mark: self.text("mark")?,
initials: self.text("initials")?,
tagline: self.text("tagline")?,
@@ -142,7 +135,6 @@ impl IdentityStore {
pub fn set_texts(&self, texts: &IdentityTexts) -> Result<AgentIdentity, IdentityError> {
let fields = [
("name", &texts.name, 64usize),
("email", &texts.email, 120),
("mark", &texts.mark, 8),
("initials", &texts.initials, 4),
("tagline", &texts.tagline, 120),
@@ -271,7 +263,6 @@ impl ToolOp for IdentitySet {
};
let texts = IdentityTexts {
name: field(args["name"].as_str(), current.name.as_deref()),
email: field(args["email"].as_str(), current.email.as_deref()),
mark: field(args["mark"].as_str(), current.mark.as_deref()),
initials: field(args["initials"].as_str(), current.initials.as_deref()),
tagline: field(args["tagline"].as_str(), current.tagline.as_deref()),
@@ -354,8 +345,10 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The identity tool set over `store`: `identity_set` — its spec from
/// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into()));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, workspace.into()),
);
assert!(
skipped.is_empty(),
"the identity_set tool manifest must load: {skipped:?}"
@@ -370,7 +363,7 @@ pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> Too
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
@@ -400,7 +393,6 @@ mod tests {
let saved = store
.set_texts(&IdentityTexts {
name: Some(" Kosmos ".to_owned()),
email: Some("kosmos@example.net".to_owned()),
mark: Some("✦".to_owned()),
initials: None,
tagline: Some("order".to_owned()),
@@ -408,7 +400,6 @@ mod tests {
})
.expect("the texts save");
assert_eq!(saved.name.as_deref(), Some("Kosmos"), "trimmed");
assert_eq!(saved.email.as_deref(), Some("kosmos@example.net"));
assert_eq!(saved.mark.as_deref(), Some("✦"));
assert_eq!(saved.initials, None);
assert_eq!(saved.signoff, None, "an empty string clears");
@@ -418,7 +409,6 @@ mod tests {
.set_texts(&IdentityTexts::default())
.expect("the clear saves");
assert_eq!(cleared.name, None);
assert_eq!(cleared.email, None);
}
#[test]
@@ -495,7 +485,6 @@ mod tests {
let answer = tool
.invoke(json!({
"name": "Kosmos",
"email": "kosmos@example.net",
"mark": "✦",
"avatar": "face.png",
}))
@@ -504,7 +493,6 @@ mod tests {
let answer: Value = serde_json::from_str(&answer).expect("parses");
assert_eq!(answer["saved"], true);
assert_eq!(answer["identity"]["name"], "Kosmos");
assert_eq!(answer["identity"]["email"], "kosmos@example.net");
assert_eq!(answer["identity"]["avatar"], true);
let (bytes, content_type) = store
.image(ImageKind::Avatar)
@@ -518,11 +506,6 @@ mod tests {
.expect("saves");
let identity = store.get().expect("reads");
assert_eq!(identity.name.as_deref(), Some("Kosmos"), "kept");
assert_eq!(
identity.email.as_deref(),
Some("kosmos@example.net"),
"kept"
);
assert_eq!(identity.tagline.as_deref(), Some("order"), "added");
assert!(identity.avatar, "untouched by a text-only save");
}
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -17,8 +17,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -42,7 +41,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The coding-agent tool set over `store`: one tool, `coding_agent` —
/// its spec from the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<CodingJobStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the coding_agent tool manifest must load: {skipped:?}"
@@ -227,7 +227,7 @@ fn required<'a>(value: &'a Option<String>, complaint: &str) -> Result<&'a str, S
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+14 -157
View File
@@ -13,7 +13,7 @@
//! instance and job resolve through the store, the workspace is the
//! instance's path, the session blob (or a fresh agent) is loaded, the
//! allowlist is permissive exactly as the forge path's — and then one
//! `HostAgent` turn runs. The final text lands in the job row and
//! `CodingAgent` turn runs. The final text lands in the job row and
//! the user's notifications; the turn itself streams nowhere, its
//! observability is the stderr tool log.
//!
@@ -22,13 +22,11 @@
//! fails before any model call. The trust boundary is unchanged from
//! the forge path — the bearer-gated surface and the instance list.
use std::num::NonZeroU32;
use std::sync::Arc;
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_coding_agent::{AllowAll, CodingAgent, CodingAgentConfig};
use rhema_core::{Event as ModelEvent, EventSink};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use crate::backends::BackendRegistry;
@@ -36,7 +34,6 @@ use crate::handler::final_text;
use crate::interactive::passthrough_key_fn;
use crate::job_store::{CodingJobStore, JobStatus};
use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
use crate::sandbox::SandboxState;
/// The source name the coding jobs ingest under.
pub const JOBS_SOURCE: &str = "jobs";
@@ -140,19 +137,10 @@ pub struct CodingJobHandler {
backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>,
max_turn_steps: NonZeroU32,
max_turn_steps: u32,
/// Whether the jobs run the bounded request view (the config's
/// `transcript`, on unless set false).
transcript: bool,
/// Where commands run: this host when absent, a remote sandbox when
/// the surface selected one. Read per job.
sandbox: Option<Arc<SandboxState>>,
/// The abort registry the sessions' abort route signals: a live job
/// turn cut at its await stashes the conversation and lands the row
/// as failed with `aborted` (see [`crate::abort`]). Private by
/// default — a handler nobody shared a registry with never receives
/// a signal — and shared through [`CodingJobHandler::with_abort`].
abort: Arc<crate::abort::AbortRegistry>,
}
impl CodingJobHandler {
@@ -163,7 +151,7 @@ impl CodingJobHandler {
backends: Arc<BackendRegistry>,
store: Arc<CodingJobStore>,
notifications: Arc<NotificationStore>,
max_turn_steps: NonZeroU32,
max_turn_steps: u32,
transcript: bool,
) -> Self {
Self {
@@ -172,36 +160,13 @@ impl CodingJobHandler {
notifications,
max_turn_steps,
transcript,
sandbox: None,
abort: Arc::new(crate::abort::AbortRegistry::new()),
}
}
/// Shares the deployment's sandbox choice: a job's commands run
/// where it says, seeded from the instance's host path.
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
self.sandbox = Some(sandbox);
self
}
/// Shares the abort registry with the HTTP surface: the abort route
/// signals it, and every job dispatch this handler runs listens on
/// it.
pub fn with_abort(mut self, abort: Arc<crate::abort::AbortRegistry>) -> Self {
self.abort = abort;
self
}
/// One dispatch, failed with a reason on any step; every failure
/// lands in the job row before it lands in the outcome, so the
/// model's `status` read and the user's notification agree.
async fn dispatch(&self, ctx: &mut SessionContext) -> Result<Outcome, String> {
// The abort listener arms first, before any of the lookups and
// file work below: the route signals the moment it sees the
// lease, and a listener that arrives after the agent is built
// would let an early abort fall through as a no-op. One listener
// per dispatch is enough — the lease forbids a second one.
let mut abort = self.abort.listen(ctx.key.as_str());
// Poll to live, as every handler does — and here the poll is also
// what closes the dispatch. A job key carries exactly one kind of
// item, the row's own delivery, and those items are drained and
@@ -247,11 +212,7 @@ impl CodingJobHandler {
.map_err(|err| format!("job {job_id} could not start: {err}"))?;
let (provider, model) = self.backends.current();
let display = match &self.sandbox {
Some(sandbox) => sandbox.workspace_for(&workspace),
None => workspace.clone(),
};
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
let mut config = CodingAgentConfig::new(model, &workspace);
config.max_turn_steps = self.max_turn_steps;
// A job's stashed session carries across runs and only ever
// grows; the view is what keeps a repeat run's steps cheap.
@@ -260,18 +221,8 @@ impl CodingJobHandler {
config.transcript = self
.transcript
.then(rhema_transcript::TranscriptSettings::default);
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
display,
sandbox.executor(workspace.clone()),
)));
}
_ => {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
}
}
let stashed = self
.store
.session(&instance_name)
@@ -285,9 +236,9 @@ impl CodingJobHandler {
self.fail(job_id, &instance_name, &reason);
reason
})?;
HostAgent::from_session(config, session)
CodingAgent::from_session(provider, config, session)
}
None => HostAgent::new(config),
None => CodingAgent::new(provider, config),
}
.map_err(|err| {
let reason = format!("cannot start the coding agent for {instance_name:?}: {err}");
@@ -297,42 +248,21 @@ impl CodingJobHandler {
// Commit-before-execute rides the dispatcher exactly as the
// forge handler's does: the intent is in the store before the
// first tool runs, and a crash-left dangling call revives at
// turn entry (HostAgent::turn's own revive, over the resumed
// turn entry (CodingAgent::turn's own revive, over the resumed
// session).
agent.set_commit_hook(Some(ctx.commit_hook()));
let mut sink = JobSink;
// The abort listener rides the turn: a signal drops the future
// at its current await — a streaming request, or a running
// shell command, whose child dies with the drop. Armed at
// dispatch entry, above.
let turned = tokio::select! {
output = agent.turn(&job.prompt, &mut sink) => {
Some(output.map_err(|err| {
format!("the coding turn for {instance_name:?} failed: {err}")
}))
}
_ = abort.wait() => None,
};
let output = match turned {
Some(Ok(output)) => output,
Some(Err(err)) => {
let reason = err;
let output = match agent.turn(&job.prompt, &mut sink, Arc::new(AllowAll)).await {
Ok(output) => output,
Err(err) => {
let reason = format!("the coding turn for {instance_name:?} failed: {err}");
// The conversation up to the failure is still the
// instance's: saved, so a follow-up run continues it.
self.save_session(&instance_name, &agent);
self.fail(job_id, &instance_name, &reason);
return Ok(Outcome::Failed(reason));
}
None => {
// Cut, not failed: the row says `aborted`, the
// conversation keeps whatever the turn committed, and
// the outcome is superseded — the work is no longer
// wanted, exactly the outcome's own words.
self.save_session(&instance_name, &agent);
self.fail(job_id, &instance_name, "aborted");
return Ok(Outcome::Superseded);
}
};
self.save_session(&instance_name, &agent);
let reply = final_text(&output.message).ok_or_else(|| {
@@ -350,7 +280,7 @@ impl CodingJobHandler {
Ok(Outcome::Handled)
}
fn save_session(&self, instance: &str, agent: &HostAgent) {
fn save_session(&self, instance: &str, agent: &CodingAgent) {
match serde_json::to_string(agent.session()) {
Ok(blob) => {
let _ = self.store.save_session(instance, &blob);
@@ -430,80 +360,7 @@ mod tests {
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"),
);
CodingJobHandler::new(
backends,
store,
notifications,
NonZeroU32::new(16).unwrap(),
true,
)
}
/// A provider whose one generation parks forever — the request an
/// abort interrupts, released only by the drop.
struct ParkingProvider;
#[rhema_autonomous_agent::async_trait]
impl rhema_core::ModelProvider for ParkingProvider {
async fn complete(
&self,
_request: rhema_core::ModelRequest,
_sink: &mut dyn rhema_core::EventSink,
) -> Result<rhema_core::ModelOutput, rhema_core::ProviderError> {
std::future::pending::<()>().await;
unreachable!("the pending future never resolves")
}
}
#[tokio::test]
async fn an_abort_signal_cuts_the_running_job_and_fails_the_row() {
let workspace = tempdir();
let store = Arc::new(CodingJobStore::in_memory().unwrap());
store
.add_instance("rhema", workspace.to_str().unwrap())
.unwrap();
let job = store.enqueue("rhema", "fix the lint").unwrap();
let notifications = Arc::new(NotificationStore::in_memory().unwrap());
let provider: Arc<dyn rhema_core::ModelProvider> = Arc::new(ParkingProvider);
let backends = Arc::new(
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
.expect("a single mock backend always constructs"),
);
let abort = Arc::new(crate::abort::AbortRegistry::new());
let handler = CodingJobHandler::new(
backends,
store.clone(),
notifications.clone(),
NonZeroU32::new(16).unwrap(),
true,
)
.with_abort(abort.clone());
let (source, driver, _dispatcher) = harness(store.clone(), handler);
assert_eq!(source.detect().await.unwrap(), 1);
// The job runs off the test task; the abort lands while the
// generation is parked.
let pass = tokio::spawn(async move { driver.run_once().await });
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
while store.job(job.id).unwrap().unwrap().status != JobStatus::Running {
assert!(
tokio::time::Instant::now() < deadline,
"the job never started"
);
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
assert!(abort.signal(&job_key("rhema", job.id)));
// Superseded, not failed-and-retried: the work is no longer
// wanted, and the row — the jobs' truth — says aborted.
assert_eq!(pass.await.unwrap().unwrap(), vec![Outcome::Superseded]);
let row = store.job(job.id).unwrap().unwrap();
assert_eq!(row.status, JobStatus::Failed);
assert_eq!(row.result.as_deref(), Some("aborted"));
// The user still hears about it.
let pending = notifications.pending(DEFAULT_DEVICE, 0).unwrap();
assert_eq!(pending.len(), 1);
assert!(pending[0].body.contains("aborted"));
CodingJobHandler::new(backends, store, notifications, 16, true)
}
fn reply(text: &str) -> ModelOutput {
+4 -18
View File
@@ -32,13 +32,9 @@
//! - [`turn_store`] — the turn-history table: what each key's stream
//! streamed, appended per event, replayed whole after a restart
//! - [`hub`] — the event hub: per-key record and broadcast of turn events
//! - [`identity`] — the agent's presentation identity: name, email,
//! mark, images, served over `/v1/agent` and settable by the agent
//! itself through the `identity_set` tool
//! - [`git_identity`] — the boot-time git identity: `user.name` and
//! `user.email` into the daemon user's global git config, resolved
//! from config, then identity, then defaults, guarded against
//! hand-edited values
//! - [`identity`] — the agent's presentation identity: name, mark,
//! images, served over `/v1/agent` and settable by the agent itself
//! through the `identity_set` tool
//! - [`consents`] — the consent table and wake bridge: a running turn
//! asks the human (a secret to store, permission to act) and waits;
//! the chat surface answers through the consent routes
@@ -46,8 +42,6 @@
//! workspace files handed to the human as fetchable cards
//! - [`phone`] — the phone state and command queue: reported status to
//! read, consent-gated control actions the device executes
//! - [`sandbox`]: where `bash` runs, this host, or a remote daemon
//! speaking the sandbox protocol over HTTP
//! - [`watch_tools`] — the agent's watch-management tool set
//! - [`notify_tools`] — the `notify` tool: the queue a device polls
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
@@ -70,7 +64,6 @@
#![forbid(unsafe_code)]
pub mod abort;
pub mod accounts_tools;
pub mod attachments;
pub mod backends;
@@ -81,7 +74,6 @@ pub mod daemon;
pub mod environment;
pub mod extension;
pub mod forge;
pub mod git_identity;
pub mod handler;
pub mod http;
pub mod hub;
@@ -96,17 +88,12 @@ pub mod mock;
pub mod notifications;
pub mod notify_tools;
pub mod openai;
pub mod paste;
pub mod pause;
pub mod phone;
pub mod sandbox;
pub mod settings;
pub mod steer;
pub mod task_source;
pub mod task_store;
pub mod task_tools;
pub mod thread;
pub mod toolkit;
pub mod turn_store;
pub(crate) mod vision;
pub mod watch_store;
@@ -118,7 +105,7 @@ pub use bootstrap::{
render_system,
};
pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
pub use daemon::{ClawError, Daemon, TickReport, run_once};
pub use environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource;
@@ -130,7 +117,6 @@ pub use interactive::InteractiveHandler;
pub use mock::MockLoop;
pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError};
pub use rhema_forge_integration::{ForgeKind, resolve_token};
pub use sandbox::{SandboxChoice, SandboxError, SandboxKind, SandboxState};
pub use settings::SettingsStore;
pub use task_source::{TASKS_SOURCE, TaskScheduler};
pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError};
+5 -10
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::Outcome;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once};
use rhema_rsd::{DispatcherConfig, Outcome};
/// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)]
@@ -74,9 +74,9 @@ async fn main() {
}
if let Some(Command::Vision { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1);
argv.push(std::ffi::OsString::from(rhema_bash::vision::MODE));
argv.push(std::ffi::OsString::from(rhema_agent_tools::vision::MODE));
argv.extend(rest.iter().cloned());
std::process::exit(rhema_bash::vision::cli_run(&argv));
std::process::exit(rhema_agent_tools::vision::cli_run(&argv));
}
if let Err(err) = run(args).await {
eprintln!("error: {err}");
@@ -100,11 +100,6 @@ async fn run(args: Args) -> Result<(), ClawError> {
} else {
resolve_backends(&config)?
};
// The workspace git identity: written in both shapes (a cron pass
// commits too), from deterministic boot code, guarded against
// hand-edited values. Never fatal — provisioning problems are the
// one stderr line this prints.
eprintln!("[claw] {}", rhema_claw::git_identity::boot(&config));
eprintln!(
"[claw] active {}/{}, db {}, http {}",
backends.active().0,
@@ -140,7 +135,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on.
config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts");
let daemon = Daemon::build(&config, backends, forge_dispatch())?;
let daemon = Daemon::build(&config, backends, DispatcherConfig::default())?;
daemon.run().await
}
}
+3 -8
View File
@@ -9,7 +9,7 @@
use std::collections::BTreeSet;
use std::sync::{Arc, OnceLock};
use rhema_host_agent::HostAgentConfig;
use rhema_coding_agent::CodingAgentConfig;
/// What one wiring produced, held for the process.
struct Wired {
@@ -61,7 +61,7 @@ fn wired() -> Option<&'static Wired> {
/// init file, the socket, the token), the prompt's `mcp` lines, and
/// the persisted off switch. A frontend without wiring changes
/// nothing.
pub(crate) fn apply(config: &mut HostAgentConfig) {
pub(crate) fn apply(config: &mut CodingAgentConfig) {
let Some(wired) = wired() else {
return;
};
@@ -82,12 +82,7 @@ mod tests {
/// same map).
#[test]
fn apply_without_any_wiring_leaves_the_config_alone() {
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
let before = config.shell_env.clone();
apply(&mut config);
// The wiring only appears when the machine's global mcp.yaml
-1
View File
@@ -65,7 +65,6 @@ impl ModelProvider for MockLoop {
message: Message {
role: Role::Assistant,
content: vec![Content::Text(text)],
annotations: Default::default(),
},
stop_reason: StopReason::EndTurn,
usage: Usage::default(),
+8 -6
View File
@@ -12,8 +12,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -34,7 +33,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[("notify", include_str!("../tools/notif
/// The notification tool set over `store`: `notify` — its spec from
/// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<NotificationStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the notify tool manifest must load: {skipped:?}"
@@ -102,7 +102,7 @@ mod tests {
async fn call(store: &Arc<NotificationStore>, args: Value) -> rhema_core::ToolResult {
let resolver =
registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
resolver
.resolve(
rhema_core::ToolCall {
@@ -118,11 +118,13 @@ mod tests {
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_spec() {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "notify");
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("notify"),
rhema_core::ReplaySafety::Unsafe,
-1
View File
@@ -259,7 +259,6 @@ pub async fn chat_completions(
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
key.as_str(),
&input.text,
&[],
&input.images,
)) {
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
-215
View File
@@ -1,215 +0,0 @@
//! How a prompt carries a pasted payload: plain text plus a span note.
//!
//! A submitted prompt is plain text with each multi-line paste's payload
//! in place, exactly what the model reads, and the message carries a
//! [`PasteSpan`] list under [`CONSUMER`] saying which byte ranges the
//! chat surface draws as chips. No provider, no summarizer, and no other
//! consumer reads that note.
//!
//! `rhema-core` carried this until 0.4.2 moved display encodings out of
//! the engine. One frontend writes the note and the same frontend reads
//! it, so it belongs beside that frontend. The format is unchanged, so a
//! session stashed by either side loads in the other.
//!
//! [`PasteSpan`] replaced an embedded encoding, [`MARK`], payload,
//! [`MARK`], written into the text. Sessions written that way still
//! load. [`migrate`] rewrites one into plain text plus spans before the
//! first provider call.
use rhema_core::{Content, Message, Role};
use serde::{Deserialize, Serialize};
/// The object-replacement character: opens and closes one embedded
/// paste. Two marks always bracket a payload; a lone mark is literal
/// text.
pub const MARK: char = '\u{FFFC}';
/// The annotation key the chat surface records paste spans under on a
/// user message. No engine reads it.
pub const CONSUMER: &str = "rhema-code";
/// One paste's span in a message's plain text: the byte range its chip
/// stands for, and the payload's line count for the chip's label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasteSpan {
/// Start byte of the payload in the message text.
pub start: usize,
/// End byte of the payload in the message text, exclusive.
pub end: usize,
/// Lines in the payload, the chip's size label.
pub lines: usize,
}
/// The annotation's own shape, `{"pastes": [...]}`.
#[derive(Serialize, Deserialize)]
struct Pastes {
pastes: Vec<PasteSpan>,
}
/// Normalizes text that travels inside an embed or beside marks:
/// carriage returns to newlines, stray marks dropped, the scan must stay
/// unambiguous.
pub fn normalize(text: &str) -> String {
text.replace("\r\n", "\n")
.replace('\r', "\n")
.replace(MARK, "")
}
/// Records `spans` on `message` under [`CONSUMER`], replacing whatever
/// the same consumer left before; an empty list clears the note.
pub fn annotate(message: &mut Message, spans: &[PasteSpan]) {
if spans.is_empty() {
message.annotations.remove(CONSUMER);
return;
}
let value = serde_json::to_value(Pastes {
pastes: spans.to_vec(),
})
.expect("paste spans serialize");
message.annotate(CONSUMER, value);
}
/// The paste spans `message` carries, empty when it has none or when the
/// note is not this consumer's shape.
pub fn spans(message: &Message) -> Vec<PasteSpan> {
message
.annotation(CONSUMER)
.and_then(|value| serde_json::from_value::<Pastes>(value.clone()).ok())
.map(|pastes| pastes.pastes)
.unwrap_or_default()
}
/// Splits legacy embedded text into the plain form and its spans.
fn split_legacy(text: &str) -> (String, Vec<PasteSpan>) {
let mut plain = String::with_capacity(text.len());
let mut spans = Vec::new();
let mut rest = text;
while let Some(start) = rest.find(MARK) {
plain.push_str(&rest[..start]);
let after = &rest[start + MARK.len_utf8()..];
match after.find(MARK) {
Some(end) => {
let payload = &after[..end];
let begin = plain.len();
plain.push_str(payload);
spans.push(PasteSpan {
start: begin,
end: plain.len(),
lines: payload.lines().count(),
});
rest = &after[end + MARK.len_utf8()..];
}
// An unpaired mark is literal text.
None => {
plain.push(MARK);
rest = after;
}
}
}
plain.push_str(rest);
(plain, spans)
}
/// Rewrites the legacy embedded form in `history` into plain text plus
/// [`PasteSpan`] annotations, returning how many messages changed.
/// Sessions written before the annotation existed carry `MARK payload
/// MARK` inside the prompt; a resumed session must not send those marks
/// to a provider. Chips only ever lived in one user text block, so only
/// user messages are considered.
pub fn migrate(history: &mut [Message]) -> usize {
let mut changed = 0;
for message in history.iter_mut() {
if message.role != Role::User {
continue;
}
let mut spans = Vec::new();
let mut touched = false;
for content in message.content.iter_mut() {
if let Content::Text(text) = content
&& text.contains(MARK)
{
let (plain, found) = split_legacy(text);
*text = plain;
spans.extend(found);
touched = true;
}
}
if touched {
annotate(message, &spans);
changed += 1;
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spans_round_trip_through_the_annotation() {
let mut message = Message::text(Role::User, "look at l1\nl2 this");
assert!(spans(&message).is_empty());
let span = PasteSpan {
start: 8,
end: 13,
lines: 2,
};
annotate(&mut message, &[span]);
assert_eq!(spans(&message), vec![span]);
let json = serde_json::to_value(&message).unwrap();
assert_eq!(json["annotations"]["rhema-code"]["pastes"][0]["lines"], 2);
// Clearing the last span drops the whole note, so an
// annotation-free message keeps the pre-annotation wire shape.
annotate(&mut message, &[]);
assert!(spans(&message).is_empty());
assert!(
serde_json::to_value(&message)
.unwrap()
.get("annotations")
.is_none()
);
}
#[test]
fn migrate_rewrites_the_legacy_form_into_plain_text_and_spans() {
let payload = "l1\nl2\nl3\nl4";
let mut history = vec![
Message::text(Role::User, format!("look at {MARK}{payload}{MARK} this")),
Message::text(Role::Assistant, "on it"),
];
assert_eq!(migrate(&mut history), 1);
assert_eq!(
history[0].content,
Message::text(Role::User, format!("look at {payload} this")).content
);
assert_eq!(
spans(&history[0]),
vec![PasteSpan {
start: 8,
end: 8 + payload.len(),
lines: 4,
}]
);
// Idempotent: the plain form has no marks left to rewrite.
assert_eq!(migrate(&mut history), 0);
assert_eq!(history[1], Message::text(Role::Assistant, "on it"));
}
#[test]
fn an_unpaired_mark_migrates_as_literal_text() {
let mut history = vec![Message::text(Role::User, format!("a{MARK}b"))];
assert_eq!(migrate(&mut history), 1);
assert_eq!(
history[0].content,
Message::text(Role::User, "a\u{FFFC}b").content
);
assert!(spans(&history[0]).is_empty());
}
#[test]
fn normalize_flattens_carriage_returns_and_drops_marks() {
assert_eq!(normalize("p\r\nq\rs"), "p\nq\ns");
assert_eq!(normalize(&format!("a{MARK}b")), "ab");
}
}
-160
View File
@@ -1,160 +0,0 @@
//! The pause gate: dispatch keys the drivers hold — the inventory's
//! pause/resume, wired through the HTTP surface.
//!
//! Pausing is an operator's hold, not a dispatcher state: rhema-rsd's
//! state machine has idle, leased and re-acquire, and none of them means
//! "keep the events, run nothing". So the hold lives beside the store:
//! a set of keys, persisted in the settings table (`paused:<key>` rows,
//! the same table the active backend pair lives in), checked by every
//! driver's ownership predicate. A paused key ingests as always — its
//! inbox accumulates, its debounce opens, `admit` offers it — and every
//! driver declines it, pass after pass, until resume lifts the hold.
//! Nothing is dropped and nothing runs; the pending work dispatches on
//! the first pass after the resume.
//!
//! The in-memory set is the read side (a predicate call is a lock and a
//! contains); the settings rows are the truth a restart reloads. A live
//! turn is not paused by this — the lease it holds was granted before
//! the hold, and it runs to its end; the abort surface is what cuts a
//! running turn (see [`crate::abort`]).
use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, PoisonError};
use crate::settings::{SettingsError, SettingsStore};
/// The settings-row prefix one paused key lives under: `paused:<key>`,
/// value `1`. The prefix is stripped back off on load.
const SETTINGS_PREFIX: &str = "paused:";
/// The keys whose dispatch is on hold, in memory over the settings
/// table. Shareable: every method takes `&self`, the set serializes on
/// its mutex, and the whole thing rides an `Arc` through the daemon and
/// the HTTP surface.
pub struct PauseSet {
settings: Arc<SettingsStore>,
live: Mutex<BTreeSet<String>>,
}
impl PauseSet {
/// Loads the set over `settings`: every `paused:` row becomes one
/// held key. The daemon calls this once at assembly; a restart
/// resumes holding whatever was held.
pub fn load(settings: Arc<SettingsStore>) -> Result<Self, SettingsError> {
let rows = settings.rows_by_prefix(SETTINGS_PREFIX)?;
let live = rows
.into_iter()
.map(|(key, _)| key[SETTINGS_PREFIX.len()..].to_owned())
.collect::<BTreeSet<_>>();
Ok(Self {
settings,
live: Mutex::new(live),
})
}
/// Holds `key`'s dispatch. `Ok(true)` when the hold is new, `Ok(false)`
/// when the key was already held — the route can answer idempotent.
pub fn pause(&self, key: &str) -> Result<bool, SettingsError> {
let fresh = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned());
if fresh && let Err(err) = self.settings.set(&format!("{SETTINGS_PREFIX}{key}"), "1") {
// The hold is one fact in two places: a row that cannot be
// written takes the in-memory half back with it, so a
// restart cannot disagree with what the caller was told.
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(key);
return Err(err);
}
Ok(fresh)
}
/// Lifts `key`'s hold. `Ok(true)` when a hold was lifted, `Ok(false)`
/// when the key was not held.
pub fn resume(&self, key: &str) -> Result<bool, SettingsError> {
let lifted = self
.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(key);
if lifted && let Err(err) = self.settings.delete(&format!("{SETTINGS_PREFIX}{key}")) {
// Same agreement as `pause`: a row that cannot be deleted
// puts the hold back, where it was.
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned());
return Err(err);
}
Ok(lifted)
}
/// Whether `key` is held — the drivers' predicate check, one lock
/// and a contains.
pub fn is_paused(&self, key: &str) -> bool {
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.contains(key)
}
/// Every held key, ascending — the ops view.
pub fn keys(&self) -> Vec<String> {
self.live
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn store() -> Arc<SettingsStore> {
Arc::new(SettingsStore::in_memory().expect("in-memory settings"))
}
#[test]
fn a_pause_persists_and_reloads() {
let settings = store();
let pause = PauseSet::load(settings.clone()).unwrap();
assert!(pause.pause("job:rhema#7").unwrap());
assert!(pause.is_paused("job:rhema#7"));
assert!(!pause.is_paused("interactive:web"));
// A fresh set over the same table starts where the last left off.
let reloaded = PauseSet::load(settings).unwrap();
assert!(reloaded.is_paused("job:rhema#7"));
assert_eq!(reloaded.keys(), vec!["job:rhema#7".to_owned()]);
}
#[test]
fn resume_lifts_the_hold_and_clears_the_row() {
let settings = store();
let pause = PauseSet::load(settings.clone()).unwrap();
pause.pause("interactive:web").unwrap();
assert!(pause.resume("interactive:web").unwrap());
assert!(!pause.is_paused("interactive:web"));
assert!(!pause.resume("interactive:web").unwrap(), "already lifted");
assert!(
PauseSet::load(settings).unwrap().keys().is_empty(),
"nothing lingers in the table"
);
}
#[test]
fn pausing_twice_is_one_hold() {
let settings = store();
let pause = PauseSet::load(settings).unwrap();
assert!(pause.pause("gitea:acme/widgets#3").unwrap());
assert!(!pause.pause("gitea:acme/widgets#3").unwrap());
assert_eq!(pause.keys().len(), 1);
}
}
+6 -5
View File
@@ -49,8 +49,7 @@ use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -722,8 +721,10 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, consents, bridge, hub, key));
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, consents, bridge, hub, key),
);
assert!(
skipped.is_empty(),
"the phone tool manifest must load: {skipped:?}"
@@ -738,7 +739,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use crate::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
-824
View File
@@ -1,824 +0,0 @@
//! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP, or an ssh login on a far
//! box.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end; its private key rides the
//! choice as key text, the settings table is the store, so a
//! credential held in config or a store has no file to stage. The
//! tool spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes the workspace root and, when it is
//! empty, sends the host workspace as a tarball through the seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use base64::Engine as _;
use rhema_bash::exec::{RunOutcome, ShellError, ShellExecutor, default_executor_with};
use rhema_core::{OutputOnly, ToolProgress};
use rhema_sandbox::{RunRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path the http sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The ssh sandbox's default workspace base: the remote login's own
/// home, the ssh backend's documented default. One directory per claw
/// workspace lands under it, named by the session hash.
pub const SSH_WORKSPACE_ROOT: &str = "/root";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
const PROBE_TIMEOUT: Duration = Duration::from_secs(20);
/// Which machine runs the shell.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxKind {
/// The daemon's own host, the original path.
#[default]
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
}
impl SandboxKind {
/// The stored spelling.
pub fn as_str(self) -> &'static str {
match self {
Self::Local => "local",
Self::Http => "http",
Self::Ssh => "ssh",
}
}
/// Parses a stored spelling. Anything else is `None`, which every
/// caller turns into the local default.
pub fn parse(value: &str) -> Option<Self> {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
"ssh" => Some(Self::Ssh),
_ => None,
}
}
}
/// One sandbox choice: the kind and whatever it needs. `local` needs
/// nothing; `http` needs a base URL and may carry a token.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
pub struct SandboxChoice {
/// The machine kind.
pub kind: SandboxKind,
/// The `http` sandbox's base URL, no trailing slash after
/// normalization.
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// The `ssh` sandbox's destination: any alias or `user@host` the
/// local ssh config resolves, the built-in client's resolution.
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
/// The `ssh` sandbox's workspace base, where the per-workspace
/// directories land. Defaults to [`SSH_WORKSPACE_ROOT`].
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
/// The `ssh` sandbox's private key, the key text itself (OpenSSH
/// or PEM format), not a path: the choice lives in a config file
/// or a store that has no file to stage. Unset, the sandbox
/// hunts like the `ssh` binary would, the agent first, then the
/// default key files. `GET /v1/sandbox` never returns the key,
/// only that one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub private_key: Option<String>,
}
impl SandboxChoice {
/// Trims the strings, drops blank ones, and validates what `http`
/// needs to run. A choice that fails reads as a 400 at the route,
/// never as a silent fallback.
pub fn normalized(mut self) -> Result<Self, SandboxError> {
self.url = self
.url
.map(|url| url.trim().trim_end_matches('/').to_owned())
.filter(|url| !url.is_empty());
self.token = self
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
self.host = self
.host
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty());
self.workspace = self
.workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty());
self.private_key = self
.private_key
.map(|key| key.trim().to_owned())
.filter(|key| !key.is_empty());
if self.kind == SandboxKind::Ssh {
let host = self
.host
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the ssh sandbox needs a host".to_owned()))?;
if host.contains(char::is_whitespace) {
return Err(SandboxError::Invalid(
"the ssh sandbox host is one destination, no spaces".to_owned(),
));
}
if let Some(workspace) = self.workspace.as_deref()
&& !workspace.starts_with('/')
{
return Err(SandboxError::Invalid(
"the ssh sandbox workspace must be an absolute path".to_owned(),
));
}
}
if self.kind == SandboxKind::Http {
let url = self
.url
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the http sandbox needs a url".to_owned()))?;
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err(SandboxError::Invalid(
"the http sandbox url must start with http:// or https://".to_owned(),
));
}
}
Ok(self)
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind != SandboxKind::Local
}
/// The remote directory one workspace's commands run in: the
/// protocol root for `http`, a directory per host workspace under
/// the configured base for `ssh`.
pub fn remote_root(&self, host: &Path) -> PathBuf {
match self.kind {
SandboxKind::Http => PathBuf::from(REMOTE_WORKSPACE),
SandboxKind::Ssh => PathBuf::from(format!(
"{}/{}",
self.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT),
session_name(host)
)),
SandboxKind::Local => host.to_path_buf(),
}
}
}
/// Why a sandbox choice or operation failed.
#[derive(Debug, thiserror::Error)]
pub enum SandboxError {
/// The choice cannot run as written.
#[error("{0}")]
Invalid(String),
/// The settings table failed.
#[error("sandbox store failed: {0}")]
Store(String),
}
/// The chosen sandbox and the executors built over it, shared by every
/// handler so a switch takes effect on the next turn without a restart.
pub struct SandboxState {
choice: RwLock<SandboxChoice>,
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<dyn Sandbox>>>,
}
impl SandboxState {
/// The state over `settings`, seeded by `seed` when no choice was
/// stored. `local_workspace` is the chat workspace the settings
/// surface reports; `shell_env` is layered over local commands.
pub fn load(
settings: Arc<SettingsStore>,
seed: Option<SandboxChoice>,
local_workspace: PathBuf,
shell_env: &BTreeMap<String, String>,
) -> Result<Self, SandboxError> {
let stored = settings
.get(SANDBOX_KEY)
.map_err(|err| SandboxError::Store(err.to_string()))?;
let choice = stored
.as_deref()
.and_then(|raw| serde_json::from_str::<SandboxChoice>(raw).ok())
.and_then(|choice| choice.normalized().ok())
.or_else(|| seed.and_then(|choice| choice.normalized().ok()))
.unwrap_or_default();
Ok(Self {
choice: RwLock::new(choice),
settings,
local_workspace,
local: default_executor_with(shell_env),
remote: Mutex::new(HashMap::new()),
})
}
/// The current choice.
pub fn choice(&self) -> SandboxChoice {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.choice
.read()
.unwrap_or_else(PoisonError::into_inner)
.is_remote()
}
/// Saves and applies a choice. The next turn reads it; nothing is
/// rebuilt in place. Answers the normalized choice that was stored.
pub fn set(&self, choice: SandboxChoice) -> Result<SandboxChoice, SandboxError> {
let choice = choice.normalized()?;
let raw =
serde_json::to_string(&choice).map_err(|err| SandboxError::Store(err.to_string()))?;
self.settings
.set(SANDBOX_KEY, &raw)
.map_err(|err| SandboxError::Store(err.to_string()))?;
*self.choice.write().unwrap_or_else(PoisonError::into_inner) = choice.clone();
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
Ok(choice)
}
/// The workspace a handler should name and start commands in: the
/// host path locally, the choice's remote root otherwise.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
self.choice().remote_root(host)
}
/// The chat workspace under the current choice, for the settings
/// surface.
pub fn workspace(&self) -> PathBuf {
self.workspace_for(&self.local_workspace)
}
/// The host workspace path, whatever the current choice.
pub fn local_workspace(&self) -> &Path {
&self.local_workspace
}
/// An executor for one host workspace. Remote sessions are derived
/// from the workspace path, so two workspaces never share a root.
pub fn executor(
self: &Arc<Self>,
host_workspace: impl Into<PathBuf>,
) -> Arc<dyn ShellExecutor> {
Arc::new(ClawShell {
state: Arc::clone(self),
host_workspace: host_workspace.into(),
local: self.local.clone(),
seeded: AtomicBool::new(false),
last: Mutex::new(None),
})
}
/// The cached sandbox for one session. The map is cleared whenever
/// the choice changes, so a new URL, token, host, or base builds a
/// new client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<dyn Sandbox>, ShellError> {
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(sandbox) = remote.get(&session) {
return Ok(sandbox.clone());
}
}
let sandbox: Arc<dyn Sandbox> =
match choice.kind {
SandboxKind::Http => {
let url = choice.url.as_deref().ok_or_else(|| {
ShellError::Failed("the http sandbox has no url".to_owned())
})?;
let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
}
SandboxKind::Ssh => {
let dest = choice.host.as_deref().ok_or_else(|| {
ShellError::Failed("the ssh sandbox has no host".to_owned())
})?;
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
let mut sandbox = SshSandbox::new(dest.to_owned())
.with_workspace(format!("{base}/{session}"));
if let Some(key) = choice.private_key.as_deref() {
sandbox = sandbox.with_private_key(key);
}
Arc::new(sandbox)
}
SandboxKind::Local => {
return Err(ShellError::Failed(
"the local sandbox needs no remote client".to_owned(),
));
}
};
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(session, sandbox.clone());
Ok(sandbox)
}
}
/// One handler's view of the choice: local commands go straight to the
/// host executor; remote commands go through the sandbox, seeded from
/// the host workspace once per choice.
struct ClawShell {
state: Arc<SandboxState>,
host_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
seeded: AtomicBool,
last: Mutex<Option<SandboxChoice>>,
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty workspace root gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox. The
/// probe makes the root first: the http daemon keeps one, the ssh
/// far end has none until something makes it, and the unpack's
/// `tar -C` would fail on a missing directory.
async fn seed(
&self,
sandbox: &Arc<dyn Sandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = OutputOnly(|_line: &str| {});
let probe = sandbox
.run(
RunRequest {
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone().into(),
timeout: PROBE_TIMEOUT,
},
cancelled,
&mut sink,
)
.await
.map_err(protocol_error)?;
if !probe.stdout.is_empty() {
return Ok(());
}
let root = self.host_workspace.clone();
let archive = tokio::task::spawn_blocking(move || tarball(&root))
.await
.map_err(|err| {
ShellError::Failed(format!("the workspace archive task failed: {err}"))
})??;
let Some(tar_gz_base64) = archive else {
return Ok(());
};
sandbox
.seed(&WorkspaceSeed::Tarball {
name: "workspace.tar.gz".to_owned(),
tar_gz_base64,
})
.await
.map_err(protocol_error)?;
Ok(())
}
}
#[async_trait]
impl ShellExecutor for ClawShell {
async fn run(
&self,
request: RunRequest,
cancelled: &AtomicBool,
progress: &mut dyn ToolProgress,
) -> Result<RunOutcome, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self.local.run(request, cancelled, progress).await;
}
{
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
if last.as_ref() != Some(&choice) {
*last = Some(choice.clone());
self.seeded.store(false, Ordering::Relaxed);
}
}
let sandbox = self.state.remote_sandbox(&choice, &self.host_workspace)?;
if !self.seeded.load(Ordering::Relaxed) {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let root = choice.remote_root(&self.host_workspace);
ShellSandbox::new(sandbox)
.run(
RunRequest {
command: request.command,
cwd: root,
timeout: request.timeout,
},
cancelled,
progress,
)
.await
}
}
/// Maps a protocol failure onto the shell error the tool shapes into an
/// `is_error` result.
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::OutOfMemory => ShellError::OutOfMemory,
rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still
// a failure, reported in-band with its own text.
_ => ShellError::Failed(err.to_string()),
}
}
/// One path quoted for the remote `bash -c`: single quotes, the
/// closing quote spliced, good for every path a workspace root can
/// have.
fn shquote(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
/// The sandbox session name for one host workspace: a stable FNV-1a
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
fn session_name(host: &Path) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in host.to_string_lossy().as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("rhema-claw-{hash:016x}")
}
/// One host workspace as a gzipped tar, base64 for the protocol.
/// `None` when the directory is missing or empty: nothing to seed.
fn tarball(root: &Path) -> Result<Option<String>, ShellError> {
if !root.is_dir() {
return Ok(None);
}
let mut entries = std::fs::read_dir(root)
.map_err(|err| ShellError::Failed(format!("cannot read the workspace {root:?}: {err}")))?;
if entries.next().is_none() {
return Ok(None);
}
let output = std::process::Command::new("tar")
.arg("-czf")
.arg("-")
.arg("-C")
.arg(root)
.arg(".")
.output()
.map_err(|err| {
ShellError::Failed(format!("cannot archive the workspace with tar: {err}"))
})?;
if !output.status.success() {
let detail = String::from_utf8_lossy(&output.stderr);
let detail = detail.trim();
return Err(ShellError::Failed(if detail.is_empty() {
"tar failed to archive the workspace".to_owned()
} else {
format!("tar failed to archive the workspace: {detail}")
}));
}
Ok(Some(
base64::engine::general_purpose::STANDARD.encode(output.stdout),
))
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn state(choice: SandboxChoice) -> Arc<SandboxState> {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
Arc::new(
SandboxState::load(
settings,
Some(choice),
PathBuf::from("/state/claw/workspaces/interactive"),
&BTreeMap::new(),
)
.expect("the state loads"),
)
}
#[test]
fn a_bare_choice_is_local() {
let choice = SandboxChoice::default().normalized().unwrap();
assert_eq!(choice.kind, SandboxKind::Local);
assert!(!choice.is_remote());
assert_eq!(choice.kind.as_str(), "local");
}
#[test]
fn an_http_choice_needs_an_absolute_url() {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a URL is required");
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn an_ssh_choice_needs_a_host_and_an_absolute_base() {
let missing = SandboxChoice {
kind: SandboxKind::Ssh,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a host is required");
let spaced = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me @box".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(spaced.is_err(), "a destination is one word");
let relative = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("srv/claw".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "the base is an absolute path");
let good = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some(" me@box ".to_owned()),
workspace: Some("/srv/claw/".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(good.host.as_deref(), Some("me@box"));
assert_eq!(good.workspace.as_deref(), Some("/srv/claw"));
assert!(good.is_remote());
assert_eq!(good.kind.as_str(), "ssh");
assert_eq!(
SandboxKind::parse("ssh"),
Some(SandboxKind::Ssh),
"the stored spelling round-trips"
);
}
#[test]
fn the_private_key_trims_and_a_blank_stays_unset() {
let keyed = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" -----BEGIN OPENSSH PRIVATE KEY----- ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(
keyed.private_key.as_deref(),
Some("-----BEGIN OPENSSH PRIVATE KEY-----"),
"the key text is trimmed, not mangled"
);
let blank = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("a blank key is no key, not a rejection");
assert_eq!(blank.private_key, None, "blank keeps the hunt on");
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
..SandboxChoice::default()
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
state.choice().url.as_deref(),
Some("http://box:7600"),
"the trailing slash is trimmed"
);
}
#[test]
fn an_ssh_workspace_is_one_directory_per_host_workspace() {
let host = PathBuf::from("/state/claw/workspaces/interactive");
let choice = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
};
let root = choice.remote_root(&host);
let root = root.to_string_lossy().to_string();
assert!(
root.starts_with("/srv/claw/rhema-claw-"),
"the root lives under the configured base: {root}"
);
assert_eq!(root.len(), "/srv/claw/rhema-claw-".len() + 16);
let default_root = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
..SandboxChoice::default()
}
.remote_root(&host);
assert_eq!(
default_root.to_string_lossy(),
format!("/root/{}", session_name(&host)),
"the base defaults to the login's home"
);
}
#[test]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
assert_eq!(state.choice().kind, SandboxKind::Local);
state
.set(SandboxChoice {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Http);
assert_eq!(reloaded.choice().url.as_deref(), Some("https://box:7600"));
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[test]
fn an_ssh_choice_persists_with_its_host_and_base() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
state
.set(SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Ssh);
assert_eq!(reloaded.choice().host.as_deref(), Some("me@box"));
assert_eq!(reloaded.choice().workspace.as_deref(), Some("/srv/claw"));
assert_eq!(
reloaded.workspace().to_string_lossy(),
format!("/srv/claw/{}", session_name(Path::new("/tmp/ws"))),
"the settings surface reports the session root"
);
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
// The emptiness probe: nothing at /workspace.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "",
"stderr": "",
"timed_out": false
})))
.up_to_n_times(1)
.mount(&server)
.await;
// The command itself.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"exit_code": 0,
"stdout": "hi\n",
"stderr": "",
"timed_out": false
})))
.mount(&server)
.await;
// The seed: accepted, and the host workspace is not empty.
Mock::given(method("POST"))
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/seed$"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"error": null
})))
.expect(1)
.mount(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("README.md"), "seed me").expect("the file writes");
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
..SandboxChoice::default()
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = OutputOnly(|_line: &str| {});
let executed = executor
.run(
RunRequest {
command: "echo hi".to_owned(),
cwd: Path::new(REMOTE_WORKSPACE).to_path_buf(),
timeout: Duration::from_secs(5),
},
&cancelled,
&mut sink,
)
.await
.expect("the remote command answers");
assert_eq!(executed.stdout, b"hi\n");
assert_eq!(executed.code, Some(0));
}
}
+13 -10
View File
@@ -15,8 +15,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
@@ -66,7 +65,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `cancel_task` — specs from the embedded manifests, operations
/// compiled here.
pub fn registry(store: Arc<TaskStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the task tool manifests must all load: {skipped:?}"
@@ -236,7 +236,7 @@ mod tests {
async fn call(store: &Arc<TaskStore>, name: &str, args: Value) -> rhema_core::ToolResult {
let resolver =
registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
resolver
.resolve(
rhema_core::ToolCall {
@@ -252,7 +252,8 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!(
@@ -270,7 +271,7 @@ mod tests {
let mut covered = Vec::new();
for (source, raw) in MANIFESTS {
covered.push(
crate::toolkit::parse_manifest(raw)
rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin,
);
@@ -285,11 +286,12 @@ mod tests {
#[test]
fn the_registry_serves_the_manifest_specs() {
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let specs = resolver.specs();
for (name, raw) in MANIFESTS {
let manifest =
crate::toolkit::parse_manifest(raw).unwrap_or_else(|err| panic!("{name}: {err}"));
let manifest = rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{name}: {err}"));
let spec = specs
.iter()
.find(|spec| spec.name == *name)
@@ -308,7 +310,8 @@ mod tests {
#[test]
fn replay_safety_comes_from_the_manifest() {
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("list_tasks"),
rhema_core::ReplaySafety::Safe
-413
View File
@@ -1,413 +0,0 @@
//! Read-only transcripts for the keys the chat surface cannot message.
//!
//! A forge thread, a finished coding job: their dispatches run through
//! handlers that never touch the hub, so the daemon holds no turn
//! record for them. What it does hold is the session stash the
//! step engine checkpoints after every step, with the engine's own
//! history in it. This module turns that history back into the hub's
//! event shapes, so the chat surface renders a finished thread with the
//! renderer it already has, and [`page`] cuts it the way the hub cuts
//! its own record.
use std::collections::HashMap;
use rhema_core::{Content, Message, Role, Session as CoreSession, ToolResult};
use rhema_rsd::Outcome;
use crate::hub::{SeqEvent, TurnEvent};
use crate::interactive::{shell_command, snippet};
/// One tool call remembered while its result is still to come: the name
/// the result event carries, and the arguments a shell result's command
/// line is read from.
struct Call {
name: String,
args: String,
}
/// The transcript of a stashed session, as the hub's events: one
/// `user_message`, the turn's deltas and tool rows, one `turn_done` per
/// turn, in history order. `last` is the record's most recent outcome,
/// which the newest turn's end marker carries; the older turns closed
/// the way the handler closes a finished one. `leased` says the record
/// is mid-dispatch right now, and a stash whose newest turn never
/// released is not "handled" — the turn was cut, and its end marker says
/// so instead of borrowing the previous turn's word.
///
/// Images and pastes ride a user message only when the stash recorded
/// them: a forge or job prompt carries none, and a chat key never takes
/// this path.
pub fn events(session: &CoreSession, last: Option<&Outcome>, leased: bool) -> Vec<TurnEvent> {
let mut out: Vec<TurnEvent> = Vec::new();
let mut calls: HashMap<String, Call> = HashMap::new();
let mut open = false;
let mut reply: Option<String> = None;
for message in &session.history {
match message.role {
Role::User => {
close(&mut out, &mut open, reply.take(), "handled");
out.push(TurnEvent::UserMessage {
text: text_of(message),
images: Vec::new(),
pastes: crate::paste::spans(message),
});
open = true;
}
Role::Assistant => {
// A stash cut before its first user message still opens
// a turn: the history is what it is.
open = true;
let mut said: Option<String> = None;
for content in &message.content {
match content {
Content::Text(text) => {
if text.trim().is_empty() {
continue;
}
out.push(TurnEvent::TextDelta { text: text.clone() });
said = Some(text.clone());
}
Content::ToolCall(call) => {
calls.insert(
call.id.clone(),
Call {
name: call.name.clone(),
args: call.args.to_string(),
},
);
out.push(TurnEvent::ToolStart {
name: call.name.clone(),
});
}
Content::ToolResult(result) => push_result(&mut out, &calls, result),
Content::Image(_) => {}
}
}
if said.is_some() {
reply = said;
}
}
Role::Tool | Role::System => {
for content in &message.content {
if let Content::ToolResult(result) = content {
push_result(&mut out, &calls, result);
}
}
}
}
}
let outcome = outcome_label(last, leased);
close(&mut out, &mut open, reply, &outcome);
out
}
/// The text blocks of a message, joined the way the model read them.
fn text_of(message: &Message) -> String {
message
.content
.iter()
.filter_map(|content| match content {
Content::Text(text) => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
/// The end marker, only for a turn that was open.
fn close(out: &mut Vec<TurnEvent>, open: &mut bool, reply: Option<String>, outcome: &str) {
if !*open {
return;
}
out.push(TurnEvent::TurnDone {
reply,
outcome: outcome.to_owned(),
});
*open = false;
}
/// One tool result as the wire's row: the name its call carried, the
/// bounded snippet the summary holds, and for a shell the command line
/// parsed back out of the call's arguments.
fn push_result(out: &mut Vec<TurnEvent>, calls: &HashMap<String, Call>, result: &ToolResult) {
let call = calls.get(&result.id);
let name = call
.map(|call| call.name.clone())
.unwrap_or_else(|| result.id.clone());
let command = matches!(name.as_str(), "bash" | "run_command")
.then(|| shell_command(call.map(|call| call.args.as_str())))
.flatten();
out.push(TurnEvent::ToolResult {
name,
is_error: result.is_error,
summary: snippet(&result.content),
code: result.code,
command,
});
}
/// The outcome label a turn's end marker carries, in the handler's own
/// words: a superseded dispatch was cut, a failed one broke. A record
/// with no outcome has never released, so its newest turn is either the
/// one running now (the lease says so) or one a restart cut — never a
/// handled turn, which always records its release.
fn outcome_label(outcome: Option<&Outcome>, leased: bool) -> String {
match outcome {
Some(Outcome::Failed(_)) => "failed",
Some(Outcome::Superseded) => "aborted",
Some(Outcome::Handled) => "handled",
None if leased => "running",
None => "aborted",
}
.to_owned()
}
/// One page of a stashed transcript, cut the way the hub cuts its own
/// record: at most `limit` events ending at `before`, starting on a
/// turn boundary, with `more` saying whether anything sits below it. A
/// turn longer than `limit` comes back whole rather than split. `seq`
/// numbers the events from 1 in history order — a stable address for as
/// long as the stash does not change.
pub fn page(events: &[TurnEvent], before: Option<i64>, limit: usize) -> (Vec<SeqEvent>, bool) {
let end = match before {
Some(before) => (before - 1).clamp(0, events.len() as i64) as usize,
None => events.len(),
};
let mut want = limit.max(1);
loop {
let from = end.saturating_sub(want);
let window = &events[from..end];
let page_start = match window
.iter()
.position(|event| matches!(event, TurnEvent::UserMessage { .. }))
{
Some(index) => from + index,
None if from == 0 => from,
None => {
// The window sits inside one turn: read further back,
// unless there is nothing further back to read.
want = (want * 2).min(crate::hub::HISTORY_SCAN_CAP);
continue;
}
};
let page = events[page_start..end]
.iter()
.enumerate()
.map(|(offset, event)| ((page_start + offset + 1) as i64, event.clone()))
.collect();
return (page, page_start > 0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use rhema_core::{Image, ToolCall};
use serde_json::json;
fn user(text: &str) -> Message {
Message::text(Role::User, text)
}
fn assistant(content: Vec<Content>) -> Message {
Message {
role: Role::Assistant,
content,
annotations: Default::default(),
}
}
fn result(id: &str, content: &str) -> Message {
Message {
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult {
id: id.to_owned(),
content: content.to_owned(),
is_error: false,
code: Some(0),
images: Vec::new(),
})],
annotations: Default::default(),
}
}
fn session(history: Vec<Message>) -> CoreSession {
CoreSession {
history,
..CoreSession::default()
}
}
#[test]
fn a_turn_becomes_the_events_the_hub_would_have_recorded() {
let core = session(vec![
user("review PR 7"),
assistant(vec![Content::ToolCall(ToolCall {
id: "call-1".to_owned(),
name: "bash".to_owned(),
args: json!({"command": "gh pr diff 7"}),
provider_data: serde_json::Value::Null,
})]),
result("call-1", "diff --git a/x b/x"),
assistant(vec![Content::Text("LGTM.".to_owned())]),
]);
assert_eq!(
events(&core, Some(&Outcome::Handled), false),
vec![
TurnEvent::UserMessage {
text: "review PR 7".to_owned(),
images: Vec::new(),
pastes: Vec::new(),
},
TurnEvent::ToolStart {
name: "bash".to_owned(),
},
TurnEvent::ToolResult {
name: "bash".to_owned(),
is_error: false,
summary: "diff --git a/x b/x".to_owned(),
code: Some(0),
command: Some("gh pr diff 7".to_owned()),
},
TurnEvent::TextDelta {
text: "LGTM.".to_owned(),
},
TurnEvent::TurnDone {
reply: Some("LGTM.".to_owned()),
outcome: "handled".to_owned(),
},
]
);
}
#[test]
fn each_turn_closes_before_the_next_question() {
let core = session(vec![
user("first"),
assistant(vec![Content::Text("one".to_owned())]),
user("second"),
assistant(vec![Content::Text("two".to_owned())]),
]);
let events = events(&core, Some(&Outcome::Failed("boom".to_owned())), false);
let closes: Vec<&TurnEvent> = events
.iter()
.filter(|event| matches!(event, TurnEvent::TurnDone { .. }))
.collect();
assert_eq!(closes.len(), 2);
assert_eq!(
closes[0],
&TurnEvent::TurnDone {
reply: Some("one".to_owned()),
outcome: "handled".to_owned(),
}
);
// The newest turn carries the record's own outcome.
assert_eq!(
closes[1],
&TurnEvent::TurnDone {
reply: Some("two".to_owned()),
outcome: "failed".to_owned(),
}
);
}
#[test]
fn a_stash_that_starts_mid_turn_still_closes() {
let core = session(vec![assistant(vec![Content::Text("orphan".to_owned())])]);
assert_eq!(
events(&core, Some(&Outcome::Handled), false).last(),
Some(&TurnEvent::TurnDone {
reply: Some("orphan".to_owned()),
outcome: "handled".to_owned(),
})
);
}
/// A record with no release is not a handled turn: either the
/// dispatch is running now, or a restart cut it. Both read as what
/// they are instead of borrowing the previous turn's word.
#[test]
fn an_unreleased_turn_is_not_labelled_handled() {
let core = session(vec![
user("cut"),
assistant(vec![Content::Text("I'll start by looking".to_owned())]),
]);
let cut = events(&core, None, false);
assert_eq!(
cut.last(),
Some(&TurnEvent::TurnDone {
reply: Some("I'll start by looking".to_owned()),
outcome: "aborted".to_owned(),
})
);
let running = events(&core, None, true);
assert_eq!(
running.last(),
Some(&TurnEvent::TurnDone {
reply: Some("I'll start by looking".to_owned()),
outcome: "running".to_owned(),
})
);
}
#[test]
fn images_in_the_history_do_not_invent_attachment_ids() {
let mut message = user("look");
message.content.push(Content::Image(Image {
media_type: rhema_core::ImageMediaType::Png,
data: "iVBORw0KGgo=".to_owned(),
}));
let events = events(&session(vec![message]), None, false);
assert_eq!(
events[0],
TurnEvent::UserMessage {
text: "look".to_owned(),
images: Vec::new(),
pastes: Vec::new(),
}
);
}
#[test]
fn a_page_starts_on_a_turn_boundary_and_stacks_backwards() {
let core = session(vec![
user("zero"),
assistant(vec![Content::Text("a".to_owned())]),
user("one"),
assistant(vec![Content::Text("b".to_owned())]),
user("two"),
assistant(vec![Content::Text("c".to_owned())]),
]);
let all = events(&core, None, false);
// The newest page holds the last turn only.
let (newest, more) = page(&all, None, 2);
assert!(more, "two turns sit above it");
assert!(matches!(newest[0].1, TurnEvent::UserMessage { .. }));
assert_eq!(newest.len(), 3, "a turn comes whole: question, delta, done");
assert_eq!(newest[0].0, 7, "seqs are absolute, so pages stack");
// The next page ends exactly where the first begins.
let (older, more) = page(&all, Some(newest[0].0), 2);
assert!(more);
assert_eq!(older[0].0, 4);
let (first, more) = page(&all, Some(older[0].0), 2);
assert!(!more, "the record ends here");
assert_eq!(first[0].0, 1);
}
#[test]
fn a_turn_longer_than_the_page_comes_back_whole() {
let core = session(vec![
user("long"),
assistant(vec![
Content::Text("a".to_owned()),
Content::Text("b".to_owned()),
Content::Text("c".to_owned()),
]),
]);
let all = events(&core, None, false);
let (whole, more) = page(&all, None, 1);
assert_eq!(whole.len(), all.len());
assert!(!more);
}
}
-680
View File
@@ -1,680 +0,0 @@
//! The resident's toolset: named tools, a `TOOL.yaml` per tool, and the
//! per-run [`ToolResolver`] cut from them.
//!
//! `rhema-core` ships the resolver seam and no registry, on purpose. It
//! ships one primitive, not a framework. Until 0.4.2 the registry, the
//! manifest loader, the allowlist, and the resolver chain rode
//! `rhema-autonomous-agent`, which was never the right home for them. The
//! crate is the lease-driven loop, and it compiles no tool of its own.
//! The claw was the only consumer, so the machinery moved here with the
//! tools it serves.
//!
//! The shape is unchanged. A tool is a folder under `tools/` holding a
//! `TOOL.yaml`: the name the model calls, the description it
//! picks the tool by, the argument schema, the replay classification, and
//! a `run` binding. The code half is a [`ToolOp`] registered under that
//! binding's id, so a tool's static data stops living next to it in Rust
//! string literals and one folder names one tool. [`builtin_tools`]
//! joins the two, [`ToolRegistry`] holds the survivors, and
//! [`ToolRegistry::resolver_for`] cuts the allowlisted view the step
//! engine consumes.
//!
//! A manifest that does not parse, or whose `run.builtin` id has no
//! operation, is skipped rather than fatal, the way an unreadable skill
//! folder is; each family pins its shipped set with a test.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use async_trait::async_trait;
use rhema_core::{
ReplaySafety, ToolCall, ToolContext, ToolProgress, ToolResolver, ToolResult, ToolSpec,
};
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
/// Why a tool invocation failed: the message the model reads. The
/// registry turns `Err` into an in-band failure result, a failing tool is
/// a result the model reacts to, never a crashed run, so the message is
/// the error's whole content.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{0}")]
pub struct ToolError(String);
impl ToolError {
/// An error whose message the model reads verbatim.
pub fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
/// The message the model reads.
pub fn message(&self) -> &str {
&self.0
}
}
impl From<String> for ToolError {
fn from(message: String) -> Self {
Self(message)
}
}
impl From<&str> for ToolError {
fn from(message: &str) -> Self {
Self(message.to_owned())
}
}
/// One named tool: the spec the model sees, and the invocation the
/// registry dispatches to.
#[async_trait]
pub trait Tool: Send + Sync {
/// The tool's schema, passed through to the provider's native
/// tool-calling format. The description lives here and nowhere else.
fn spec(&self) -> ToolSpec;
/// Whether a resume may re-execute one of this tool's committed calls
/// that lost its result. [`ReplaySafety::Unsafe`] unless declared
/// otherwise: an unclassified tool is treated as side-effecting.
fn replay_safety(&self) -> ReplaySafety {
ReplaySafety::Unsafe
}
/// Runs the tool. The registry turns `Err` into an in-band failure
/// result carrying the error's message; `Ok` text is the tool's
/// answer.
async fn invoke(&self, args: Value) -> Result<String, ToolError>;
}
/// The static half of a tool, parsed from a `TOOL.yaml`.
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest {
/// Name the model uses to call the tool.
pub name: String,
/// What the tool does; the model picks tools from this.
pub description: String,
/// JSON schema for the call arguments; the empty-object schema when
/// the manifest omits it.
pub parameters: Value,
/// Whether a resume may re-execute a committed call that lost its
/// result; [`ReplaySafety::Unsafe`] when the manifest omits it.
pub replay_safety: ReplaySafety,
/// The `run.builtin` id naming the compiled operation.
pub builtin: String,
}
/// Why a `TOOL.yaml` did not parse into a [`Manifest`].
#[derive(Debug, Error)]
#[error("{0}")]
pub struct ManifestError(String);
/// Parses one `TOOL.yaml`. `parameters` defaults to the empty-object
/// schema and `replay_safety` to [`ReplaySafety::Unsafe`], so a minimal
/// manifest is a name, a description, and a `run` binding.
pub fn parse_manifest(raw: &str) -> Result<Manifest, ManifestError> {
let yaml: ManifestYaml =
serde_yaml::from_str(raw).map_err(|err| ManifestError(err.to_string()))?;
let name = yaml.name.trim().to_owned();
if name.is_empty() {
return Err(ManifestError("no tool name".to_owned()));
}
let description = yaml.description.trim().to_owned();
if description.is_empty() {
return Err(ManifestError(format!("{name}: no description")));
}
let builtin = match yaml.run.kind {
RunKind::Builtin { builtin } => builtin.trim().to_owned(),
};
if builtin.is_empty() {
return Err(ManifestError(format!(
"{name}: run.builtin names no operation"
)));
}
let parameters = match yaml.parameters {
Some(value) => serde_json::to_value(&value)
.map_err(|err| ManifestError(format!("{name}: parameters are not JSON: {err}")))?,
None => serde_json::json!({ "type": "object" }),
};
let replay_safety = yaml
.replay_safety
.map(|replay| match replay {
ReplayYaml::Unsafe => ReplaySafety::Unsafe,
ReplayYaml::Safe => ReplaySafety::Safe,
})
.unwrap_or_default();
Ok(Manifest {
name,
description,
parameters,
replay_safety,
builtin,
})
}
/// The operation half of a manifest-defined tool: run the call. The spec
/// half lives in the tool's `TOOL.yaml`, so an operation carries no
/// schema strings of its own.
#[async_trait]
pub trait ToolOp: Send + Sync {
/// Runs the tool. The registry turns `Err` into an in-band failure
/// result; `Ok` text is the tool's answer.
async fn invoke(&self, args: Value) -> Result<String, ToolError>;
}
/// A [`Tool`] cut from a [`Manifest`] plus its registered operation: the
/// model sees the manifest's spec, and the registry dispatches to the
/// operation.
pub struct ManifestTool {
manifest: Manifest,
op: Arc<dyn ToolOp>,
}
impl ManifestTool {
/// Binds `manifest` to the operation `op`.
pub fn new(manifest: Manifest, op: Arc<dyn ToolOp>) -> Self {
Self { manifest, op }
}
}
#[async_trait]
impl Tool for ManifestTool {
fn spec(&self) -> ToolSpec {
ToolSpec::new(
self.manifest.name.clone(),
self.manifest.description.clone(),
self.manifest.parameters.clone(),
)
}
fn replay_safety(&self) -> ReplaySafety {
self.manifest.replay_safety
}
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
self.op.invoke(args).await
}
}
/// Loads `manifests`: `(source, text)` pairs, `source` naming the
/// manifest in skip reports, against the registered `builtins`. A
/// manifest that does not parse, or whose `run.builtin` id has no
/// operation, is skipped and reported; the survivors are ready to
/// register.
pub fn builtin_tools(
manifests: &[(&str, &str)],
builtins: &BTreeMap<String, Arc<dyn ToolOp>>,
) -> (Vec<Arc<dyn Tool>>, Vec<String>) {
let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
let mut skipped = Vec::new();
for (source, raw) in manifests {
let manifest = match parse_manifest(raw) {
Ok(manifest) => manifest,
Err(err) => {
skipped.push(format!("{source}: {err}"));
continue;
}
};
match builtins.get(&manifest.builtin) {
Some(op) => tools.push(Arc::new(ManifestTool::new(manifest, op.clone()))),
None => skipped.push(format!(
"{source}: no builtin operation for {:?}",
manifest.builtin
)),
}
}
(tools, skipped)
}
/// The tool-permission set one handler run is granted. `None` means
/// permissive, every registered tool, which is the resident tier's
/// standing policy: the HTTP surface is the trust boundary.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Allowlist {
allowed: Option<BTreeSet<String>>,
}
impl Allowlist {
/// Every registered tool is permitted.
pub fn permissive() -> Self {
Self { allowed: None }
}
/// Only the named tools are permitted.
pub fn from_tools(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
allowed: Some(names.into_iter().map(Into::into).collect()),
}
}
/// Whether `tool` may be invoked under this allowlist.
pub fn allows(&self, tool: &str) -> bool {
match &self.allowed {
None => true,
Some(allowed) => allowed.contains(tool),
}
}
}
/// The named tool set, from which per-run [`ToolResolver`]s are cut.
#[derive(Default)]
pub struct ToolRegistry {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
impl ToolRegistry {
/// An empty registry.
pub fn new() -> Self {
Self::default()
}
/// Registers a tool under its spec's name; a re-register replaces.
pub fn register(&mut self, tool: Arc<dyn Tool>) {
self.tools.insert(tool.spec().name, tool);
}
/// How many tools are registered.
pub fn len(&self) -> usize {
self.tools.len()
}
/// Whether nothing is registered.
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
/// A resolver over the tools `allowlist` permits: the model sees only
/// those specs, and a call for a forbidden or unknown tool comes back
/// as an in-band failure result.
pub fn resolver_for(&self, allowlist: &Allowlist) -> Arc<dyn ToolResolver> {
Arc::new(FilteredResolver {
tools: self
.tools
.iter()
.filter(|(name, _)| allowlist.allows(name))
.map(|(name, tool)| (name.clone(), tool.clone()))
.collect(),
})
}
}
/// One run's view of the registry: the allowlisted slice, as the seam the
/// step engine consumes.
struct FilteredResolver {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
#[async_trait]
impl ToolResolver for FilteredResolver {
fn specs(&self) -> Vec<ToolSpec> {
self.tools.values().map(|tool| tool.spec()).collect()
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
self.tools
.get(name)
.map(|tool| tool.replay_safety())
.unwrap_or(ReplaySafety::Unsafe)
}
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
let Some(tool) = self.tools.get(&call.name) else {
return ToolResult::failure(&call.id, format!("unknown tool: {}", call.name));
};
match tool.invoke(call.args.clone()).await {
Ok(text) => ToolResult::success(&call.id, text),
Err(err) => ToolResult::failure(&call.id, err.message()),
}
}
}
/// Several resolvers behind one seam: specs concatenate in order, and a
/// call is served by the first resolver offering that tool's name. Tool
/// names should be unique across the chain; on a duplicate, the earlier
/// resolver wins and the later one is unreachable for it.
pub struct ResolverChain {
resolvers: Vec<Arc<dyn ToolResolver>>,
}
impl ResolverChain {
/// A chain serving tools from `resolvers`, in order.
pub fn new(resolvers: Vec<Arc<dyn ToolResolver>>) -> Self {
Self { resolvers }
}
/// The resolver offering `name`, if any.
fn owner(&self, name: &str) -> Option<&Arc<dyn ToolResolver>> {
self.resolvers
.iter()
.find(|resolver| resolver.specs().iter().any(|spec| spec.name == name))
}
}
#[async_trait]
impl ToolResolver for ResolverChain {
fn specs(&self) -> Vec<ToolSpec> {
self.resolvers
.iter()
.flat_map(|resolver| resolver.specs())
.collect()
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
self.owner(name)
.map(|resolver| resolver.replay_safety(name))
.unwrap_or(ReplaySafety::Unsafe)
}
async fn resolve(&self, call: ToolCall, ctx: &ToolContext) -> ToolResult {
match self.owner(&call.name) {
Some(resolver) => resolver.resolve(call, ctx).await,
None => ToolResult::failure(&call.id, format!("unknown tool: {}", call.name)),
}
}
/// Streams through the owning resolver: the shell is long, and its
/// live lines are the reason this chain exists as a seam rather than
/// a filter.
async fn resolve_streaming(
&self,
call: ToolCall,
ctx: &ToolContext,
progress: &mut dyn ToolProgress,
) -> ToolResult {
match self.owner(&call.name) {
Some(resolver) => resolver.resolve_streaming(call, ctx, progress).await,
None => ToolResult::failure(&call.id, format!("unknown tool: {}", call.name)),
}
}
}
/// The `TOOL.yaml` body this module reads.
#[derive(Debug, Deserialize)]
struct ManifestYaml {
name: String,
description: String,
#[serde(default)]
parameters: Option<serde_yaml::Value>,
#[serde(default)]
replay_safety: Option<ReplayYaml>,
run: Run,
}
/// The `run` binding: the kind's field name is the variant, so `builtin`
/// names a compiled operation the consumer registered under that id, and
/// a future kind is another variant.
#[derive(Debug, Deserialize)]
struct Run {
#[serde(flatten)]
kind: RunKind,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RunKind {
Builtin { builtin: String },
}
/// The manifest's `replay_safety`, lowercase to read like the yaml it
/// sits in; maps onto [`ReplaySafety`].
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ReplayYaml {
Unsafe,
Safe,
}
#[cfg(test)]
mod tests {
use super::*;
struct Echo;
#[async_trait]
impl ToolOp for Echo {
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
Ok(args.to_string())
}
}
struct Boom;
#[async_trait]
impl ToolOp for Boom {
async fn invoke(&self, _args: Value) -> Result<String, ToolError> {
Err(ToolError::new("exploded"))
}
}
fn builtins() -> BTreeMap<String, Arc<dyn ToolOp>> {
BTreeMap::from([
("test.echo".to_owned(), Arc::new(Echo) as Arc<dyn ToolOp>),
("test.boom".to_owned(), Arc::new(Boom) as Arc<dyn ToolOp>),
])
}
#[test]
fn a_full_manifest_parses() {
let manifest = parse_manifest(
"name: probe\n\
description: |\n\
\x20 Probe the parser.\n\
parameters:\n\
\x20 type: object\n\
\x20 properties:\n\
\x20 path:\n\
\x20 type: string\n\
\x20 required: [path]\n\
replay_safety: safe\n\
run:\n\
\x20 builtin: test.echo\n",
)
.expect("parses");
assert_eq!(manifest.name, "probe");
assert_eq!(manifest.description, "Probe the parser.");
assert_eq!(
manifest.parameters,
serde_json::json!({
"type": "object",
"properties": { "path": { "type": "string" } },
"required": ["path"]
})
);
assert_eq!(manifest.replay_safety, ReplaySafety::Safe);
assert_eq!(manifest.builtin, "test.echo");
}
#[test]
fn omissions_take_defaults() {
let manifest =
parse_manifest("name: probe\ndescription: Probe.\nrun:\n builtin: test.echo\n")
.expect("parses");
assert_eq!(manifest.parameters, serde_json::json!({ "type": "object" }));
assert_eq!(manifest.replay_safety, ReplaySafety::Unsafe);
}
#[test]
fn blank_fields_and_a_missing_run_are_rejected() {
assert!(parse_manifest("description: Probe.\nrun:\n builtin: test.echo\n").is_err());
assert!(
parse_manifest("name: probe\ndescription: \" \"\nrun:\n builtin: test.echo\n")
.is_err()
);
assert!(
parse_manifest("name: probe\ndescription: Probe.\nrun:\n builtin: \" \"\n").is_err()
);
assert!(parse_manifest("name: probe\ndescription: Probe.\n").is_err());
}
#[test]
fn an_unknown_run_kind_is_rejected_not_silently_dropped() {
let err = parse_manifest("name: probe\ndescription: Probe.\nrun:\n exec: ./run.sh\n")
.expect_err("exec is not a binding");
assert!(
err.to_string().contains("did not match any variant"),
"{err}"
);
}
#[test]
fn loading_resolves_builtins_and_reports_skips() {
let manifests = [
(
"probe",
"name: probe\ndescription: Probe.\nrun:\n builtin: test.echo\n",
),
("bad", "name: bad\ndescription: Probe.\n"),
(
"orphan",
"name: orphan\ndescription: Probe.\nrun:\n builtin: test.nope\n",
),
];
let (tools, skipped) = builtin_tools(&manifests, &builtins());
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "probe");
assert_eq!(skipped.len(), 2, "{skipped:?}");
assert!(skipped[0].starts_with("bad:"), "{skipped:?}");
assert!(skipped[1].contains("test.nope"), "{skipped:?}");
}
#[test]
fn a_loaded_tool_registers_under_its_manifest_name_and_classifies() {
let manifests = [(
"probe",
"name: probe\ndescription: Probe.\nreplay_safety: safe\nrun:\n builtin: test.echo\n",
)];
let (tools, skipped) = builtin_tools(&manifests, &builtins());
assert!(skipped.is_empty(), "{skipped:?}");
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
assert_eq!(registry.len(), 1);
let resolver = registry.resolver_for(&Allowlist::permissive());
assert_eq!(resolver.specs()[0].name, "probe");
assert_eq!(
resolver.replay_safety("probe"),
ReplaySafety::Safe,
"the manifest's classification reaches the resolver"
);
assert_eq!(resolver.replay_safety("unknown"), ReplaySafety::Unsafe);
}
fn call(name: &str) -> ToolCall {
ToolCall {
id: "c1".into(),
name: name.into(),
args: serde_json::json!({ "a": 1 }),
provider_data: Value::Null,
}
}
#[tokio::test]
async fn a_filtered_resolver_hides_what_it_forbids_and_fails_a_call_for_it() {
let (tools, _) = builtin_tools(
&[
(
"echo",
"name: echo\ndescription: Echo.\nrun:\n builtin: test.echo\n",
),
(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
),
],
&builtins(),
);
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
let resolver = registry.resolver_for(&Allowlist::from_tools(["echo"]));
let names: Vec<String> = resolver.specs().iter().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["echo".to_owned()]);
let forbidden = resolver
.resolve(call("boom"), &ToolContext::default())
.await;
assert!(forbidden.is_error);
assert_eq!(forbidden.content, "unknown tool: boom");
}
#[tokio::test]
async fn an_operation_error_is_an_in_band_failure_with_its_message() {
let (tools, _) = builtin_tools(
&[(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
)],
&builtins(),
);
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
let resolver = registry.resolver_for(&Allowlist::permissive());
let result = resolver
.resolve(call("boom"), &ToolContext::default())
.await;
assert!(result.is_error);
assert_eq!(result.content, "exploded");
assert_eq!(result.id, "c1");
}
#[tokio::test]
async fn a_chain_serves_each_name_from_its_own_resolver() {
let (tools, _) = builtin_tools(
&[
(
"echo",
"name: echo\ndescription: Echo.\nreplay_safety: safe\nrun:\n builtin: test.echo\n",
),
(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
),
],
&builtins(),
);
let mut left = ToolRegistry::new();
left.register(tools[0].clone());
let mut right = ToolRegistry::new();
right.register(tools[1].clone());
let chain = ResolverChain::new(vec![
left.resolver_for(&Allowlist::permissive()),
right.resolver_for(&Allowlist::permissive()),
]);
let names: Vec<String> = chain.specs().iter().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["echo".to_owned(), "boom".to_owned()]);
assert_eq!(chain.replay_safety("echo"), ReplaySafety::Safe);
assert_eq!(chain.replay_safety("boom"), ReplaySafety::Unsafe);
assert_eq!(
chain
.resolve(call("echo"), &ToolContext::default())
.await
.content,
r#"{"a":1}"#
);
assert!(
chain
.resolve(call("boom"), &ToolContext::default())
.await
.is_error
);
assert_eq!(
chain
.resolve(call("nope"), &ToolContext::default())
.await
.content,
"unknown tool: nope"
);
}
#[test]
fn an_empty_allowlist_permits_nothing() {
let allowlist = Allowlist::from_tools(Vec::<String>::new());
assert!(!allowlist.allows("bash"));
assert_eq!(Allowlist::default(), Allowlist::permissive());
}
}
+1 -3
View File
@@ -325,7 +325,6 @@ mod tests {
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new(),
},
text_delta("hi"),
],
@@ -349,8 +348,7 @@ mod tests {
0,
TurnEvent::UserMessage {
text: "hello".into(),
images: Vec::new(),
pastes: Vec::new()
images: Vec::new()
}
),
(1, text_delta("hi")),
+15 -14
View File
@@ -9,15 +9,21 @@
#![forbid(unsafe_code)]
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use rhema_host_agent::HostAgentConfig;
use rhema_coding_agent::CodingAgentConfig;
/// The daemon's wiring, provisioned at first use and kept for the
/// process's life — the toolkit's own process-wide cache holds it, so
/// `None` only when provisioning failed, and a failure does not retry.
pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
static WIRED: OnceLock<Option<Arc<rhema_agent_tools::vision::Wiring>>> = OnceLock::new();
/// The daemon's wiring, established at first use and kept for the
/// process's life. `None` only when provisioning failed, cached like
/// every answer this static gives.
pub(crate) fn wired() -> Option<&'static Arc<rhema_agent_tools::vision::Wiring>> {
WIRED
.get_or_init(|| {
rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV")).map(Arc::clone)
})
.as_ref()
}
/// The init file a later provisioner chains through — `None` when the
@@ -30,7 +36,7 @@ pub(crate) fn init_path() -> Option<std::ffi::OsString> {
/// Layers the wiring onto one agent config: the shell env map (the
/// init file, the binary, the staging directory) and the prompt's
/// vision section. A frontend without wiring changes nothing.
pub(crate) fn apply(config: &mut HostAgentConfig) {
pub(crate) fn apply(config: &mut CodingAgentConfig) {
let Some(wired) = wired() else {
return;
};
@@ -46,12 +52,7 @@ mod tests {
/// values are constants, so extending twice is the same map.
#[test]
fn apply_twice_is_apply_once() {
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
rhema_bash::AllowAll,
);
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
apply(&mut config);
let once = config.shell_env.clone();
apply(&mut config);
+5 -27
View File
@@ -395,13 +395,6 @@ impl ClawStore {
"DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2",
params![forge.trim(), account_id.trim()],
)?;
// The cursor goes with the watch, like a repo watch's: a re-add
// is a new watch, and its first pass asks from nothing rather
// than resuming where the old one stopped.
conn.execute(
"DELETE FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3",
params![SCOPE_ACCOUNT, forge.trim(), account_id.trim()],
)?;
Ok(removed == 1)
}
@@ -413,11 +406,6 @@ impl ClawStore {
"DELETE FROM account_watches WHERE account_id = ?1",
params![account_id.trim()],
)?;
// The cursors go with the watches, every forge at once.
conn.execute(
"DELETE FROM watch_cursors WHERE scope = ?1 AND subject = ?2",
params![SCOPE_ACCOUNT, account_id.trim()],
)?;
Ok(removed)
}
@@ -715,9 +703,7 @@ mod tests {
fn a_cursor_is_kept_per_watch_and_moves_forward() {
let store = ClawStore::in_memory().expect("store opens");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
store.cursor(SCOPE_REPO, "gitea", "acme/barn").expect("read"),
None,
"a watch that never polled has no cursor"
);
@@ -726,16 +712,12 @@ mod tests {
.set_cursor(SCOPE_REPO, "gitea", "acme/barn", "2026-10-08T00:00:00Z")
.expect("cursor lands");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
store.cursor(SCOPE_REPO, "gitea", "acme/barn").expect("read"),
Some("2026-10-08T00:00:00Z".to_owned())
);
// Another watch of the same forge is another cursor.
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/quarry")
.expect("read"),
store.cursor(SCOPE_REPO, "gitea", "acme/quarry").expect("read"),
None
);
@@ -743,9 +725,7 @@ mod tests {
.set_cursor(SCOPE_REPO, "gitea", "acme/barn", "2026-10-09T00:00:00Z")
.expect("the cursor advances");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
store.cursor(SCOPE_REPO, "gitea", "acme/barn").expect("read"),
Some("2026-10-09T00:00:00Z".to_owned())
);
@@ -756,9 +736,7 @@ mod tests {
.expect("add");
store.remove("gitea", "acme/barn").expect("remove");
assert_eq!(
store
.cursor(SCOPE_REPO, "gitea", "acme/barn")
.expect("read"),
store.cursor(SCOPE_REPO, "gitea", "acme/barn").expect("read"),
None
);
}
+12 -10
View File
@@ -14,8 +14,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -63,7 +62,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `unwatch_repo`, `list_watches` — specs from the embedded manifests,
/// operations compiled here.
pub fn registry(store: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the watch tool manifests must all load: {skipped:?}"
@@ -197,7 +197,7 @@ mod tests {
fn names(registry: &ToolRegistry) -> Vec<String> {
registry
.resolver_for(&crate::toolkit::Allowlist::permissive())
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive())
.specs()
.into_iter()
.map(|spec| spec.name)
@@ -206,7 +206,8 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!(
@@ -220,7 +221,7 @@ mod tests {
let mut covered = Vec::new();
for (source, raw) in MANIFESTS {
covered.push(
crate::toolkit::parse_manifest(raw)
rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin,
);
@@ -235,7 +236,8 @@ mod tests {
#[test]
fn replay_safety_comes_from_the_manifest() {
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("list_watches"),
rhema_core::ReplaySafety::Safe
@@ -261,7 +263,7 @@ mod tests {
async fn watch_repo_lands_a_row_and_answers_json() {
let store = store();
let tools = registry(store.clone());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let result = resolver
.resolve(
@@ -301,7 +303,7 @@ mod tests {
async fn a_bad_watch_fails_in_band_with_the_reason() {
let store = store();
let tools = registry(store.clone());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| {
resolver.resolve(
@@ -354,7 +356,7 @@ mod tests {
store.add("github", "acme/widgets", None, "").expect("seed");
store.add("gitlab", "group/prop", None, "").expect("seed");
let tools = registry(store.clone());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| {
resolver.resolve(
+3 -10
View File
@@ -13,8 +13,8 @@ use rhema_claw::{ClawConfig, run_once};
/// carrying watches, and the test speaks to the daemon the way an
/// integration would: through the store the routes share.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
let store =
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
let store = rhema_claw::ClawStore::open(dir.path().join("dispatch.db"))
.expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
@@ -22,12 +22,7 @@ fn seed_watch(dir: &tempfile::TempDir, host: &str) {
// the feed from there instead of seeding one at *now* (which a
// never-polled watch does, and which feeds nothing).
store
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.set_cursor(rhema_claw::SCOPE_REPO, "github", "acme/widgets", "2026-10-01T00:00:00Z")
.expect("the cursor seeds");
}
use rhema_core::{Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
@@ -93,8 +88,6 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
+3 -10
View File
@@ -59,8 +59,6 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -69,8 +67,8 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
/// carrying watches, and the test speaks to the daemon the way an
/// integration would: through the store the routes share.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
let store =
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
let store = rhema_claw::ClawStore::open(dir.path().join("dispatch.db"))
.expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
@@ -78,12 +76,7 @@ fn seed_watch(dir: &tempfile::TempDir, host: &str) {
// the feed from there instead of seeding one at *now* (which a
// never-polled watch does, and which feeds nothing).
store
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.set_cursor(rhema_claw::SCOPE_REPO, "github", "acme/widgets", "2026-10-01T00:00:00Z")
.expect("the cursor seeds");
}
+8 -775
View File
@@ -11,14 +11,14 @@ use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use rhema_claw::toolkit::Allowlist;
use rhema_autonomous_agent::Allowlist;
use rhema_claw::watch_tools;
use rhema_claw::{ClawConfig, Daemon};
use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
use rhema_rsd::{ResourceKey, SqliteStore, Store};
use serde_json::{Value, json};
use tokio_stream::StreamExt;
use wiremock::matchers::{method, path, query_param};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
/// The scripted assistant turn: one text reply, nothing else.
@@ -34,7 +34,6 @@ fn reply(text: &str) -> ModelOutput {
fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput {
ModelOutput {
message: Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall {
id: id.to_owned(),
@@ -66,8 +65,6 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
tools_bin: None,
ingest_token: None,
transcript: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
@@ -235,11 +232,9 @@ impl rhema_core::ModelProvider for RecordingProvider {
/// One quiet GitHub repo, for the watches test: an issues list with a
/// single closed issue and a quiet comments feed.
async fn mount_github(server: &MockServer) {
// The issues feed filters by `since` server-side, as GitHub does: a
// watch seeded at *now* sees nothing, and one rewound to before the
// row sees it. Without the filter a fresh watch would replay whatever
// the mock always answers.
let row = json!([{
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([{
"id": 1007,
"number": 7,
"state": "closed",
@@ -251,18 +246,7 @@ async fn mount_github(server: &MockServer) {
"updated_at": "2026-10-02T10:00:00Z",
"closed_at": "2026-10-02T10:00:00Z",
"html_url": "https://github.com/acme/widgets/issues/7"
}]);
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.and(query_param("since", "2026-10-01T00:00:00Z"))
.respond_with(ResponseTemplate::new(200).set_body_json(row))
.with_priority(1)
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
.with_priority(2)
}])))
.mount(server)
.await;
Mock::given(method("GET"))
@@ -514,225 +498,6 @@ async fn a_message_into_a_live_turn_steers_it() {
);
}
/// The session controls: pause holds a key's dispatch (its queued work
/// waits, the inventory says held), resume lifts the hold and the work
/// drains, and abort cuts what runs or drops what waits. The three
/// routes answer the shape the sidebar reads, and none of them reaches
/// into the transcript beyond the cut's own `aborted` marker.
#[tokio::test]
async fn sessions_pause_resume_and_abort_over_http() {
let gate = Arc::new(WireGate::default());
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(GatedProvider::new(gate.clone()))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// The key exists first: the create route is what puts it in the
// inventory, and the controls 404 on a key that is not there.
let created = client
.post(format!("{base}/v1/sessions"))
.json(&json!({"name": "web"}))
.send()
.await
.expect("the create posts");
assert_eq!(created.status(), 201, "the session is created");
let paused = client
.post(format!("{base}/v1/sessions/interactive:web/pause"))
.send()
.await
.expect("the pause posts");
assert_eq!(paused.status(), 200);
assert_eq!(
paused.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "paused": true})
);
// Two messages into the held key: accepted, queued, dispatched by
// nobody, and the inventory says so.
for text in ["first", "second"] {
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({"text": text}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
}
let listed = client
.get(format!("{base}/v1/sessions"))
.send()
.await
.expect("the listing reads");
let sessions: Vec<Value> = listed.json().await.expect("the listing parses");
let web = sessions
.iter()
.find(|row| row["key"] == "interactive:web")
.expect("the key is listed");
assert_eq!(web["paused"], json!(true));
assert_eq!(web["state"], json!("idle"), "held work does not dispatch");
// Abort with nothing running drains the queue and says how much it
// dropped; a second abort is the idempotent no-op.
let aborted = client
.post(format!("{base}/v1/sessions/interactive:web/abort"))
.send()
.await
.expect("the abort posts");
assert_eq!(aborted.status(), 200);
assert_eq!(
aborted.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "cut": false, "dropped": 2})
);
let again = client
.post(format!("{base}/v1/sessions/interactive:web/abort"))
.send()
.await
.expect("the second abort posts");
assert_eq!(
again.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "cut": false, "dropped": 0})
);
let quiet = client
.get(format!("{base}/v1/sessions"))
.send()
.await
.expect("the listing reads");
let sessions: Vec<Value> = quiet.json().await.expect("the listing parses");
let web = sessions
.iter()
.find(|row| row["key"] == "interactive:web")
.expect("the key is listed");
assert_eq!(web["inbox_depth"], json!(0));
// Resume, then a fresh message runs: the hold is gone.
let resumed = client
.post(format!("{base}/v1/sessions/interactive:web/resume"))
.send()
.await
.expect("the resume posts");
assert_eq!(
resumed.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "paused": false})
);
// A live turn, and the abort that cuts it: the stream closes on the
// `aborted` marker and the answer reports the cut.
let events = client
.get(format!("{base}/v1/sessions/interactive:web/events"))
.send()
.await
.expect("the events request goes out");
let mut stream = sse_body(events).await;
let mut seen = String::new();
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({"text": "hello"}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
let mut in_flight = gate.in_flight_rx();
while !*in_flight.borrow_and_update() {
in_flight
.changed()
.await
.expect("the in-flight sender lives");
}
let cut = client
.post(format!("{base}/v1/sessions/interactive:web/abort"))
.send()
.await
.expect("the abort posts");
assert_eq!(
cut.json::<Value>().await.expect("the answer parses"),
json!({"key": "interactive:web", "cut": true, "dropped": 0})
);
read_until(&mut stream, &mut seen, "\"aborted\"").await;
assert!(seen.contains("\"outcome\":\"aborted\""), "seen: {seen}");
// Unknown keys are 404 on all three, and the inventory survives.
for verb in ["pause", "resume", "abort"] {
let missing = client
.post(format!("{base}/v1/sessions/nope:gone/{verb}"))
.send()
.await
.expect("the route answers");
assert_eq!(missing.status(), 404, "{verb} on an unknown key");
}
}
/// An abort on an idle `job:` key drops the queued delivery *and*
/// lands the row: the coding job's table is the jobs' truth, so a row
/// whose only delivery was dropped must not sit queued forever — it
/// fails with `aborted`, the same word the handler's own cut uses.
#[tokio::test]
async fn an_abort_on_a_queued_job_key_fails_its_row() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, Some("sekrit")),
mock_registry(Arc::new(MockProvider::new(Vec::new()))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let auth = |request: reqwest::RequestBuilder| {
request.header(reqwest::header::AUTHORIZATION, "Bearer sekrit")
};
// The row the job's table holds — enqueued through the store the
// daemon reads, quiet: nothing runs, the daemon's own loop is not
// started in this test.
let jobs = rhema_claw::job_store::CodingJobStore::open(dir.path().join("dispatch.db"))
.expect("the job store opens");
jobs.add_instance("rhema", "/tmp")
.expect("the instance lands");
let job = jobs
.enqueue("rhema", "tidy the crate")
.expect("the job queues");
assert_eq!(job.status, rhema_claw::job_store::JobStatus::Queued);
// Whatever would dispatch it sits on the key: the jobs source's own
// delivery, stood in for by the external ingest door.
let ingested = auth(client.post(format!("{base}/v1/ingest")))
.json(&json!({
"source": "phone",
"key": format!("job:rhema#{}", job.id),
"payload": {"job_id": job.id},
}))
.send()
.await
.expect("the event posts");
assert_eq!(ingested.status(), 202);
let aborted: Value =
auth(client.post(format!("{base}/v1/sessions/job:rhema%23{}/abort", job.id)))
.send()
.await
.expect("the abort posts")
.json()
.await
.expect("the answer parses");
assert_eq!(
aborted,
json!({"key": format!("job:rhema#{}", job.id), "cut": false, "dropped": 1}),
"{aborted}"
);
let row = jobs
.job(job.id)
.expect("the row reads")
.expect("the row is there");
assert_eq!(row.status, rhema_claw::job_store::JobStatus::Failed);
assert_eq!(row.result.as_deref(), Some("aborted"));
}
/// A chat message with images: the route enforces the budget (media
/// type, non-empty body, decoded size, count), the transcript's
/// user_message card names the stored ids and media types, and each id
@@ -890,77 +655,6 @@ async fn chat_messages_carry_images_into_the_attachment_store() {
);
}
/// A staged chip rides beside its draft and records as spans: the
/// echo on the stream and the stashed session both carry the plain
/// text with the `rhema-code` annotation beside it, and no mark ever
/// crosses the wire.
#[tokio::test]
async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
let provider = Arc::new(MockProvider::new([reply("on it")]));
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(provider),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// The chip rides as a payload beside the plain draft.
let accepted = client
.post(format!("{base}/v1/sessions/interactive:web/messages"))
.json(&json!({
"text": "review this:",
"pastes": ["fn main() {}\nfn other() {}"],
}))
.send()
.await
.expect("the message posts");
assert_eq!(accepted.status(), 202);
// The echo on the stream: the payload in place, the span record
// beside it, no marks in the text.
let events = client
.get(format!("{base}/v1/sessions/interactive:web/events"))
.send()
.await
.expect("the events request goes out");
let mut stream = sse_body(events).await;
let mut seen = String::new();
read_until(&mut stream, &mut seen, r#""type":"turn_done""#).await;
assert!(
seen.contains(r#""type":"user_message","text":"review this:fn main() {}\nfn other() {}""#),
"the echo carries the composed plain form: {seen}"
);
assert!(
seen.contains(r#""pastes":[{"start":12,"end":38,"lines":2}]"#),
"the chip notes itself as the span it stands for: {seen}"
);
assert!(!seen.contains('\u{FFFC}'), "no marks ride the wire: {seen}");
// The stash: the checkpoint's user message carries the payload in
// the text and the annotation that outlives the turn.
let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
let key = ResourceKey::from("interactive:web");
let record = store
.load(&key)
.expect("the record loads")
.expect("the key has a record");
let stashed: Session =
serde_json::from_value(record.session.expect("a session").core.driver_state)
.expect("the stash parses");
let ask = stashed
.history
.iter()
.find(|message| message.role == Role::User)
.expect("the question is stashed");
assert_eq!(rhema_claw::paste::spans(ask).len(), 1);
assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_claw::paste::spans(ask)[0].lines, 2);
}
/// A turn nobody watched is still replayable: a client arriving after
/// the fact — a reloaded browser, a reopened phone — subscribes cold and
/// gets the finished turns back before the live feed. The same holds
@@ -1425,12 +1119,7 @@ async fn watches_added_over_http_feed_the_next_detect_pass() {
// Rewound to before the feed's rows — an established watch — the same
// pass detects the feed's event.
Arc::new(rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("reopens"))
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.set_cursor(rhema_claw::SCOPE_REPO, "github", "acme/widgets", "2026-10-01T00:00:00Z")
.expect("the cursor rewinds");
let report = daemon.tick().await.expect("the pass runs");
assert_eq!(report.detected, 1, "the new watch's feed event was fed");
@@ -2531,252 +2220,6 @@ async fn providers_gain_and_lose_backends_over_the_surface() {
assert_eq!(gone.status(), 400);
}
/// The sandbox surface: the default is this host, a remote choice
/// persists across a rebuild, the token is write-only, and a choice
/// without a URL or with an unknown kind is refused.
#[tokio::test]
async fn the_sandbox_choice_is_listed_and_switchable() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let listed: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(listed["kind"], "local");
assert_eq!(listed["token_set"], false);
assert_eq!(listed["remote_workspace"], "/workspace");
assert!(
listed["workspace"]
.as_str()
.is_some_and(|path| !path.is_empty())
);
// A remote choice: the URL and token go in, the token never comes
// back.
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "http",
"url": "https://box.example:7600/",
"token": "s3cret"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "http");
assert_eq!(switched["url"], "https://box.example:7600");
assert_eq!(switched["token_set"], true);
assert_eq!(switched["workspace"], "/workspace");
assert!(
switched.get("token").is_none(),
"the token stays write-only"
);
// A remote choice without a URL is a 400, and an unknown kind too.
let missing = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "http", "url": ""}))
.send()
.await
.expect("the refusal posts");
assert_eq!(missing.status(), 400);
let unknown = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "quantum"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(unknown.status(), 400);
// Back to this host: the remote fields stay staged for the next
// switch, and the workspace path flips with the choice.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["token_set"], true);
// The persisted choice wins after a restart.
drop(base);
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon rebuilds");
let base = serve(&daemon).await;
let reloaded: Value = client
.get(format!("{base}/v1/sandbox"))
.send()
.await
.expect("the sandbox reads")
.json()
.await
.expect("the sandbox parses");
assert_eq!(reloaded["kind"], "local");
assert_eq!(reloaded["token_set"], true);
// `clear_token` drops the stored secret without moving the URL.
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local", "clear_token": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["token_set"], false);
assert_eq!(cleared["url"], "https://box.example:7600");
}
/// The ssh sandbox over the surface: a choice without a host is a 400,
/// a complete one lists its host and reports the workspace under the
/// configured base, and switching back to this host keeps the ssh
/// fields staged for the next switch. The private key rides the same
/// write-only contract the token has: it goes in, a bit comes back,
/// and `clear_private_key` drops it without moving the host.
#[tokio::test]
async fn the_ssh_sandbox_is_switchable_over_the_surface() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let refused = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(refused.status(), 400, "an ssh choice without a host");
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "workspace": "/srv/claw"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "ssh");
assert_eq!(switched["host"], "me@box.example");
let workspace = switched["workspace"].as_str().expect("the workspace reads");
assert!(
workspace.starts_with("/srv/claw/rhema-claw-"),
"the workspace sits under the configured base: {workspace}"
);
// The private key rides the same route: it goes in as the key
// text (the store-held credential, no file to stage), only the
// `private_key_set` bit comes back, and an absent field leaves
// the stored key alone the way the token's partial save does.
let keyed: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "ssh",
"host": "me@box.example",
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(keyed["private_key_set"], true);
assert!(
keyed.get("private_key").is_none(),
"the key stays write-only"
);
// A present-but-blank key clears the stored one, the token's
// exact contract: absent keeps, present replaces, even blank.
let blank: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "private_key": " "}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(blank["private_key_set"], false);
// The key is gone now, so set it again before the clear step:
// `clear_private_key` drops the stored key without moving the
// host.
let _again: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "ssh",
"host": "me@box.example",
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n"
}))
.send()
.await
.expect("the re-set posts")
.json()
.await
.expect("the re-set parses");
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "clear_private_key": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["private_key_set"], false);
assert_eq!(cleared["host"], "me@box.example");
// Back to this host: the workspace flips, the ssh fields stay
// staged for the next switch.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["host"], "me@box.example");
assert!(
local["workspace"].as_str().expect("the workspace reads") != workspace,
"the workspace path follows the choice"
);
}
/// The agent identity surface: the text fields round-trip with
/// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type,
@@ -2807,7 +2250,7 @@ async fn the_agent_identity_is_editable_over_the_surface() {
// A save names the fields it touches.
let saved: Value = client
.put(format!("{base}/v1/agent"))
.json(&json!({"name": "Kosmos", "email": "kosmos@example.net", "mark": "✦", "tagline": "order"}))
.json(&json!({"name": "Kosmos", "mark": "✦", "tagline": "order"}))
.send()
.await
.expect("the save posts")
@@ -2816,7 +2259,6 @@ async fn the_agent_identity_is_editable_over_the_surface() {
.expect("the save parses");
assert_eq!(saved["name"], "Kosmos");
assert_eq!(saved["mark"], "✦");
assert_eq!(saved["email"], "kosmos@example.net");
assert_eq!(saved["avatar"], false);
// A partial save leaves the fields it omitted.
@@ -2831,10 +2273,6 @@ async fn the_agent_identity_is_editable_over_the_surface() {
.expect("the partial save parses");
assert_eq!(partial["name"], "Kosmos Prime");
assert_eq!(partial["mark"], "✦", "untouched by the partial save");
assert_eq!(
partial["email"], "kosmos@example.net",
"untouched by the partial save"
);
// An empty string clears its field.
let cleared: Value = client
@@ -3836,29 +3274,6 @@ async fn a_restart_releases_a_dead_lease_and_the_key_answers() {
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// The turn the restart cut is not left wearing an outcome it never
// earned: recovery releases it as superseded, and the read-only
// transcript ends the turn aborted, not handled.
let thread: Value = client
.get(format!("{base}/v1/sessions/interactive:web/history"))
.send()
.await
.expect("the history request goes out")
.json()
.await
.expect("the history body parses");
let closes: Vec<&Value> = thread["events"]
.as_array()
.expect("events is a list")
.iter()
.filter(|event| event["event"]["type"] == "turn_done")
.collect();
let last = closes.last().map(|event| event["event"]["outcome"].clone());
assert!(
last.as_ref().is_none_or(|outcome| outcome == "aborted"),
"a cut turn is not handled: {thread}"
);
// The key reads idle, not leased: the ghost lease is gone.
let sessions: Value = client
.get(format!("{base}/v1/sessions"))
@@ -4119,185 +3534,3 @@ async fn a_leased_session_is_not_deletable() {
assert_eq!(sessions[0]["key"], "interactive:web");
assert_eq!(sessions[0]["state"], "leased", "{sessions:?}");
}
/// The turn a restart cut must not wear the previous turn's outcome. A
/// record keeps the outcome of its last release, so a dispatch that
/// checkpointed its prompt and the model's first words and then died
/// would read back as "handled" beside text it never finished: handled
/// is what the turn before it was. Boot releases the dead lease as
/// superseded, and the transcript says aborted.
#[tokio::test]
async fn a_restart_cut_turn_reads_aborted_not_the_previous_outcome() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("dispatch.db");
let key = ResourceKey::from("github:pull:acme/widgets#2");
{
let store = SqliteStore::open(&db).expect("the store opens");
let mut record = rhema_rsd::KeyRecord::fresh(key.clone(), 1);
let mut session = rhema_rsd::Session::fresh(key.clone(), 1);
session.core.history = vec![
Message::text(Role::User, "address the review feedback"),
Message::text(Role::Assistant, "I'll start by looking at the workspace."),
];
record.session = Some(session);
// The dispatch before this one finished handled, and its release
// is the record's last outcome.
record.last_outcome = Some(rhema_rsd::Outcome::Handled);
// This one held a lease when the process died.
record.state = rhema_rsd::KeyState::Leased;
record.lease = Some(rhema_rsd::LeaseRecord {
id: rhema_rsd::LeaseId::new("lease-old"),
holder: "the-old-process".to_owned(),
acquired_at: 1,
expires_at: u64::MAX,
});
store.save(record, None).expect("the record seeds");
}
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
daemon.bootstrap().await.expect("recovery runs");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let body: Value = client
.get(format!(
"{base}/v1/sessions/github%3Apull%3Aacme%2Fwidgets%232/history"
))
.send()
.await
.expect("the history request goes out")
.json()
.await
.expect("the history body parses");
let events = body["events"].as_array().expect("events is a list");
let close = events
.iter()
.find(|event| event["event"]["type"] == "turn_done")
.expect("the cut turn closes");
assert_eq!(
close["event"]["outcome"], "aborted",
"the cut turn is not the handled turn before it: {body}"
);
assert_eq!(
close["event"]["reply"], "I'll start by looking at the workspace.",
"what the turn said before it was cut still reads: {body}"
);
}
/// A key the resident context does not own has no turn record: its
/// handler never streams, and the events route refuses it. The history
/// route still opens it, read-only, from the session stash the step
/// engine checkpointed — the same page shape, cut the same way, so a
/// chat surface paints a finished forge thread with its own renderer.
#[tokio::test]
async fn a_forge_thread_reads_back_as_a_read_only_snapshot() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("dispatch.db");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
// What a finished dispatch leaves behind: the engine's own history
// in the record's session stash.
let key = ResourceKey::from("github:issue:acme/widgets#7");
{
let store = SqliteStore::open(&db).expect("the store opens");
let mut record = rhema_rsd::KeyRecord::fresh(key.clone(), 1);
let mut session = rhema_rsd::Session::fresh(key.clone(), 1);
session.core.history = vec![
Message::text(Role::User, "review the failing check"),
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(rhema_core::ToolCall {
id: "call-1".to_owned(),
name: "bash".to_owned(),
args: json!({"command": "gh pr checks 7"}),
provider_data: Value::Null,
})],
},
Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(rhema_core::ToolResult {
id: "call-1".to_owned(),
content: "build\tfail\t2m".to_owned(),
is_error: false,
code: Some(1),
images: Vec::new(),
})],
},
Message::text(Role::Assistant, "The build is red; rerunning."),
];
record.session = Some(session);
record.last_outcome = Some(rhema_rsd::Outcome::Handled);
store.save(record, None).expect("the record seeds");
}
let page = client
.get(format!(
"{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/history"
))
.send()
.await
.expect("the history request goes out");
assert_eq!(page.status(), 200, "a stash has a transcript to read");
let body: Value = page.json().await.expect("the body parses");
assert_eq!(body["read_only"], true, "the client must not open a stream");
assert_eq!(body["more"], false);
let events = body["events"].as_array().expect("events is a list");
let types: Vec<&str> = events
.iter()
.map(|entry| entry["event"]["type"].as_str().expect("a type"))
.collect();
assert_eq!(
types,
[
"user_message",
"tool_start",
"tool_result",
"text_delta",
"turn_done"
],
"{events:?}"
);
assert_eq!(events[0]["event"]["text"], "review the failing check");
assert_eq!(events[2]["event"]["name"], "bash");
assert_eq!(
events[2]["event"]["command"], "gh pr checks 7",
"the shell's command line survives the stash"
);
assert_eq!(events[2]["event"]["code"], 1);
assert_eq!(events[4]["event"]["reply"], "The build is red; rerunning.");
// Read-only for real: the message route still refuses the prefix,
// and the stream route refuses it too — a client that followed
// `read_only=false` would retry a 400 forever.
let refused = client
.post(format!(
"{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/messages"
))
.json(&json!({"text": "hello"}))
.send()
.await
.expect("the message posts");
assert_eq!(refused.status(), 400);
let stream = client
.get(format!(
"{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/events"
))
.send()
.await
.expect("the events request goes out");
assert_eq!(stream.status(), 400);
}
-222
View File
@@ -1,222 +0,0 @@
//! The mention gate, end to end: a comment that names the daemon runs a
//! turn and posts a reply; a comment that names nobody is drained and
//! ignored — no snapshot, no model call, no comment. Zero network.
use std::sync::Arc;
use rhema_claw::{ClawConfig, run_once};
use rhema_core::{Message, MockProvider, ModelOutput, Role, StopReason, Usage};
use rhema_rsd::Outcome;
use serde_json::{Value, json};
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
/// The one issue the tests watch, updated inside the seeded cursor's
/// window so the pass sees it as news alongside the comment.
fn issue_row() -> Value {
json!({
"id": 1007,
"number": 7,
"state": "open",
"title": "crash on save",
"user": { "login": "alice" },
"labels": [],
"body": "steps to reproduce…",
"created_at": "2026-10-01T09:00:00Z",
"updated_at": "2026-10-02T10:00:00Z",
"closed_at": null,
"html_url": "https://github.com/acme/widgets/issues/7"
})
}
/// A comment on thread 7: the author and the body are the test's subject.
fn comment_row(author: &str, body: &str) -> Value {
json!({
"id": 8001,
"user": { "login": author },
"body": body,
"created_at": "2026-10-03T09:00:00Z",
"updated_at": "2026-10-03T09:00:00Z",
"issue_url": "https://api.github.com/repos/acme/widgets/issues/7",
"html_url": "https://github.com/acme/widgets/issues/7#issuecomment-8001"
})
}
fn reply(text: &str) -> ModelOutput {
ModelOutput {
message: Message::text(Role::Assistant, text),
stop_reason: StopReason::EndTurn,
usage: Usage::default(),
}
}
fn config(dir: &tempfile::TempDir) -> ClawConfig {
ClawConfig {
db: Some(dir.path().join("dispatch.db")),
workspace_root: Some(dir.path().join("workspaces")),
memory_root: None,
bootstrap_root: None,
poll_interval_secs: 60,
max_turn_steps: rhema_claw::config::DEFAULT_MAX_TURN_STEPS,
provider: Some("google".to_owned()),
model: Some("test-model".to_owned()),
listen: None,
token: None,
agent_token: None,
tools_bin: None,
transcript: None,
ingest_token: None,
sandbox: None,
git: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
/// An established watch: the cursor is what makes the pass read the feed
/// as news rather than seeding a start line at *now*.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
let store =
rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
store
.set_cursor(
rhema_claw::SCOPE_REPO,
"github",
"acme/widgets",
"2026-10-01T00:00:00Z",
)
.expect("the cursor seeds");
}
/// The feeds every pass reads, plus the forge's answer to "who am I" —
/// the watch's token is a bare value that names nobody, so the mention
/// gate asks the forge rather than guess.
async fn mount_repo(server: &MockServer, author: &str, comment: &str) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([issue_row()])))
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues/comments"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([comment_row(author, comment)])),
)
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos" })))
.mount(server)
.await;
}
/// The orientation call the turn makes once the gate has opened.
async fn mount_snapshot(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues/7"))
.respond_with(ResponseTemplate::new(200).set_body_json(issue_row()))
.mount(server)
.await;
}
/// The headline case: "hey @kosmos, can you take a look at this?" — one
/// comment addressed by name, one turn, one reply.
#[tokio::test]
async fn a_comment_that_names_the_daemon_runs_a_turn() {
let server = MockServer::start().await;
mount_repo(&server, "dave", "hey @kosmos can you take a look at this?").await;
mount_snapshot(&server).await;
let posted = Mock::given(method("POST"))
.and(path("/repos/acme/widgets/issues/7/comments"))
.and(body_partial_json(json!({ "body": "on it" })))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 })))
.expect(1)
.mount_as_scoped(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(report.outcomes, vec![Outcome::Handled]);
drop(posted);
}
/// The gate's whole point: somebody else's conversation on a watched
/// repository is context, not a request. The news is drained and dropped
/// — and the snapshot is deliberately not mocked, so a dispatch that got
/// past the gate would fail loudly instead of posting quietly.
#[tokio::test]
async fn a_comment_that_names_nobody_runs_nothing() {
let server = MockServer::start().await;
mount_repo(&server, "dave", "any progress on this?").await;
let posted = Mock::given(method("POST"))
.and(path("/repos/acme/widgets/issues/7/comments"))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 })))
.expect(0)
.mount_as_scoped(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(
report.outcomes,
vec![Outcome::Superseded],
"nothing was asked, and nothing ran"
);
drop(posted);
}
/// Our own replies are news too — and they quote the mention they answer.
/// Without the actor check, every answer would open the gate for the next
/// turn: the daemon talking to itself, forever.
#[tokio::test]
async fn the_daemons_own_reply_does_not_reopen_the_gate() {
let server = MockServer::start().await;
// Written by the daemon itself, quoting the mention it answers.
mount_repo(
&server,
"kosmos",
"> hey @kosmos can you take a look?\n\nDone — branch pushed.",
)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(
report.outcomes,
vec![Outcome::Superseded],
"the daemon answered itself"
);
}
/// A registry whose only backend is the scripted mock — the shape every
/// integration test runs on.
fn mock_registry(provider: Arc<dyn rhema_core::ModelProvider>) -> Arc<rhema_claw::BackendRegistry> {
Arc::new(
rhema_claw::BackendRegistry::new(
vec![rhema_claw::Backend::headless("mock", provider)],
None,
)
.expect("a single mock backend always constructs"),
)
}
+5 -11
View File
@@ -3,12 +3,11 @@
name: identity_set
description: >-
Set your own presentation identity: the name, mark, initials,
tagline, and signoff the interfaces render, an email to commit and
write as, and your avatar or logo images. This is how you look, not
who you are — personality lives in SOUL.md. Leave a field out to
keep what is set; an empty string clears it. The avatar and logo
take a workspace-relative path to an image file (png, jpeg, gif, or
webp, under 2 MiB — svg is refused).
tagline, and signoff the interfaces render, and your avatar or logo
images. This is how you look, not who you are — personality lives in
SOUL.md. Leave a field out to keep what is set; an empty string
clears it. The avatar and logo take a workspace-relative path to an
image file (png, jpeg, gif, or webp, under 2 MiB — svg is refused).
parameters:
type: object
properties:
@@ -17,11 +16,6 @@ parameters:
description: >-
Display name: message author, window title, notifications. Up
to 64 chars.
email:
type: string
description: >-
The author address on the commits your workspaces make. Up to
120 chars.
mark:
type: string
description: Glyph or emoji for the rail and favicon. Up to 8 chars.
+2 -25
View File
@@ -48,26 +48,9 @@ FROM debian:stable-slim
# bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& apt-get install -y --no-install-recommends bash git ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# gob (github.com/juanibiapina/gob) is the agent's process manager: a turn
# starts a dev server or a build with `gob add`, and a later turn reads its
# logs, status and ports. Without it a long command either blocks the turn
# for its whole run or is backgrounded with `&`, which no later turn can
# find again. The release is a static binary, so nothing rides along but
# the file; its state lands under XDG_STATE_HOME (/data/state, the volume)
# and its socket under XDG_RUNTIME_DIR. Only amd64 and arm64 are published,
# and a build for any other arch fails here rather than shipping a daemon
# with no `gob` on PATH.
ARG GOB_VERSION=3.9.0
RUN arch="$(dpkg --print-architecture)" \
&& curl -fsSL -o /tmp/gob.tar.gz \
"https://github.com/juanibiapina/gob/releases/download/v${GOB_VERSION}/gob_${GOB_VERSION}_linux_${arch}.tar.gz" \
&& tar -xzf /tmp/gob.tar.gz -C /usr/local/bin gob \
&& rm /tmp/gob.tar.gz \
&& gob --version
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
RUN useradd --uid 1000 --user-group --create-home claw \
&& install -d -o 1000 -g 1000 /config /data
@@ -76,14 +59,8 @@ COPY --from=builder /build/target/release/rhema-claw /usr/local/bin/rhema-claw
# The chart passes --config /config/claw.yaml (the ConfigMap mount) and
# mounts the state PVC at /data; these defaults serve a bare `docker run`.
#
# XDG_RUNTIME_DIR is gob's socket directory. Left unset, gob looks in
# /run/user/1000, which nothing creates here, and its daemon dies with
# "socket not created". A socket does not belong on the volume (an NFS
# PVC cannot hold one), so it lives in the container's own /tmp.
ENV XDG_CONFIG_HOME=/config \
XDG_STATE_HOME=/data/state \
XDG_RUNTIME_DIR=/tmp/run
XDG_STATE_HOME=/data/state
VOLUME /data
EXPOSE 7799
+1 -1
View File
@@ -67,7 +67,7 @@ FROM debian:stable-slim
# load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
# neither).
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& apt-get install -y --no-install-recommends bash git ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+2 -2
View File
@@ -3,5 +3,5 @@ name: rhema-claw
description: "The resident forge-watching agent daemon: forge watches and a
chat HTTP surface over one SQLite store."
type: application
version: 0.4.1
appVersion: "0.4.1"
version: 0.1.0
appVersion: "0.1.0"
-8
View File
@@ -31,14 +31,6 @@ config:
# - forge: github
# repo: acme/widgets
watches: []
# The git identity the daemon writes into its user's global git
# config at boot, so workspace commits carry the agent as author.
# A field set here wins over the agent's own identity (Agent ·
# General in the UI); values the daemon did not write are left
# alone. Example:
# git:
# name: claw
# email: claw@example.net
service:
type: ClusterIP
@@ -15,20 +15,20 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's
rhema-autonomous-agent = "0.4.2"
rhema-autonomous-agent = "0.2.3"
# The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's
rhema-rsd = "0.4.2"
rhema-rsd = "0.2.3"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
async-trait = { workspace = true }
# HTTP against the three feed kinds: one bounded request per poll, no
# streaming
reqwest = { version = "0.13", features = ["json", "query"] }
reqwest = { version = "0.12", features = ["json"] }
# The CalDAV adapter reads 207 multistatus bodies; the element set it
# cares about is small enough that a pull parser beats a DOM
quick-xml = "0.42"
quick-xml = "0.41"
# Every wire time (RFC 3339, iCalendar's compact `YYYYMMDDTHHMMSS[Z]`,
# `VALUE=DATE` all-days) normalizes to an OffsetDateTime, and the
# vocabulary's instants round-trip as RFC 3339.
@@ -186,9 +186,10 @@ fn compact_z(at: OffsetDateTime) -> String {
/// namespace URIs the element binds. Matching local names inside a
/// `prop` stat is the pragmatic read every DAV client ships.
fn local_name(name: quick_xml::name::QName<'_>) -> &str {
// The reader was built from a &str, so a borrowed name is valid
// UTF-8 by construction; no decode step can fail here.
name.local_name().into_inner()
// The reader was built from a &str, so every borrowed name is
// UTF-8 already; a decoding failure cannot say anything truer than
// "not the element we were looking for".
std::str::from_utf8(name.local_name().into_inner()).unwrap_or("")
}
/// Pulls every `calendar-data` value out of a 207 multistatus, in
@@ -214,8 +215,10 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
// where the iCalendar needs CRLF, and an unexpanded
// reference would fold the whole object into one line
// and read as quietly empty.
let content = text.xml10_content();
let decoded = unescape(&content)
let decoded = text
.xml10_content()
.map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?;
let decoded = unescape(&decoded)
.map_err(|err| CalendarError::Parse(format!("multistatus text: {err}")))?;
current.push_str(&decoded);
}
@@ -225,7 +228,9 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
Ok(Some(ch)) => current.push(ch),
// A named entity (`&amp;`): the escape table's.
Ok(None) => {
let raw = reference.xml10_content();
let raw = reference.xml10_content().map_err(|err| {
CalendarError::Parse(format!("multistatus text: {err}"))
})?;
let entity = format!("&{raw};");
let decoded = unescape(&entity).map_err(|err| {
CalendarError::Parse(format!("multistatus text: {err}"))
@@ -238,7 +243,7 @@ fn parse_multistatus(xml: &str) -> Result<Vec<String>, CalendarError> {
}
}
Ok(XmlEvent::CData(text)) if capturing => {
current.push_str(&text);
current.push_str(&String::from_utf8_lossy(text.as_ref()));
}
Ok(XmlEvent::End(element)) => {
if capturing && local_name(element.name()) == "calendar-data" {
@@ -13,14 +13,14 @@ publish = false
[dependencies]
# The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = "0.4.2"
rhema-rsd = "0.2.3"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
async-trait = { workspace = true }
# HTTP against the three forge REST APIs: JSON request/response bodies,
# no streaming
reqwest = { version = "0.13", features = ["json", "query"] }
reqwest = { version = "0.12", features = ["json"] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
@@ -230,17 +230,6 @@ pub struct Notification {
/// When the notification row was last touched. The poll cursor
/// advances to the newest of these.
pub timestamp: Timestamp,
/// What the backend's read-marking route keys on, when it has one —
/// GitHub's `PUT /notifications/threads/{id}` takes the numeric
/// notification id, which [`Notification::id`] embeds only as text
/// (its suffix is the dedup timestamp, not the row's identity).
/// `None` on a backend with no read route.
///
/// Defaulted on deserialize: rows already in a dispatcher inbox were
/// written before this field existed, and a replay must not fail on
/// one.
#[serde(default)]
pub read_key: Option<String>,
/// The untouched wire row, minus the keys the notification lifts.
pub raw: serde_json::Value,
}
@@ -408,9 +397,7 @@ impl Timestamp {
let raw = if sub_millis == 0 {
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
} else {
format!(
"{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{sub_millis:03}Z"
)
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{sub_millis:03}Z")
};
Self::parse(&raw)
}
@@ -16,9 +16,7 @@
use async_trait::async_trait;
use crate::error::ForgeError;
use crate::event::{
ForgeEvent, ForgeThreadKind, Notification, NotificationPage, RepoRef, Snapshot, Timestamp,
};
use crate::event::{ForgeEvent, ForgeThreadKind, NotificationPage, RepoRef, Snapshot, Timestamp};
/// One poll's worth of activity, with the cursor to continue from.
#[derive(Debug, Clone, PartialEq)]
@@ -101,38 +99,6 @@ pub trait Forge: Send + Sync {
&self,
since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>;
/// Marks `notification` read on the forge, so the account's feed
/// stops returning it.
///
/// The feed is at-least-once: `since` is inclusive at the boundary
/// and the cursor only ever advances to the newest row seen, so a row
/// that the poll cannot get past — anything at or before the cursor,
/// every poll — comes back for as long as the forge considers it
/// unread. Dedup ids absorb a repeat *within* one pass, but a row
/// re-read on the next pass is a fresh event with the same id, and a
/// restart drops the in-memory cursor entirely and asks for the whole
/// unread feed again. Deciding a row is therefore not the same as
/// consuming it; this is the call that consumes it.
///
/// The default is a no-op: a backend with no read route repeats its
/// rows, which its dedup ids absorb — noisier, never wrong.
async fn mark_read(&self, _notification: &Notification) -> Result<(), ForgeError> {
Ok(())
}
/// The login this client authenticates as — the backend's own answer
/// to "who am I".
///
/// A consumer that must recognize its own handle (to see an @-mention
/// in a body, and to ignore its own replies) cannot always read it off
/// its credential: a token pasted into a watch row, or an environment
/// variable, names nobody. `None` is the honest default — a backend
/// with no such route simply cannot say who it is — and a backend that
/// can say answers with its `/user` row.
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
Ok(None)
}
}
#[cfg(test)]
@@ -520,10 +520,7 @@ fn comment_urls(row: &WireComment) -> [Option<&str>; 3] {
/// number is therefore read from the first URL that carries one, in
/// order of directness.
fn comment_parent(row: &WireComment) -> Option<u64> {
comment_urls(row)
.into_iter()
.flatten()
.find_map(parent_number)
comment_urls(row).into_iter().flatten().find_map(parent_number)
}
/// [`comment_parent`]'s "is it a pull request" half: `pull_request_url`
@@ -585,9 +582,6 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(),
url: None,
timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()),
}))
}
@@ -729,11 +723,6 @@ impl Forge for GiteaForge {
Ok(())
}
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
let user: WireUser = decode(self.send(self.get("/user")).await?).await?;
Ok(user.login.filter(|login| !login.trim().is_empty()))
}
async fn snapshot(
&self,
repo: &RepoRef,
@@ -120,17 +120,6 @@ impl GitHubForge {
}
}
/// A PUT builder for `path` with auth applied.
fn put(&self, path: &str) -> reqwest::RequestBuilder {
let base = &self.base_url;
let request = self.http.put(format!("{base}{path}"));
if self.token.is_empty() {
request
} else {
request.bearer_auth(&self.token)
}
}
/// Follows `per_page`/`page` pagination until a short page.
async fn paged<T: DeserializeOwned>(
&self,
@@ -298,9 +287,7 @@ struct WireComment {
/// One row of the account notifications feed.
#[derive(Debug, Clone, Deserialize)]
struct WireNotification {
/// GitHub sends this one as a JSON string, unlike every other id in
/// this adapter; see [`lenient_id`].
#[serde(default, deserialize_with = "lenient_id")]
#[serde(default)]
id: Option<i64>,
#[serde(default)]
reason: Option<String>,
@@ -465,32 +452,6 @@ fn parent_number(url: &str) -> Option<u64> {
url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
}
/// An id that arrives as either a JSON number or a JSON string.
///
/// GitHub's notifications feed is the odd one out: `id` there is a
/// string (`"27210544329"`), while issues, comments and reviews send
/// numbers. One row that refuses to decode fails the whole page, so the
/// notification id is read leniently.
fn lenient_id<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum IdWire {
Number(i64),
Text(String),
}
match Option::<IdWire>::deserialize(deserializer)? {
None => Ok(None),
Some(IdWire::Number(n)) => Ok(Some(n)),
Some(IdWire::Text(text)) => text.trim().parse().map(Some).map_err(|_| {
serde::de::Error::custom(format!("notification id is not a number: {text}"))
}),
}
}
/// The notification a notifications row carries. GitHub's `reason` field
/// is the row's whole why; the subject's API URL yields the thread.
fn notification_event(row: &WireNotification) -> Result<Option<Notification>, ForgeError> {
@@ -520,9 +481,6 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(),
url: None,
timestamp: updated,
// `PUT /notifications/threads/{id}` is keyed on this same id:
// the notification, not the thread's number.
read_key: Some(id.to_string()),
raw: Value::Object(row.raw.clone()),
}))
}
@@ -688,16 +646,6 @@ impl Forge for GitHubForge {
Ok(())
}
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
let response = self
.get("/user")
.send()
.await
.map_err(ForgeError::network)?;
let user: WireUser = decode(response).await?;
Ok(user.login.filter(|login| !login.trim().is_empty()))
}
async fn snapshot(
&self,
repo: &RepoRef,
@@ -750,22 +698,6 @@ impl Forge for GitHubForge {
}
Ok(NotificationPage::finish(notifications, since))
}
async fn mark_read(&self, notification: &Notification) -> Result<(), ForgeError> {
let Some(read_key) = notification.read_key.as_deref() else {
// A row built without one is a shape break, not a forge
// outage: say so instead of silently re-reading it forever.
return Err(ForgeError::Parse(format!(
"notification {} carries no read key",
notification.id
)));
};
let path = format!("/notifications/threads/{read_key}");
let response = self.put(&path).send().await.map_err(ForgeError::network)?;
// 205 Reset Content: marked, nothing to decode.
ensure_success(response).await?;
Ok(())
}
}
#[cfg(test)]
@@ -928,63 +860,4 @@ mod tests {
assert_eq!(event.raw["node_id"], "MDU6SXNzdWUxMDA3");
assert!(event.raw.get("title").is_none());
}
fn notification(json: &str) -> WireNotification {
serde_json::from_str(json).expect("notification fixture parses")
}
// Captured from the live feed on 2026-11-21: `id` there is a string,
// and one such row used to fail the whole page's decode.
#[test]
fn a_notification_id_sent_as_a_string_decodes() {
let row = notification(
r#"{"id": "27210544329", "unread": true, "reason": "mention",
"updated_at": "2026-11-21T22:33:00Z", "last_read_at": null,
"subject": {"title": "Snap build failed for v2.5.1",
"url": "https://api.github.com/repos/acme/widgets/issues/10",
"latest_comment_url": "https://api.github.com/repos/acme/widgets/issues/comments/7070",
"type": "Issue"},
"repository": {"id": 1239653662, "full_name": "acme/widgets"},
"url": "https://api.github.com/notifications/threads/27210544329"}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 10);
assert_eq!(notification.repo, RepoRef::new("acme", "widgets"));
assert_eq!(notification.reason, NotificationReason::Mention);
assert!(!notification.is_pr);
assert_eq!(
notification.id,
"github:notification:27210544329@2026-11-21T22:33:00Z"
);
assert_eq!(notification.read_key.as_deref(), Some("27210544329"));
}
#[test]
fn a_notification_id_sent_as_a_number_still_decodes() {
let row = notification(
r#"{"id": 42188, "reason": "review_requested",
"updated_at": "2026-10-08T12:00:00Z",
"subject": {"title": "tidy the parser", "type": "PullRequest",
"url": "https://api.github.com/repos/acme/widgets/pulls/8"},
"repository": {"full_name": "acme/widgets"}}"#,
);
let notification = notification_event(&row)
.expect("maps")
.expect("carries a notification");
assert_eq!(notification.number, 8);
assert!(notification.is_pr);
assert_eq!(
notification.id,
"github:notification:42188@2026-10-08T12:00:00Z"
);
assert_eq!(notification.read_key.as_deref(), Some("42188"));
}
#[test]
fn a_notification_id_that_is_not_a_number_is_a_parse_error() {
let err = serde_json::from_str::<WireNotification>(r#"{"id": "not-a-number"}"#)
.expect_err("a junk id is loud, not silently dropped");
assert!(err.to_string().contains("not-a-number"), "got: {err}");
}
}
@@ -331,9 +331,6 @@ fn todo_notification(row: &WireTodo) -> Result<Option<Notification>, ForgeError>
title: target.title.clone(),
url: row.target_url.clone(),
timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()),
}))
}
@@ -526,18 +523,6 @@ impl Forge for GitLabForge {
Ok(())
}
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
// GitLab spells the login `username`, like every author object it
// sends.
let response = self
.get("/user")
.send()
.await
.map_err(ForgeError::network)?;
let user: WireAuthor = decode(response).await?;
Ok(user.username.filter(|login| !login.trim().is_empty()))
}
async fn snapshot(
&self,
repo: &RepoRef,
@@ -97,7 +97,6 @@ mod tests {
title: None,
url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
}
}
@@ -606,25 +606,6 @@ async fn poll_survives_a_comments_feed_with_blank_issue_urls() {
.collect();
assert_eq!(
summary,
vec![
(EventKind::Comment, 1, true),
(EventKind::Comment, 2, false)
]
);
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos".to_owned())
vec![(EventKind::Comment, 1, true), (EventKind::Comment, 2, false)]
);
}
@@ -2,8 +2,8 @@
//! wiremock server. Zero network.
use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, Notification, NotificationReason,
RepoRef, Timestamp,
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, NotificationReason, RepoRef,
Timestamp,
};
use serde_json::{Value, json};
use wiremock::matchers::{header, method, path, query_param};
@@ -532,102 +532,3 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses"))
);
}
/// A notification row, as the account's feed sends it.
fn notification_row(id: i64, reason: &str, number: u64) -> Value {
json!({
"id": id,
"unread": true,
"reason": reason,
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": format!("https://api.github.com/repos/acme/widgets/issues/{number}"),
"type": "Issue"
},
"repository": { "full_name": "acme/widgets" }
})
}
/// Deciding a row is not consuming it: the feed keeps returning anything
/// the account still has unread, so the read route is what ends the
/// repeat. It keys on the notification's own id, not the thread number —
/// the dedup id keeps that integer only as text.
#[tokio::test]
async fn marking_a_notification_read_puts_its_thread() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([notification_row(
42188,
"review_requested",
142
)])),
)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/notifications/threads/42188"))
.and(header("authorization", "Bearer tok"))
.respond_with(ResponseTemplate::new(205))
.mount(&server)
.await;
let forge = forge(&server);
let page = forge.notifications(None).await.expect("poll succeeds");
let notification = &page.notifications[0];
forge.mark_read(notification).await.expect("marks read");
let requests = server.received_requests().await.expect("recording is on");
let puts: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(puts.len(), 1, "one read call, on the row's id");
assert_eq!(puts[0].url.path(), "/notifications/threads/42188");
}
/// A row that reaches the caller with no read key is a shape break, not a
/// silent no-op: re-reading the same thread forever is the failure this
/// whole route exists to stop.
#[tokio::test]
async fn a_notification_without_a_read_key_fails_loudly() {
// Defaulted on deserialize, so this is also the row an inbox written
// before the field existed decodes to.
let notification: Notification = serde_json::from_value(json!({
"id": "github:notification:42188@2026-10-05T12:00:00Z",
"reason": "review_requested",
"repo": { "owner": "acme", "name": "widgets" },
"number": 142,
"is_pr": false,
"actor": null,
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-05T12:00:00Z",
"raw": {}
}))
.expect("a read-key-less row parses");
let err = GitHubForge::new("tok")
.mark_read(&notification)
.await
.expect_err("loud failure");
assert!(matches!(err, ForgeError::Parse(_)), "got: {err:?}");
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos-ai-bot" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos-ai-bot".to_owned())
);
}
@@ -572,20 +572,3 @@ async fn todos_poll_maps_actions_targets_and_projects() {
Some("https://gitlab.com/acme/widgets/-/merge_requests/12")
);
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody. GitLab spells the login
/// `username`.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v4/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "username": "kosmos" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos".to_owned())
);
}
-397
View File
@@ -1,397 +0,0 @@
# 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.
+22 -60
View File
@@ -60,12 +60,9 @@ Two consequences worth knowing before changing this code:
fire-and-forget (202); the reply streams back on
`GET /v1/sessions/{key}/events`. The transcript here is a mirror of
the stream, and the stream opens on the newest turn before the live
feed. That turn comes back whole even when it is longer than the
replay window, so a reload never lands mid-reply with the file the
turn handed over above the cut. A reload paints the latest
conversation at once instead of replaying a session that may have run
for weeks, and the turns above it come from
`GET /v1/sessions/{key}/history`, one whole turn per
feed — a reload paints the latest conversation at once instead of
replaying a session that may have run for weeks, and the turns above
it come from `GET /v1/sessions/{key}/history`, one whole turn per
page, as the reader scrolls up (or right away, while the transcript
is shorter than the screen). So the transcript survives the browser,
not just the claw.
@@ -93,21 +90,12 @@ Two consequences worth knowing before changing this code:
## What the transcript does with the stream
- **Replies, asks and files only.** The stream carries tool calls and
the model's thinking trace; this surface drops both and renders the
reply. A consent card and an attachment card still appear inline,
because the reader has to answer or open them. The mirror still
folds those other events; only the render ignores them.
- **Long pastes travel as chips.** A paste over three lines (the TUI's
`PASTE_INLINE_LINES`) never lands in the composer; it stages as a
droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
the plain draft — the claw composes the record (the payload in
place, the span note beside it) — so no mark ever crosses the wire.
The `user_message` echo names each chip as the byte span it stands
for (the session record's own shape, `paste::PasteSpan`), and the
transcript renders from that. Rows recorded before spans rode the
stream carry the legacy mark form in the text instead; the render
still scans for those, and an unpaired mark stays literal.
droppable chip (`▣1 42L`) and embeds into the sent text as
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s
`paste::embed` keeps — so the transcript renders each embed back as
a chip in place of the payload. An unpaired mark is literal text.
- **The agent can ask.** A `consent_request` event renders as an
inline card: kind `secret` gets a password input plus submit, kind
`phone` gets Approve/Deny, and both carry a deny link
@@ -115,16 +103,11 @@ Two consequences worth knowing before changing this code:
and again on the stream's `consent_resolved` echo; nothing persists
client-side, so a reload rebuilds the cards from the replay.
- **Attachments render inline.** An `attachment` event becomes a card
— media glyph, file name, B/KB/MB size, caption. The media kind comes
from the file extension, decided by the daemon when it stores the
file, so a `.png` renders and a `.patch` downloads without the client
guessing. Images fetch the bearer-guarded bytes
(`GET /v1/attachments/{id}`, blob → object URL, like the identity
images) and render capped at 240px; every card downloads on click,
images included. A card lives inside the turn that produced it, so
the scan that fetches image bytes walks finished turns and the live
one, not just the top-level rows. Object URLs cache per id, so a
replay never refetches.
— media glyph, file name, B/KB/MB size, caption. Images fetch the
bearer-guarded bytes (`GET /v1/attachments/{id}`, blob → object URL,
like the identity images) and render capped at 240px; code and file
cards download on click. Object URLs cache per id, so a replay never
refetches.
- **Your images ride along.** The composer's `+` — and an image on the
clipboard — stage as removable chips (`▣1 photo.png 1.2 MB`), the
claw's own budget enforced client-side (8 a message, 5 MiB decoded
@@ -136,21 +119,11 @@ Two consequences worth knowing before changing this code:
- **Sessions are created in place.** The sidebar's `+` form posts
`POST /v1/sessions` with a client-validated name
(`[A-Za-z0-9._-]{1,64}`), switches the chat to the new key, and
lets 400/409 land in the error banner. The interactive prefixes
(`interactive:`) list above the fold; *others* holds the whole rest
of the inventory — `task:`, `calendar:`, the phone's keys
(`phone:…`), the coding jobs' `job:<instance>#<id>` keys and forge
keys.
- **Every row opens, and some open read-only.** A resident key
(`interactive:`, `task:`, `phone:`, `calendar:`) has a live stream,
and the chat resets its mirror whenever that stream reopens. A key
outside them has none: its dispatch runs outside the hub. The panel
fetches `GET /v1/sessions/{key}/history` instead, which serves the
session the engine checkpointed, and shows the turns with a
`snapshot` status and the composer replaced by a line saying why.
The inventory's `revision` is that view's only reload signal: a poll
that sees it move fetches the newest page again, so an older page
the reader walked back to survives polling until a turn runs.
lets 400/409 land in the error banner. The inventory lists only the
resident prefixes (`interactive:`, `task:`, `calendar:`) — the ones the
message, event and history routes answer for. The phone's status keys
(`phone:…`), the coding jobs' `job:<instance>#<id>` keys and forge keys
stay out, and the full list stays on the wire.
- **Deleting a session is a decision, not a click.** The row's delete
button only names the key; the shell's dialog spells out that the
turn history goes with it, and `DELETE /v1/sessions/{key}` runs on
@@ -159,16 +132,6 @@ Two consequences worth knowing before changing this code:
error banner like every other refusal, and the chat moves to the
first remaining session, the stream's watcher following the key so
nothing keeps streaming a session that no longer exists.
- **Every row is controllable.** Beside the delete button, on hover:
`hold` posts `POST /v1/sessions/{key}/pause` and the row badges
`held` — queued work accumulates and nothing dispatches until `run`
posts the resume, both answered by the inventory's `paused` flag.
`stop` posts `POST /v1/sessions/{key}/abort`: a live turn is cut
(the stream closes on its `aborted` marker, in the warn tone, since
nothing failed), and an idle key's queued work is dropped instead —
the notice says which, from the answer's `cut`/`dropped`. A key with
neither running nor queued work has `stop` disabled rather than
sending a no-op.
## Layout
@@ -212,10 +175,10 @@ app/
raw HTML escaped, styles in main.css .md)
ClawBanner.vue the one error/notice banner surface
ChatPanel.vue transcript: sent lines (paste chips),
streamed turns as reply text plus
consent + attachment cards; the growing
composer; agent replies render through
AppMarkdown
streamed turns as bash shell lines and
glyph rows, consent + attachment
cards; the growing composer; agent
replies render through AppMarkdown
SessionsSidebar.vue conversable dispatch keys (phone status
keys hidden), interactive first; the
+ form creates a session
@@ -230,8 +193,7 @@ app/
composables/
useClaw.ts the typed API client + fetch-based SSE
useTranscript.ts folds TurnEvents into renderable turn
blocks; owns the paste span record (and
the legacy mark form old rows carry)
blocks; owns the paste-embed text form
server/
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
```
+36 -207
View File
@@ -17,12 +17,10 @@ import type {
NewAccount,
ProviderCredentials,
ProvidersState,
SandboxSelection,
SandboxState,
StreamStatus,
} from '~/composables/useClaw'
import { composeChips, useTranscript } from '~/composables/useTranscript'
import type { AttachmentCard, StagedImage } from '~/composables/useTranscript'
import { useTranscript } from '~/composables/useTranscript'
import type { StagedImage } from '~/composables/useTranscript'
const TOKEN_STORE_KEY = 'claw.token'
const ACTIVE_STORE_KEY = 'claw.activeKey'
@@ -60,13 +58,7 @@ const SETTINGS_SECTIONS: { label: string; entries: { id: string; label: string }
],
},
{ label: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] },
{
label: 'System',
entries: [
{ id: 'sandbox', label: 'Sandbox' },
{ id: 'about', label: 'About' },
],
},
{ label: 'System', entries: [{ id: 'about', label: 'About' }] },
]
function parseHash(): Route {
@@ -121,12 +113,9 @@ const {
// for weeks costs nothing up front and still reaches its first message.
const olderAvailable = ref(true)
// The cards this page already tried to fetch. Keyed by the card object
// rather than the attachment id: a page read, a mirror reset, or a live
// turn folding into a record builds new cards, and a new card deserves
// its fetch — the useClaw cache answers a repeat with the blob it
// already holds, so a retry costs no request.
let attemptedAttachments = new WeakSet<object>()
// Attachment ids this page already tried to fetch; a failed fetch is
// not retried until the stream resets and clears the set.
const attemptedAttachments = new Set<string>()
// Image cards need their bytes before they can render: fetched as the
// card appears, not on any timer. code/file fetch on download instead.
@@ -134,33 +123,28 @@ let attemptedAttachments = new WeakSet<object>()
// their attachment ids, never the bytes; locally sent rows hold their
// own object URLs.
//
// The cards sit at two depths. One handed over mid-turn lands in the
// open turn's entries and rides into the finished turn with it, so a
// scan of the top-level rows alone would never see it and the card
// would stay a name with no picture. Every path that can hold a card is
// walked here; the attempt set makes a repeated pass free.
function requestAttachmentImages(): void {
const fetchAttachment = (attachment: AttachmentCard) => {
const { id, media, url } = attachment
if (media !== 'image' || url !== null || attemptedAttachments.has(attachment)) return
attemptedAttachments.add(attachment)
// The watch is deep (rows mutate in place as their bytes land), and it
// fires on every streamed delta, so the scan covers only the items the
// last pass did not see — the transcript only ever appends.
let scannedItems = 0
watch(
transcriptItems,
(items) => {
for (const item of items.slice(scannedItems)) {
if (item.kind === 'attachment') {
const { id, media, url } = item.attachment
if (media !== 'image' || url !== null || attemptedAttachments.has(id)) continue
attemptedAttachments.add(id)
claw
.attachmentUrl(id)
.then((fetched) => transcript.setAttachmentUrl(id, fetched))
.catch((err) => noteApiError(err))
}
for (const item of transcriptItems.value) {
if (item.kind === 'attachment') {
fetchAttachment(item.attachment)
} else if (item.kind === 'turn') {
for (const entry of item.turn.entries) {
if (entry.kind === 'attachment') fetchAttachment(entry.attachment)
}
} else if (item.kind === 'sent') {
for (const image of item.images) {
const { id, url } = image
if (id === null || url !== null || attemptedAttachments.has(image)) continue
attemptedAttachments.add(image)
if (id === null || url !== null || attemptedAttachments.has(id)) continue
attemptedAttachments.add(id)
claw
.attachmentUrl(id)
.then((fetched) => transcript.setSentImageUrl(id, fetched))
@@ -168,15 +152,10 @@ function requestAttachmentImages(): void {
}
}
}
for (const entry of transcript.live.value?.entries ?? []) {
if (entry.kind === 'attachment') fetchAttachment(entry.attachment)
}
}
watch([transcriptItems, transcript.live], requestAttachmentImages, {
deep: true,
immediate: true,
})
scannedItems = items.length
},
{ deep: true },
)
// --- the agent's identity --------------------------------------------
const identity = ref<AgentIdentity | null>(null)
@@ -286,8 +265,6 @@ const mutatingIdentity = ref(false)
const accounts = ref<ClawAccount[] | null>(null)
const accountsLoading = ref(false)
const mutatingAccounts = ref(false)
const sandboxState = ref<SandboxState | null>(null)
const savingSandbox = ref(false)
const streamStatus = ref<StreamStatus>('connecting')
const busy = ref(false)
const authRequired = ref(false)
@@ -323,13 +300,6 @@ async function refreshSessions(): Promise<void> {
try {
sessions.value = await claw.sessions()
apiError.value = null
// A read-only thread has no stream to tell it a dispatch ran; the
// inventory's revision does. Reload the snapshot when it moved, and
// only then — a reload drops the pages the reader walked back to.
if (activeKey.value !== '' && !isResidentKey(activeKey.value) && !threadLoading) {
const revision = sessions.value.find((s) => s.key === activeKey.value)?.revision ?? null
if (revision !== threadRevision) void loadThread()
}
} catch (err) {
noteApiError(err)
} finally {
@@ -397,49 +367,6 @@ async function confirmDeleteSession(): Promise<void> {
}
}
/** The pause gate: hold a key's dispatch, lift the hold. The inventory
* refresh carries the `paused` flag back to the sidebar. */
async function pauseSession(key: string): Promise<void> {
try {
await claw.pauseSession(key)
pushNotice(`${key} held`)
apiError.value = null
} catch (err) {
noteApiError(err)
}
void refreshSessions()
}
async function resumeSession(key: string): Promise<void> {
try {
await claw.resumeSession(key)
pushNotice(`${key} resumed`)
apiError.value = null
} catch (err) {
noteApiError(err)
}
void refreshSessions()
}
/** Abort: cut a live turn, or drop the key's queued work. The answer
* says which happened; the inventory refresh settles the row. */
async function abortSession(key: string): Promise<void> {
try {
const result = await claw.abortSession(key)
pushNotice(
result.cut
? `turn on ${key} stopped`
: result.dropped > 0
? `${result.dropped} queued item(s) dropped on ${key}`
: `nothing running on ${key}`,
)
apiError.value = null
} catch (err) {
noteApiError(err)
}
void refreshSessions()
}
async function refreshProviders(): Promise<void> {
try {
providersState.value = await claw.providers()
@@ -572,54 +499,21 @@ async function removeProvider(id: string): Promise<void> {
}
}
async function refreshSandbox(): Promise<void> {
try {
sandboxState.value = await claw.sandbox()
apiError.value = null
} catch (err) {
noteApiError(err)
}
}
async function saveSandbox(choice: SandboxSelection): Promise<void> {
savingSandbox.value = true
try {
sandboxState.value = await claw.setSandbox(choice)
pushNotice(
choice.kind === 'http'
? 'sandbox: remote host'
: choice.kind === 'ssh'
? 'sandbox: ssh host'
: 'sandbox: this machine',
)
apiError.value = null
} catch (err) {
noteApiError(err)
} finally {
savingSandbox.value = false
}
}
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews and the composed
// chip record — the same plain text and spans the fold records on
// the other side — so the stream's user_message echo, which
// carries the stored ids beside that record, dedupes against it.
const composed = composeChips(message.text, message.pastes)
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
// The optimistic row renders the staged previews; the stream's
// user_message echo carries the stored ids and dedupes against it.
const rowId = transcript.addSent(
composed.text,
message.text,
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
composed.pastes,
)
busy.value = true
try {
// Fire-and-forget by design: the claw answers 202 and the reply
// arrives on the event stream. The chips and the images ride the
// body only when there are some.
// arrives on the event stream. The body carries the images only
// when there are some.
await claw.sendMessage(
activeKey.value,
message.text,
message.pastes,
message.images.map(({ media_type, data }) => ({ media_type, data })),
)
apiError.value = null
@@ -665,11 +559,7 @@ async function downloadAttachment(id: string, name: string): Promise<void> {
const anchor = document.createElement('a')
anchor.href = url
anchor.download = name
// A click on a detached anchor is a no-op in some browsers; the
// element joins the document for the length of the click.
document.body.append(anchor)
anchor.click()
anchor.remove()
} catch (err) {
noteApiError(err)
}
@@ -691,43 +581,22 @@ function saveToken(): void {
void refreshSessions()
void refreshIdentity()
void refreshAccounts()
void refreshSandbox()
}
// --- the one live subscription ---------------------------------------
let stream: { close: () => void } | null = null
/** The revision the read-only thread on screen was loaded at; a poll
* that sees a newer one reloads it, since no stream will. */
let threadRevision: number | null = null
/** A load is in flight: a poll landing mid-load must not start a second
* one and append the same page twice. */
let threadLoading = false
/** Whether the key on screen answers a snapshot. The key's prefix says
* so before the fetch lands; the page's own `read_only` has the last
* word. */
const threadReadOnly = ref(false)
function resubscribe(): void {
stream?.close()
stream = null
transcript.reset()
olderAvailable.value = true
attemptedAttachments = new WeakSet<object>()
attemptedAttachments.clear()
notices.value = []
streamStatus.value = 'connecting'
threadRevision = null
threadReadOnly.value = activeKey.value !== '' && !isResidentKey(activeKey.value)
// Deleting the last session clears the key, and an empty key is not a
// stream: subscribing to one would retry a 404 forever.
if (activeKey.value === '') return
// A key outside the resident context has no turn record: its handler
// never streams, and the events route answers 400. What the daemon
// does hold is the session stash, which the history route serves as a
// read-only snapshot. The panel shows it with the composer closed.
if (!isResidentKey(activeKey.value)) {
void loadThread()
return
}
stream = claw.subscribeEvents(activeKey.value, {
onEvent: (event, seq) => transcript.applyEvent(event, seq),
// The record lost what this mirror holds (a wiped or reset
@@ -735,8 +604,8 @@ function resubscribe(): void {
onReset: () => {
transcript.reset()
olderAvailable.value = true
attemptedAttachments = new WeakSet<object>()
requestAttachmentImages()
attemptedAttachments.clear()
scannedItems = 0
},
onStatus: (status) => {
streamStatus.value = status
@@ -745,8 +614,8 @@ function resubscribe(): void {
// is. Only the attachment set is cleared — a fetch that failed
// during the outage should retry against the recovered stream.
if (status === 'reconnecting') {
attemptedAttachments = new WeakSet<object>()
requestAttachmentImages()
attemptedAttachments.clear()
scannedItems = 0
}
if (status === 'open') void refreshSessions()
},
@@ -754,35 +623,6 @@ function resubscribe(): void {
})
}
/** Loads the newest page of a read-only thread: a snapshot of the
* engine's own history, rendered by the same mirror the stream feeds.
* Pagination is the walk back, unchanged — a page lands, the scroller
* asks for the next one. */
async function loadThread(): Promise<void> {
const key = activeKey.value
threadLoading = true
streamStatus.value = 'open'
// A reload (a finished dispatch moved the revision) rebuilds from the
// newest page: the mirror holds the previous snapshot, and stacking
// the new one under it would duplicate every turn.
transcript.reset()
olderAvailable.value = true
attemptedAttachments = new WeakSet<object>()
try {
const page = await claw.history(key)
if (key !== activeKey.value) return
for (const { seq, event } of page.events) transcript.applyEvent(event, seq)
olderAvailable.value = page.more
threadReadOnly.value = page.readOnly
threadRevision = sessions.value.find((session) => session.key === key)?.revision ?? null
apiError.value = null
} catch (err) {
noteApiError(err)
} finally {
threadLoading = false
}
}
/** Fetches one page of turns older than the mirror's first and stacks
* it above. Whole turns only, so the page never duplicates or skips:
* the daemon ends it exactly where the mirror begins. */
@@ -817,7 +657,6 @@ onMounted(() => {
void refreshIdentity()
void refreshProviders()
void refreshAccounts()
void refreshSandbox()
void refreshSessions()
healthTimer = setInterval(checkHealth, 30000)
sessionsTimer = setInterval(() => void refreshSessions(), 20000)
@@ -886,16 +725,12 @@ onUnmounted(() => {
@refresh="refreshSessions"
@create="createSession"
@delete="askDeleteSession"
@pause="pauseSession"
@resume="resumeSession"
@abort="abortSession"
/>
<ChatPanel
:items="transcriptItems"
:live="liveTurn"
:active-key="activeKey"
:can-send="isInteractive(activeKey)"
:read-only="threadReadOnly"
:busy="busy"
:session="activeSession"
:active-backend="providersState?.active ?? null"
@@ -954,12 +789,6 @@ onUnmounted(() => {
@add="addProvider"
@remove="removeProvider"
/>
<SettingsSandboxPage
v-show="route.section === 'sandbox'"
:state="sandboxState"
:saving="savingSandbox"
@save="saveSandbox"
/>
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
</template>
</main>
+32 -129
View File
@@ -10,14 +10,12 @@
import {
PASTE_INLINE_LINES,
chipLabel,
byteToIndex,
chipLinesLabel,
embedPastes,
lineCount,
normalizePaste,
pasteParts,
} from '~/composables/useTranscript'
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
import type { PasteSpan } from '~/composables/useClaw'
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
const props = defineProps<{
@@ -26,8 +24,6 @@ const props = defineProps<{
activeKey: string
/** Only `interactive:*` keys accept messages (the claw 400s the rest). */
canSend: boolean
/** The daemon answers this key with a snapshot, not a stream. */
readOnly: boolean
busy: boolean
session: ClawSession | null
activeBackend: { provider: string; model: string } | null
@@ -45,34 +41,10 @@ const props = defineProps<{
const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
/** Why the composer is closed. A resident key that is not `interactive:`
* runs on its own trigger; anything else is a snapshot of a stash the
* engine checkpointed, whose answer went out through its dispatch. */
const readOnlyNote = computed(() =>
!props.readOnly
? 'Only interactive: keys take messages. This key runs on its own trigger and the transcript is read-only.'
: 'Read-only snapshot of the turns this key ran. The dispatch takes its input and posts its answer outside the chat.',
)
/** Whose words a user row holds. A chat key's are the human's, on the
* web surface or on the phone; every other key's are the prompt its
* dispatch was started with. */
const userLabel = computed(() =>
/^(interactive|phone):/.test(props.activeKey) ? 'you' : 'dispatch',
)
/** Whether the key has a stream at all. A snapshot answers a page once
* and follows nothing, so the header says so instead of claiming to be
* live. */
const streaming = computed(() => !props.readOnly)
/** One send as the panel hands it up: the text (pastes embedded) and
* the staged images, previews included for the optimistic row. */
interface SendPayload {
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[]
}
@@ -164,12 +136,20 @@ watch(
},
)
// A consent or attachment card opening inside the trailing turn
// changes the rendered height, so the reply length and the entries
// length both join the watch that keeps the stream pinned at the
// bottom.
// Thinking grows inside the trailing entry without changing the
// entries length, so its total length joins the watch to keep the
// stream pinned at the bottom.
function liveThinkingLength(): number {
return (
props.live?.entries.reduce(
(count, entry) => (entry.kind === 'thinking' ? count + entry.text.length : count),
0,
) ?? 0
)
}
watch(
() => [props.items.length, props.live?.reply.length, props.live?.entries.length],
() => [props.items.length, props.live?.reply.length, liveThinkingLength(), props.live?.entries.length],
async () => {
if (!pinned.value) return
await nextTick()
@@ -185,7 +165,7 @@ function submit(): void {
// answers 202 at once) — a running turn never blocks the composer,
// because a send into one steers it.
if (!text || !props.canSend || props.busy) return
emit('send', { text, pastes: pastes.value, images: stagedImages.value })
emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value })
stageGeneration++
draft.value = ''
pastes.value = []
@@ -387,12 +367,8 @@ function storedImageName(image: SentImage): string {
type MessageSegment = PastePart | { kind: 'chip'; label: string }
/** The message's render pieces: literal text and resolved chips, the
* chips' one-based ids counted across the message. The chips come
* from the row's span record — the plain text sliced at the spans'
* byte boundaries — and a row from before spans rode the wire
* carries none; that one still scans the mark form in its text. */
function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] {
if (pastes.length === 0) {
* chips' one-based ids counted across the message. */
function messageSegments(text: string): MessageSegment[] {
const segments: MessageSegment[] = []
let chip = 0
for (const part of pasteParts(text)) {
@@ -404,21 +380,6 @@ function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment
}
return segments
}
const indexOf = byteToIndex(text)
const segments: MessageSegment[] = []
let chip = 0
let cut = 0
for (const span of [...pastes].sort((a, b) => a.start - b.start)) {
const start = indexOf(span.start)
const end = indexOf(span.end)
if (start === -1 || end === -1 || start < cut || end < start) continue
if (start > cut) segments.push({ kind: 'text', text: text.slice(cut, start) })
segments.push({ kind: 'chip', label: chipLinesLabel(span.lines, chip++) })
cut = end
}
if (cut < text.length) segments.push({ kind: 'text', text: text.slice(cut) })
return segments
}
const displayName = computed(() => props.activeKey.replace(/^interactive:/, ''))
@@ -451,13 +412,10 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="text">
<h2>{{ displayName }}</h2>
</div>
<span v-if="streaming" class="stream-status" :title="`event stream: ${streamStatus}`">
<span class="stream-status" :title="`event stream: ${streamStatus}`">
<StatusDot :tone="streamTone(streamStatus)" />
{{ streamLabel }}
</span>
<span v-else class="stream-status" title="a snapshot of the stored session; no stream follows this key">
snapshot
</span>
<button class="ghost info" title="session info" @click="infoOpen = true">ⓘ</button>
</header>
@@ -472,9 +430,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div ref="scroller" class="stream-area" @scroll.passive="onScroll">
<p v-if="items.length === 0 && !live" class="empty">
{{ streaming
? 'nothing streamed yet; messages post to the claw and replies arrive here live'
: 'nothing recorded for this key yet' }}
nothing streamed yet; messages post to the claw and replies arrive here live
</p>
<p v-if="loadingOlder" class="older-hint">loading earlier turns</p>
@@ -483,7 +439,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div v-if="item.kind === 'sent'" class="msg">
<div class="avatar user" aria-hidden="true">·</div>
<div class="msg-body">
<div class="who">{{ userLabel }}</div>
<div class="who">you</div>
<div v-if="item.images.length > 0" class="sent-images">
<button
v-for="(image, index) in item.images"
@@ -497,7 +453,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
</button>
</div>
<div class="reply plain">
<template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
<template v-for="(segment, index) in messageSegments(item.text)" :key="index">
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
<template v-else>{{ segment.text }}</template>
</template>
@@ -518,11 +474,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div
v-if="item.turn.outcome"
class="outcome mono"
:class="{
failed: item.turn.outcome === 'failed',
steered: item.turn.outcome === 'steered',
aborted: item.turn.outcome === 'aborted',
}"
:class="{ failed: item.turn.outcome === 'failed', steered: item.turn.outcome === 'steered' }"
>
{{ item.turn.outcome }}
</div>
@@ -546,15 +498,12 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
<div class="who">{{ agentName }}</div>
<TurnEntries
:entries="live.entries"
:open-thinking="true"
@consent-answer="(id, answer) => emit('consentAnswer', id, answer)"
@consent-deny="(id) => emit('consentDeny', id)"
@download-attachment="(id, name) => emit('downloadAttachment', id, name)"
/>
<AppMarkdown v-if="live.reply" :text="live.reply" streaming class="reply" />
<p v-if="!live.reply" class="working" role="status">
<span class="spinner" aria-hidden="true" />
{{ agentName }} is working…
</p>
</div>
</div>
</div>
@@ -591,9 +540,8 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
{{ imageError }}
<button class="chip-x" title="dismiss" @click="imageError = null">×</button>
</p>
<p v-if="!canSend" class="read-only">{{ readOnlyNote }}</p>
<div v-else class="input-row">
<button class="ghost attach" title="attach images" @click="pickImages">
<div class="input-row">
<button class="ghost attach" title="attach images" :disabled="!canSend" @click="pickImages">
+
</button>
<textarea
@@ -601,15 +549,20 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
v-model="draft"
rows="1"
:placeholder="
live ? `Message ${agentName}… sending steers the running turn` : `Message ${agentName}…`
canSend
? live
? `Message ${agentName}… sending steers the running turn`
: `Message ${agentName}…`
: 'only interactive:* sessions accept messages'
"
:disabled="!canSend"
@keydown="onPromptKeydown"
@paste="onPaste"
@input="resizePrompt"
/>
<button
class="primary send"
:disabled="busy || draft.trim() === ''"
:disabled="!canSend || busy || draft.trim() === ''"
:title="live ? 'send — interrupts the running turn' : 'send'"
@click="submit"
>
@@ -787,49 +740,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
color: var(--accent-text);
}
/* An aborted turn: stopped from the controls, and nothing replaced
it. Not a failure either — the same warn tone the held badge
carries, which is what an operator's stop is. */
.outcome.aborted {
color: var(--warn);
}
/* While the turn runs but no reply text has landed yet. Tool rows and
the thinking trace never render on this surface, so this line is the
turn's only pulse between its first event and its first delta — the
streaming cursor takes over once text arrives, and the line goes.
Reduced motion gets the static ring. */
.working {
display: flex;
align-items: center;
gap: 8px;
margin: 4px 0 0;
color: var(--text3);
font-size: 12.5px;
}
.spinner {
flex: none;
width: 12px;
height: 12px;
border: 2px solid var(--border-strong);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
/* A consent card: the agent asking its human something — distinct
from a tool row, toned by its resolution. */
.consent-card {
@@ -1012,13 +922,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
gap: 8px;
}
.read-only {
margin: 0;
padding: 2px 0;
color: var(--text3);
font-size: 12.5px;
}
.attach {
width: 38px;
padding: 0;
+15 -168
View File
@@ -7,19 +7,6 @@
// new key lands in the inventory. The delete button asks nothing itself
// — the confirmation, which names the transcript that goes with the
// session, is the shell's.
//
// The non-interactive keys fold under *others*: folded (the default),
// the group shows only how many of them hold a lease, plus the
// more/less toggle; unfolded it lists every row, the whole inventory.
// Every row opens: a resident key streams, and any other key (a forge
// thread, a coding job, a phone topic) opens the read-only snapshot its
// history route serves. The controls beside it act on its dispatch from
// either view.
//
// The controls sit beside the delete button, on hover, one word each:
// hold/run pauses and resumes the key's dispatch, stop aborts — cuts a
// live turn, or drops the key's queued work when none runs. Nothing
// here is destructive beyond the delete, which keeps its own dialog.
import { SESSION_NAME_PATTERN, isResidentKey } from '~/composables/useClaw'
import type { ClawSession } from '~/composables/useClaw'
@@ -36,80 +23,42 @@ const emit = defineEmits<{
refresh: []
create: [name: string]
delete: [key: string]
pause: [key: string]
resume: [key: string]
abort: [key: string]
}>()
interface Group {
label: string
rows: {
key: string
name: string
session: ClawSession
/** Whether abort has anything to act on: a live turn, or queued
* work to drop. */
abortable: boolean
}[]
/** How many rows hold a lease; the others' header shows the count. */
working: number
/** Whether the rows fold away until the toggle says otherwise. */
collapsible: boolean
rows: { key: string; name: string; session: ClawSession }[]
}
const groups = computed<Group[]>(() => {
const byKey = (a: ClawSession, b: ClawSession) => a.key.localeCompare(b.key)
// The resident prefixes are the chat sessions: `interactive:` is the
// live chat surface, `task:` a scheduled task's own turn, `phone:` the
// phone client's, `calendar:` a reminder's. The rest of the inventory —
// `job:<instance>#<id>`, a forge thread — holds no turn record: its
// handler never streams. Its history route serves the session stash
// instead, so the row still opens, read-only.
const interactive = props.sessions
// Only the resident prefixes are chat sessions: `interactive:` is the
// live chat surface, `task:` a scheduled task's own turn, `calendar:` a
// reminder's. The rest of the inventory has no transcript to open —
// `phone:<device>:<topic>` is status reporting, `job:<instance>#<id>`
// is the coding jobs' bookkeeping, a forge key is a thread the handler
// reports on — and the daemon's message, event and history routes
// refuse those prefixes, so a row for one is a dead end. The inventory
// hides them rather than the API narrowing.
const conversable = props.sessions.filter((session) => isResidentKey(session.key))
const interactive = conversable
.filter((session) => session.key.startsWith('interactive:'))
.sort(byKey)
const others = props.sessions
const others = conversable
.filter((session) => !session.key.startsWith('interactive:'))
.sort(byKey)
const row = (session: ClawSession) => ({
key: session.key,
name: session.key.replace(/^interactive:/, ''),
session,
abortable: session.state === 'leased' || session.inbox_depth > 0,
})
const working = (sessions: ClawSession[]) =>
sessions.filter((session) => session.state === 'leased').length
const groups: Group[] = []
if (interactive.length > 0)
groups.push({
label: 'interactive',
rows: interactive.map(row),
working: working(interactive),
collapsible: false,
})
if (others.length > 0)
groups.push({
label: 'others',
rows: others.map(row),
working: working(others),
collapsible: true,
})
groups.push({ label: 'interactive', rows: interactive.map(row) })
if (others.length > 0) groups.push({ label: 'other keys', rows: others.map(row) })
return groups
})
/** Whether the others group is folded out; it starts folded, and opens
* when the chat opens a row that lives in it — otherwise the selection
* would be invisible. */
const othersOpen = ref(false)
watch(
() => props.activeKey,
(key) => {
if (key !== '' && !isResidentKey(key)) othersOpen.value = true
},
{ immediate: true },
)
const shownCount = computed(() =>
groups.value.reduce((total, group) => total + group.rows.length, 0),
)
@@ -210,21 +159,7 @@ watch(
</p>
<div v-for="group in groups" :key="group.label" class="group">
<div class="group-head">
<span class="label">{{ group.label }}</span>
<span v-if="group.collapsible" class="working" :class="{ live: group.working > 0 }">
{{ group.working }} working
</span>
<button
v-if="group.collapsible"
class="ghost toggle"
:title="othersOpen ? 'fold the other keys away' : 'show every other key'"
@click="othersOpen = !othersOpen"
>
{{ othersOpen ? 'less' : 'more' }}
</button>
</div>
<template v-if="!group.collapsible || othersOpen">
<div
v-for="row in group.rows"
:key="row.key"
@@ -235,41 +170,10 @@ watch(
<button class="entry" @click="$emit('select', row.key)">
<StatusDot :tone="stateTone(row.session.state)" />
<span class="name">{{ row.name }}</span>
<span
v-if="row.session.paused"
class="held"
title="dispatch held: nothing runs until resume"
>
held
</span>
<span v-if="row.session.inbox_depth > 0" class="depth" title="inbox depth">
{{ row.session.inbox_depth }}
</span>
</button>
<button
v-if="row.session.paused"
class="ghost act"
:title="`resume ${row.key}`"
@click.stop="$emit('resume', row.key)"
>
run
</button>
<button
v-else
class="ghost act"
:title="`pause ${row.key}`"
@click.stop="$emit('pause', row.key)"
>
hold
</button>
<button
class="ghost act stop"
:disabled="!row.abortable"
:title="`abort ${row.key}`"
@click.stop="$emit('abort', row.key)"
>
stop
</button>
<button
class="ghost remove"
aria-label="delete session"
@@ -279,7 +183,6 @@ watch(
×
</button>
</div>
</template>
</div>
</aside>
</template>
@@ -384,32 +287,10 @@ watch(
margin-bottom: 14px;
}
.group-head {
display: flex;
align-items: center;
gap: 8px;
.group .label {
padding: 0 8px 4px;
}
.group-head .working {
flex: 1;
min-width: 0;
text-align: right;
font-family: var(--mono);
font-size: 11px;
color: var(--text3);
}
.group-head .working.live {
color: var(--ok);
}
.group-head .toggle {
flex: none;
padding: 0 6px;
font-size: 11px;
}
/* The row owns the hover and active surface: the select button fills it
and the delete button sits beside it, so neither has to nest in the
other. */
@@ -448,27 +329,6 @@ watch(
font-weight: inherit;
}
.row .act {
flex: none;
padding: 0 4px;
font-size: 11px;
font-family: var(--mono);
opacity: 0;
}
.row .act.stop {
color: var(--error);
}
.row .act:disabled {
color: var(--text3);
cursor: default;
}
.entry:disabled {
cursor: default;
}
.row .remove {
flex: none;
padding: 0 5px;
@@ -476,25 +336,12 @@ watch(
opacity: 0;
}
.row:hover .act,
.row:hover .remove,
.row:focus-within .act,
.row:focus-within .remove,
.row.active .act,
.row.active .remove {
opacity: 1;
}
.held {
flex: none;
font-size: 10px;
font-family: var(--mono);
color: var(--warn);
border: 1px solid var(--border-strong);
border-radius: 999px;
padding: 0 5px;
}
.name {
flex: 1;
min-width: 0;
@@ -1,9 +1,7 @@
<script setup lang="ts">
// The agent handing a file over: a head row naming it, the image (when
// there is one) under it, capped so a screenshot cannot take the
// stream. Every card downloads, images included: a picture the browser
// cannot paint, an SVG, or bytes that failed to fetch must still come
// out of the store.
// stream; code and file download on click.
import type { AttachmentCard } from '~/composables/useTranscript'
defineProps<{ attachment: AttachmentCard }>()
@@ -37,6 +35,7 @@ function formatBytes(size: number): string {
<span class="attachment-name mono">{{ attachment.name }}</span>
<span class="attachment-size mono">{{ formatBytes(attachment.size) }}</span>
<button
v-if="attachment.media !== 'image'"
class="ghost"
:title="`download ${attachment.name}`"
@click="emit('download', attachment.id, attachment.name)"
+39 -16
View File
@@ -1,22 +1,17 @@
<script setup lang="ts">
// The turn's middle, as the web surface shows it: the agent's asks
// (consent cards) and its handovers (attachment cards), each at the
// position the stream delivered it. Tool calls and the thinking trace
// stay off this surface; the reply is what it shows, and these two
// cards are the only things the reader must act on or can open.
import { computed } from 'vue'
// A turn's stream-ordered middle: tool rows, pieces of the thinking
// trace, the agent's asks, its handovers — each at the position the
// stream delivered it, so an ask sits at the tool call that raised it
// and thinking sits between the calls it precedes.
import type { TurnEntry } from '~/composables/useTranscript'
import type { ConsentAnswer } from '~/composables/useClaw'
const props = defineProps<{
defineProps<{
entries: TurnEntry[]
/** A live turn's thinking blocks start expanded; finished ones collapse. */
openThinking?: boolean
}>()
/** Cards only: a turn's tool rows and thinking blocks never render. */
const cards = computed(() =>
props.entries.filter((entry) => entry.kind === 'consent' || entry.kind === 'attachment'),
)
const emit = defineEmits<{
consentAnswer: [id: string, answer: ConsentAnswer]
consentDeny: [id: string]
@@ -25,16 +20,21 @@ const emit = defineEmits<{
</script>
<template>
<div v-if="cards.length > 0" class="entries">
<template v-for="(entry, index) in cards" :key="index">
<div v-if="entries.length > 0" class="entries">
<template v-for="(entry, index) in entries" :key="index">
<TurnToolRow v-if="entry.kind === 'tool'" :row="entry.row" />
<details v-else-if="entry.kind === 'thinking'" class="thinking" :open="openThinking">
<summary>thinking</summary>
<pre>{{ entry.text }}</pre>
</details>
<TurnConsentCard
v-if="entry.kind === 'consent'"
v-else-if="entry.kind === 'consent'"
:consent="entry.consent"
@answer="(id, answer) => emit('consentAnswer', id, answer)"
@deny="(id) => emit('consentDeny', id)"
/>
<TurnAttachmentCard
v-else-if="entry.kind === 'attachment'"
v-else
:attachment="entry.attachment"
@download="(id, name) => emit('downloadAttachment', id, name)"
/>
@@ -49,4 +49,27 @@ const emit = defineEmits<{
gap: 4px;
margin-bottom: 10px;
}
.thinking {
color: var(--text3);
}
.thinking summary {
cursor: pointer;
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.thinking pre {
margin: 6px 0 0;
padding: 8px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text3);
font-style: italic;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
+102
View File
@@ -0,0 +1,102 @@
<script setup lang="ts">
// One tool call in a turn: running, completed, or failed — shell lines
// for bash (the TUI's tool_row), glyph rows for everything else.
import type { ToolRow } from '~/composables/useTranscript'
defineProps<{ row: ToolRow }>()
/** Command rows render as shell lines, not glyph rows; run_command is
* the bash tool's other name. */
function isShellTool(name: string): boolean {
return name === 'bash' || name === 'run_command'
}
</script>
<template>
<div class="tool-row" :class="{ error: row.isError === true }">
<template v-if="isShellTool(row.name)">
<span class="shell-mark" aria-hidden="true">$ </span>
<span class="shell-command mono">{{ row.command ?? '…' }}</span>
<span
v-if="typeof row.code === 'number'"
class="shell-code mono"
:class="row.code === 0 ? 'ok' : 'failed'"
>[{{ row.code }}]</span>
<span v-else-if="row.isError === true" class="shell-code failed">✗</span>
</template>
<template v-else>
<span class="glyph" aria-hidden="true">{{
row.isError === null ? '…' : row.isError ? '✗' : '✓'
}}</span>
<span class="name mono">{{ row.name }}</span>
<span v-if="row.summary" class="summary mono">{{ row.summary }}</span>
</template>
</div>
</template>
<style scoped>
.tool-row {
display: flex;
gap: 8px;
align-items: baseline;
padding: 5px 10px;
background: var(--surface);
border: 1px solid var(--border);
border-left: 3px solid var(--ok);
border-radius: 6px;
}
.tool-row.error {
border-left-color: var(--error);
}
.glyph {
flex: none;
color: var(--ok);
}
.tool-row.error .glyph {
color: var(--error);
}
.name {
color: var(--text);
}
.summary {
color: var(--text3);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A bash row reads as the shell line it ran: dim $ prefix, the
command, and the exit code pushed to the row's right end. */
.shell-mark {
flex: none;
color: var(--text3);
white-space: pre;
}
.shell-command {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text);
}
.shell-code {
flex: none;
font-size: 11px;
}
.shell-code.ok {
color: var(--ok);
}
.shell-code.failed {
color: var(--error);
}
</style>
@@ -14,9 +14,6 @@ const routes = [
{ method: 'GET', path: '/v1/sessions', note: 'the dispatch-key inventory' },
{ method: 'POST', path: '/v1/sessions', note: 'create an interactive session from a name' },
{ method: 'DELETE', path: '/v1/sessions/{key}', note: 'delete a session and its turn history' },
{ method: 'POST', path: '/v1/sessions/{key}/pause', note: "hold a key's dispatch" },
{ method: 'POST', path: '/v1/sessions/{key}/resume', note: 'lift the hold' },
{ method: 'POST', path: '/v1/sessions/{key}/abort', note: 'cut the live turn, or drop the queue' },
{ method: 'POST', path: '/v1/sessions/{key}/messages', note: 'message ingest, 202 + stream' },
{ method: 'GET', path: '/v1/sessions/{key}/events', note: 'the turn-event stream (SSE)' },
{ method: 'POST', path: '/v1/consents/{id}', note: 'answer a consent (a secret or a grant)' },
@@ -24,7 +24,6 @@ const emit = defineEmits<{
// The draft: '' means "clear this field", matching the wire.
const draft = ref<IdentityTexts>({
name: '',
email: '',
mark: '',
initials: '',
tagline: '',
@@ -36,7 +35,6 @@ const dirty = computed(() => {
if (!identity) return false
return (
draft.value.name !== (identity.name ?? '') ||
draft.value.email !== (identity.email ?? '') ||
draft.value.mark !== (identity.mark ?? '') ||
draft.value.initials !== (identity.initials ?? '') ||
draft.value.tagline !== (identity.tagline ?? '') ||
@@ -49,7 +47,6 @@ function discard(): void {
if (!identity) return
draft.value = {
name: identity.name ?? '',
email: identity.email ?? '',
mark: identity.mark ?? '',
initials: identity.initials ?? '',
tagline: identity.tagline ?? '',
@@ -69,7 +66,6 @@ watch(
initialized.value = true
draft.value = {
name: identity.name ?? '',
email: identity.email ?? '',
mark: identity.mark ?? '',
initials: identity.initials ?? '',
tagline: identity.tagline ?? '',
@@ -101,7 +97,6 @@ function onImageChosen(kind: AgentImageKind, event: Event): void {
const CAPS: Record<keyof IdentityTexts, number> = {
name: 64,
email: 120,
mark: 8,
initials: 4,
tagline: 120,
@@ -147,7 +142,7 @@ const CAPS: Record<keyof IdentityTexts, number> = {
<SettingCard v-if="identity" title="Agent identity">
<SettingRow
title="Display name"
description="Shown as the author of messages, in the window title, in notifications, and as the author name on commits in workspaces."
description="Shown as the author of messages, in the window title, and in notifications."
>
<input
v-model="draft.name"
@@ -158,19 +153,6 @@ const CAPS: Record<keyof IdentityTexts, number> = {
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Email"
description="The author address on commits the agent makes in its workspaces."
>
<input
v-model="draft.email"
type="email"
:maxlength="CAPS.email"
placeholder="claw@example.net"
autocomplete="off"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Mark"
description="The glyph or emoji in the rail and the empty states. Defaults to ῥ."
@@ -1,375 +0,0 @@
<script setup lang="ts">
// The Sandbox page: where the agent's `bash` runs. The choice saves as
// a whole; the token is write-only, so an empty field keeps whatever
// the claw already stored. Presentational: data flows in as props,
// intent flows up as events.
import type { SandboxKind, SandboxSelection, SandboxState } from '~/composables/useClaw'
const props = defineProps<{
state: SandboxState | null
saving: boolean
}>()
const emit = defineEmits<{
save: [choice: SandboxSelection]
}>()
const kind = ref<SandboxKind>('local')
const url = ref('')
const token = ref('')
const clearToken = ref(false)
const host = ref('')
const workspace = ref('')
const privateKey = ref('')
const clearPrivateKey = ref(false)
const dirty = computed(() => {
const state = props.state
if (!state) return false
if (kind.value !== state.kind) return true
if (kind.value === 'http') {
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
}
if (kind.value === 'ssh') {
if (host.value.trim() !== (state.host ?? '')) return true
if (workspace.value.trim() !== (state.ssh_workspace ?? '')) return true
return privateKey.value.trim() !== '' || clearPrivateKey.value
}
return false
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const hostValid = computed(
() => host.value.trim() !== '' && !host.value.trim().includes(' '),
)
const ready = computed(() => {
if (kind.value === 'http') return urlValid.value
if (kind.value === 'ssh') return hostValid.value
return true
})
const urlHint = computed(() =>
url.value.trim() && !urlValid.value
? 'The URL must start with http:// or https://.'
: 'The sandboxd base URL, for example https://box.example:7600.',
)
const hostHint = computed(() =>
host.value.trim() && !hostValid.value
? 'One destination, no spaces: an alias or user@host your ssh config resolves.'
: 'An alias or user@host your ssh config resolves.',
)
function sync(): void {
const state = props.state
if (!state) return
kind.value = state.kind
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? ''
privateKey.value = ''
clearPrivateKey.value = false
}
watch(
() => props.state,
(state) => {
if (state) sync()
},
{ immediate: true },
)
function discard(): void {
sync()
}
function save(): void {
if (!dirty.value || props.saving || !ready.value) return
const choice: SandboxSelection = { kind: kind.value }
if (kind.value === 'http') {
choice.url = url.value.trim()
if (token.value.trim() !== '') {
choice.token = token.value.trim()
} else if (clearToken.value) {
choice.clear_token = true
}
}
if (kind.value === 'ssh') {
choice.host = host.value.trim()
choice.workspace = workspace.value.trim()
if (privateKey.value.trim() !== '') {
choice.private_key = privateKey.value
} else if (clearPrivateKey.value) {
choice.clear_private_key = true
}
}
emit('save', choice)
}
// The path the staged choice would use, not the saved one.
const workspacePath = computed(() => {
const state = props.state
if (!state) return ''
if (kind.value === 'local') return state.local_workspace
if (kind.value === 'http') return state.remote_workspace
return state.workspace
})
</script>
<template>
<div class="page">
<PageHeader title="Sandbox" subtitle="Where the agent's bash runs.">
<template #actions>
<button :disabled="!dirty || saving" @click="discard">Discard</button>
<button class="primary" :disabled="!dirty || saving || !ready" @click="save">
{{ saving ? 'Saving…' : 'Save' }}
</button>
</template>
</PageHeader>
<div class="scroll">
<p v-if="!state" class="muted">loading sandbox…</p>
<template v-else>
<SettingCard title="Execution" meta="applies on the next turn">
<label class="option" :class="{ selected: kind === 'local' }">
<input v-model="kind" type="radio" value="local" :disabled="saving" />
<span class="option-text">
<span class="option-title">
This machine
<span v-if="state.kind === 'local'" class="current">current</span>
</span>
<span class="option-detail">
Commands run as processes on the daemon's host.
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'http' }">
<input v-model="kind" type="radio" value="http" :disabled="saving" />
<span class="option-text">
<span class="option-title">
Remote sandbox
<span v-if="state.kind === 'http'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a host that speaks the sandbox protocol over HTTP.
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'ssh' }">
<input v-model="kind" type="radio" value="ssh" :disabled="saving" />
<span class="option-text">
<span class="option-title">
SSH host
<span v-if="state.kind === 'ssh'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a box the claw reaches with ssh, nothing installed on the far end.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'ssh'" title="SSH host">
<SettingRow title="Destination" :description="hostHint">
<input
v-model="host"
type="text"
class="mono"
placeholder="me@box.example"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Workspace base"
description="The remote directory the claw's workspaces live under. Defaults to /root."
>
<input
v-model="workspace"
type="text"
class="mono"
placeholder="/root"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Private key"
:description="state.private_key_set
? 'A key is stored. Leave this blank to keep it, or paste a replacement.'
: 'The key text itself (OpenSSH or PEM), not a path: the claw stores it, it stages no file. Leave blank to authenticate through an agent or the default key files.'"
>
<textarea
v-model="privateKey"
class="mono key-input"
rows="3"
:placeholder="state.private_key_set ? 'stored' : '-----BEGIN OPENSSH PRIVATE KEY-----'"
autocomplete="off"
spellcheck="false"
:disabled="saving || clearPrivateKey"
/>
</SettingRow>
<SettingRow
v-if="state.private_key_set"
title="Stored key"
:description="clearPrivateKey
? 'The stored key is removed when you save.'
: 'The key stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearPrivateKey = !clearPrivateKey">
{{ clearPrivateKey ? 'Keep key' : 'Forget key' }}
</button>
</SettingRow>
</SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
<SettingRow
title="URL"
:description="urlHint"
>
<input
v-model="url"
type="text"
class="mono"
placeholder="https://box.example:7600"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Token"
:description="state.token_set
? 'A token is stored. Leave this blank to keep it.'
: 'The shared secret the daemon checks. Leave it blank when the daemon has none.'"
>
<input
v-model="token"
type="password"
:placeholder="state.token_set ? 'stored' : 'optional'"
autocomplete="off"
:disabled="saving || clearToken"
/>
</SettingRow>
<SettingRow
v-if="state.token_set"
title="Stored token"
:description="clearToken
? 'The stored token is removed when you save.'
: 'The token stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearToken = !clearToken">
{{ clearToken ? 'Keep token' : 'Forget token' }}
</button>
</SettingRow>
</SettingCard>
<AppCallout v-if="kind !== 'local'" variant="info" title="Remote commands start from a copy">
On first use the claw sends the local workspace to the sandbox as a tarball.
Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout>
<SettingCard title="Workspace">
<SettingRow
title="Path"
description="Where the agent's bash starts under this choice."
>
<code>{{ workspacePath }}</code>
</SettingRow>
</SettingCard>
</template>
</div>
</div>
</template>
<style scoped>
.page {
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
flex: 1;
}
.scroll {
flex: 1;
overflow-y: auto;
padding: 0 24px 24px;
display: flex;
flex-direction: column;
gap: 16px;
max-width: 860px;
}
.muted {
color: var(--text3);
padding: 8px 2px;
}
.option {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 13px 16px;
cursor: pointer;
}
.option:hover {
background: var(--elevated);
}
.option.selected {
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
}
.option input[type='radio'] {
flex: none;
margin: 3px 0 0;
accent-color: var(--accent);
}
.option-text {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
.option-title {
display: flex;
align-items: baseline;
gap: 8px;
color: var(--text);
font-weight: 600;
}
.option-detail {
color: var(--text3);
font-size: 12.5px;
}
.current {
color: var(--accent-text);
font-size: 12px;
font-weight: 500;
}
.key-input {
width: 100%;
min-width: 0;
resize: vertical;
font-size: 12px;
word-break: break-all;
}
</style>
+17 -209
View File
@@ -56,20 +56,9 @@ export interface UserImage {
media_type: string
}
/** One paste chip a `user_message` carries: the record the session's
* `rhema-code` annotation holds — the byte range in the plain text the
* chip stands for (UTF-8 offsets; see useTranscript's
* `byteToIndex`), plus the payload's line count for the chip's label
* (rhema-core `PasteSpan`). */
export interface PasteSpan {
start: number
end: number
lines: number
}
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
export type TurnEvent =
| { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
| { type: 'user_message'; text: string; images: UserImage[] }
| { type: 'thinking_delta'; text: string }
| { type: 'text_delta'; text: string }
| { type: 'tool_start'; name: string }
@@ -95,17 +84,6 @@ export interface ClawSession {
revision: number
inbox_depth: number
last_outcome: string | null
/** Whether the pause gate holds the key: queued work waits, nothing
* dispatches, until resume lifts the hold. */
paused: boolean
}
/** The `POST /v1/sessions/{key}/abort` answer: `cut` when a live turn
* was signalled, `dropped` the queued items the route drained. */
export interface AbortResult {
key: string
cut: boolean
dropped: number
}
/** One watch (config.rs `Watch`, as the watches routes accept and return it). */
@@ -203,7 +181,6 @@ export interface ProvidersState {
* unset text fields read as null, the images report presence. */
export interface AgentIdentity {
name: string | null
email: string | null
mark: string | null
initials: string | null
tagline: string | null
@@ -216,7 +193,6 @@ export interface AgentIdentity {
* string clears the field. */
export interface IdentityTexts {
name: string
email: string
mark: string
initials: string
tagline: string
@@ -244,51 +220,6 @@ export interface ActiveBackend {
active: { provider: string; model: string }
}
/** Where the agent's `bash` runs: this host, a daemon speaking the
* sandbox protocol over HTTP, or an ssh login on a far box. */
export type SandboxKind = 'local' | 'http' | 'ssh'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */
export interface SandboxState {
kind: SandboxKind
url: string | null
token_set: boolean
/** Whether an ssh private key is stored; the key itself never
* rides the wire. */
private_key_set: boolean
/** The ssh destination, an alias or `user@host` the local ssh
* config resolves. */
host: string | null
/** The ssh workspace base the workspaces sit under, `null` for the
* default. */
ssh_workspace: string | null
/** Where `bash` starts under the current choice. */
workspace: string
/** The daemon's chat workspace, whatever the choice. */
local_workspace: string
/** The path a remote sandbox exposes. */
remote_workspace: string
}
/** The body `PUT /v1/sandbox` takes. `token` is write-only, and
* `clear_token` drops the stored one. An omitted `url` keeps the
* current one. */
export interface SandboxSelection {
kind: SandboxKind
url?: string
token?: string
clear_token?: boolean
host?: string
/** The ssh private key text (no file): the store-held credential.
* Write-only, like the token. */
private_key?: string
clear_private_key?: boolean
/** The ssh workspace base; the per-workspace directories land under
* it. An omitted value keeps the current one. */
workspace?: string
}
/** A failed API call: the status plus the claw's `error` string when it sent one. */
export class ClawError extends Error {
/** HTTP status; 0 when the claw was unreachable at all. */
@@ -309,9 +240,7 @@ const INTERACTIVE_PREFIX = 'interactive:'
* connection and reconnects: the claw sends a keep-alive comment every
* fifteen seconds (hub.rs), so three missed ones means the path is
* black-holed — a half-open TCP after a laptop sleep shows the same
* 'live' badge a healthy stream does without this check. 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. */
* 'live' badge a healthy stream does without this check. */
const STREAM_SILENCE_TIMEOUT_MS = 45000
/** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */
@@ -319,13 +248,12 @@ export function isInteractive(key: string): boolean {
return key.startsWith(INTERACTIVE_PREFIX)
}
/** The prefixes the daemon's resident context owns: its
* `is_resident_key` (`crates/rhema-claw/src/interactive.rs`). A resident
* key has a live turn record the event stream follows. Every other key
* in the inventory — a forge thread, a coding job — answers no stream
* and takes no message: its history route serves the snapshot the
* engine checkpointed, and the panel renders it read-only. */
const RESIDENT_PREFIXES = ['interactive:', 'task:', 'phone:', 'calendar:']
/** The prefixes the chat surface answers for: the daemon's
* `is_resident_key` (`crates/rhema-claw/src/interactive.rs`). Every other
* key in the inventory — `phone:` status reporting, `job:<instance>#<id>`,
* a forge thread — has no transcript: the message, event and history
* routes 400 on it. */
const RESIDENT_PREFIXES = ['interactive:', 'task:', 'calendar:']
/** Whether `key` is one the transcript surface can open. */
export function isResidentKey(key: string): boolean {
@@ -415,9 +343,6 @@ export interface StreamHandlers {
export interface HistoryPage {
events: { seq: number; event: TurnEvent }[]
more: boolean
/** The page is a snapshot of a key the daemon cannot take messages
* for: the chat surface renders it and hides the composer. */
readOnly: boolean
}
export interface ClawApi {
@@ -431,14 +356,6 @@ export interface ClawApi {
* same name starts empty. 409 while a turn holds the key, 404 when it is
* already gone. */
deleteSession(key: string): Promise<void>
/** `POST /v1/sessions/{key}/pause` — hold the key's dispatch. 404
* when the inventory has no such key. */
pauseSession(key: string): Promise<void>
/** `POST /v1/sessions/{key}/resume` — lift the hold. */
resumeSession(key: string): Promise<void>
/** `POST /v1/sessions/{key}/abort` — cut the live turn, or drop the
* queued work when none runs. */
abortSession(key: string): Promise<AbortResult>
/** `GET /v1/consents` — the pending consents, oldest first. */
listConsents(): Promise<ConsentRequest[]>
/** `POST /v1/consents/{id}` — answer one consent; 409 when already
@@ -451,8 +368,8 @@ export interface ClawApi {
* a plain src will not do). Cached per id: attachments are immutable,
* so a replayed event never refetches. */
attachmentUrl(id: string): Promise<string>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void>
/** `GET /v1/providers` — the constructible backends and the active pair. */
providers(): Promise<ProvidersState>
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
@@ -466,11 +383,6 @@ export interface ClawApi {
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers
* the new providers state. The last backend is refused claw-side. */
removeProvider(id: string): Promise<ProvidersState>
/** `GET /v1/sandbox`: where the agent's `bash` runs. */
sandbox(): Promise<SandboxState>
/** `PUT /v1/sandbox`: switch the sandbox, persisted claw-side. The
* choice applies on the next turn. */
setSandbox(choice: SandboxSelection): Promise<SandboxState>
/** `GET /v1/accounts` — the stored accounts, redacted. */
accounts(): Promise<ClawAccount[]>
/** `POST /v1/accounts` — store an account (the secret is write-only),
@@ -515,7 +427,6 @@ export interface ClawApi {
* `GET /v1/sessions/{key}/history` — one page of whole turns ending
* at `before` (absent: the newest). Pages stack: the next call passes
* the seq of the oldest event held, and stops when `more` is false.
* A non-resident key answers a read-only snapshot here.
*/
history(key: string, before?: number | null, limit?: number): Promise<HistoryPage>
}
@@ -567,27 +478,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})
}
async function pauseSession(key: string): Promise<void> {
await send(`/v1/sessions/${encodeURIComponent(key)}/pause`, {
method: 'POST',
headers: authHeaders(token.value),
})
}
async function resumeSession(key: string): Promise<void> {
await send(`/v1/sessions/${encodeURIComponent(key)}/resume`, {
method: 'POST',
headers: authHeaders(token.value),
})
}
async function abortSession(key: string): Promise<AbortResult> {
return (await send(`/v1/sessions/${encodeURIComponent(key)}/abort`, {
method: 'POST',
headers: authHeaders(token.value),
})) as AbortResult
}
async function listConsents(): Promise<ConsentRequest[]> {
const body = (await get('/v1/consents', token.value)) as { consents: ConsentRequest[] }
return body.consents
@@ -608,19 +498,11 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})
}
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
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> {
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(body),
body: JSON.stringify(images?.length ? { text, images } : { text }),
})
}
@@ -636,11 +518,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const body = (await get(
`/v1/sessions/${encodeURIComponent(key)}/history${query}`,
token.value,
)) as {
events?: { seq?: unknown; event?: unknown }[]
more?: unknown
read_only?: unknown
}
)) as { events?: { seq?: unknown; event?: unknown }[]; more?: unknown }
// The wire shape is trusted only as far as it parses: an event the
// parser does not know is dropped, and its seq with it — the page
// still renders what it could read.
@@ -648,7 +526,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const event = parseTurnEvent(JSON.stringify(entry.event))
return event && typeof entry.seq === 'number' ? [{ seq: entry.seq, event }] : []
})
return { events, more: body.more === true, readOnly: body.read_only === true }
return { events, more: body.more === true }
}
async function providers(): Promise<ProvidersState> {
@@ -685,18 +563,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
})) as ProvidersState
}
async function sandbox(): Promise<SandboxState> {
return (await get('/v1/sandbox', token.value)) as SandboxState
}
async function setSandbox(choice: SandboxSelection): Promise<SandboxState> {
return (await send('/v1/sandbox', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
body: JSON.stringify(choice),
})) as SandboxState
}
async function accounts(): Promise<ClawAccount[]> {
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
return body.accounts
@@ -773,19 +639,11 @@ export function useClaw(token: Ref<string | null>): ClawApi {
* notice says so instead of naming an opaque abort error. */
let timedOut = false
let silence: ReturnType<typeof setTimeout> | null = null
const isHidden = (): boolean =>
typeof document !== 'undefined' && document.hidden
/** Whether the attempt in flight crossed a hidden tab: a drop there
* is a backgrounded connection, not a stream the user needs a notice
* about. */
let hiddenDuringAttempt = isHidden()
const rearmSilence = (): void => {
if (silence !== null) clearTimeout(silence)
silence = null
if (closed || isHidden()) return
silence = setTimeout(() => {
if (closed || isHidden()) return
if (closed) return
timedOut = true
current?.abort()
}, STREAM_SILENCE_TIMEOUT_MS)
@@ -794,23 +652,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
if (silence !== null) clearTimeout(silence)
silence = null
}
/** A frame or keep-alive proved this attempt alive: from here on a
* drop is real, even if the tab was hidden earlier. */
const noteActivity = (): void => {
hiddenDuringAttempt = false
rearmSilence()
}
const visibility = (): void => {
if (isHidden()) {
hiddenDuringAttempt = true
stopSilence()
return
}
if (current !== null && !current.signal.aborted) rearmSilence()
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', visibility)
}
const status = (next: StreamStatus) => {
if (!closed) handlers.onStatus?.(next)
@@ -822,7 +663,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
const controller = new AbortController()
current = controller
timedOut = false
hiddenDuringAttempt = isHidden()
rearmSilence()
try {
const resume = cursor === null ? '' : `?since=${cursor}`
@@ -844,7 +684,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
await readFrames(
response.body,
(data, id) => {
noteActivity()
rearmSilence()
const event = parseTurnEvent(data)
if (!event) return
const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null
@@ -854,7 +694,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
(comment) => {
// Keep-alives come through here too; each one proves the
// path alive.
noteActivity()
rearmSilence()
// The record lost what this mirror holds: drop the cursor
// so the next open asks for the tail, and let the consumer
// drop its items before the tail that already followed
@@ -880,16 +720,11 @@ export function useClaw(token: Ref<string | null>): ClawApi {
// Backoff caps at 15s: a live stream of a running turn is the
// UI's whole job, so retries stay eager but not tight-looped.
const backoff = Math.min(15000, 1000 * 2 ** attempt++)
// A connection that crossed a hidden tab reconnects quietly:
// the browser held it while the page was in the background,
// and the operator did not just lose a live stream.
if (!isHidden() && !hiddenDuringAttempt) {
handlers.onNotice?.(
timedOut
? `the event stream went quiet (no keep-alive for ${STREAM_SILENCE_TIMEOUT_MS / 1000}s); reconnecting in ${backoff / 1000}s`
: `event stream dropped (${cause instanceof Error ? cause.message : String(cause)}); retrying in ${backoff / 1000}s`,
)
}
status('reconnecting')
await new Promise((resolve) => setTimeout(resolve, backoff))
} finally {
@@ -903,9 +738,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
close() {
closed = true
stopSilence()
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', visibility)
}
current?.abort()
},
}
@@ -915,9 +747,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
sessions,
createSession,
deleteSession,
pauseSession,
resumeSession,
abortSession,
listConsents,
resolveConsent,
denyConsent,
@@ -928,8 +757,6 @@ export function useClaw(token: Ref<string | null>): ClawApi {
models,
setCredentials,
removeProvider,
sandbox,
setSandbox,
accounts,
addAccount,
removeAccount,
@@ -1009,24 +836,6 @@ function parseUserImages(raw: unknown): UserImage[] {
return images
}
/** The paste chips a `user_message` carries: rows recorded before
* chips rode as spans carry the mark form in the text instead and no
* field at all — empty, the render falls back to scanning — and a
* span without whole-number bounds or a line count is not one. */
function parseUserPastes(raw: unknown): PasteSpan[] {
if (!Array.isArray(raw)) return []
const pastes: PasteSpan[] = []
for (const entry of raw) {
const span = entry as Record<string, unknown>
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
if (typeof span.lines !== 'number') continue
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
pastes.push({ start: span.start, end: span.end, lines: span.lines })
}
return pastes
}
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
function parseTurnEvent(data: string): TurnEvent | null {
try {
@@ -1037,7 +846,6 @@ function parseTurnEvent(data: string): TurnEvent | null {
type: 'user_message',
text: String(raw.text ?? ''),
images: parseUserImages(raw.images),
pastes: parseUserPastes(raw.pastes),
}
case 'thinking_delta':
case 'text_delta':
+47 -78
View File
@@ -6,7 +6,7 @@
// mirror when the stream reopens and folds what arrives, never the other
// way around.
import { ref } from 'vue'
import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw'
/** One tool call inside a turn: started, then completed by its result. */
export interface ToolRow {
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
/** A transcript line: a message the local user sent, or one streamed turn. */
export type TranscriptItem =
| { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
| { kind: 'sent'; id: number; text: string; images: SentImage[] }
| { kind: 'turn'; id: number; turn: TurnBlock }
| { kind: 'consent'; id: number; consent: ConsentCard }
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
@@ -123,53 +123,20 @@ export function lineCount(text: string): number {
return lines.length
}
/** A chip's label from its line count: `▣1 5L` — the chip's
* one-based id and the payload's line count (the TUI's chip_label). */
export function chipLinesLabel(lines: number, index: number): string {
return `▣${index + 1} ${lines}L`
}
/** A chip's label from its payload (the TUI's chip_label). */
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
* payload's line count (the TUI's chip_label). */
export function chipLabel(paste: string, index: number): string {
return chipLinesLabel(lineCount(paste), index)
return `▣${index + 1} ${lineCount(paste)}L`
}
/** The modern record the wire carries: each paste a byte span in the
* plain text (the `rhema-code` annotation's own shape), one walk over
* the composed text mapping every code-point boundary — a span that
* splits a code point maps to none, the render skips it. */
export function byteToIndex(text: string): (byte: number) => number {
const at = new Map<number, number>([[0, 0]])
const bytesOf = new TextEncoder()
let bytes = 0
let units = 0
for (const cp of text) {
bytes += bytesOf.encode(cp).length
units += cp.length
at.set(bytes, units)
}
return (byte) => at.get(byte) ?? -1
}
/** Composes a send the way the fold composes its record: each paste's
* normalized payload appends to the draft, its chip's span measured
* over the composed plain text. The same form the `user_message`
* echo carries, so the optimistic row and the replay render rows of
* one shape and the echo dedupes against what this surface sent. */
export function composeChips(
draft: string,
pastes: string[],
): { text: string; pastes: PasteSpan[] } {
const bytesOf = new TextEncoder()
let text = draft
const spans: PasteSpan[] = []
for (const paste of pastes) {
const payload = normalizePaste(paste)
const start = bytesOf.encode(text).length
text += payload
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
}
return { text, pastes: spans }
/** Appends each paste as one MARK-payload-MARK embed, in order — the
* session's record of the prompt (paste::embed; a web draft holds no
* anchors, so every payload lands at the end). */
export function embedPastes(draft: string, pastes: string[]): string {
return (
draft +
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
)
}
/** One scanned piece of embedded-form text. */
@@ -277,7 +244,6 @@ export function useTranscript() {
id: nextId++,
text: event.text,
images: event.images.map((image) => ({ ...image, url: null, name: null })),
pastes: event.pastes,
})
break
}
@@ -390,10 +356,10 @@ export function useTranscript() {
* Its images render from the staged previews — the claw stores them
* and the stream's echo dedupes against this row. Returns the row's
* id, so a failed POST can retract it. */
function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
function addSent(text: string, images: SentImage[] = []): number {
const id = nextId++
pendingSent.push({ text, images: images.length, itemId: id })
items.value.push({ kind: 'sent', id, text, images, pastes })
items.value.push({ kind: 'sent', id, text, images })
return id
}
@@ -409,42 +375,41 @@ export function useTranscript() {
if (pending !== -1) pendingSent.splice(pending, 1)
}
/** The cards on the mirror, at either depth. A card lands in the open
* turn's entries and rides into the finished turn with it, so a scan
* of the top-level rows alone misses everything a turn handed over.
* The returned objects are the mirror's own, not copies: flipping one
* flips what the panel renders. */
function cards(): TurnEntry[] {
const found: TurnEntry[] = [...(live.value?.entries ?? [])]
for (const item of items.value) {
if (item.kind === 'consent' || item.kind === 'attachment') {
found.push(item)
} else if (item.kind === 'turn') {
found.push(...item.turn.entries)
}
}
return found
}
/** A consent card resolved: flipped in place, or ignored when no
* card carries the id. */
* card carries the id. The in-flight turn's entries hold the cards a
* running turn asked for; finished turns keep their own copies. */
function resolveConsent(id: string, granted: boolean): void {
for (const card of cards()) {
if (card.kind === 'consent' && card.consent.id === id) {
card.consent.granted = granted
if (live.value) {
for (const entry of live.value.entries) {
if (entry.kind === 'consent' && entry.consent.id === id) {
entry.consent.granted = granted
return
}
}
}
for (const item of items.value) {
if (item.kind === 'consent' && item.consent.id === id) {
item.consent.granted = granted
return
}
}
}
/** An attachment's object URL landed; stored on every card that names
* the id. Two cards can hold one id when a page's open tail is dropped
* and re-read, so the loop does not stop at the first. The useClaw
/** An attachment's object URL landed; stored on its card. The useClaw
* cache keeps a reconnect's replay from refetching the bytes. */
function setAttachmentUrl(id: string, url: string): void {
for (const card of cards()) {
if (card.kind === 'attachment' && card.attachment.id === id) {
card.attachment.url = url
if (live.value) {
for (const entry of live.value.entries) {
if (entry.kind === 'attachment' && entry.attachment.id === id) {
entry.attachment.url = url
return
}
}
}
for (const item of items.value) {
if (item.kind === 'attachment' && item.attachment.id === id) {
item.attachment.url = url
return
}
}
}
@@ -467,12 +432,16 @@ export function useTranscript() {
/** Whether a card for this consent id is already on the mirror — a
* replayed request never stacks a second card beside the first. */
function findConsent(id: string): boolean {
return cards().some((card) => card.kind === 'consent' && card.consent.id === id)
if (live.value?.entries.some((e) => e.kind === 'consent' && e.consent.id === id)) return true
return items.value.some((item) => item.kind === 'consent' && item.consent.id === id)
}
/** Whether a card for this attachment id is already on the mirror. */
function findAttachment(id: string): boolean {
return cards().some((card) => card.kind === 'attachment' && card.attachment.id === id)
if (live.value?.entries.some((e) => e.kind === 'attachment' && e.attachment.id === id)) {
return true
}
return items.value.some((item) => item.kind === 'attachment' && item.attachment.id === id)
}
/** Reads one page of older turns (whole turns, oldest first) and
+1921 -1116
View File
File diff suppressed because it is too large. Load diff