forked from vhaudiquet/rhema-claw
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c13455f35 | ||
|
|
6abb1436b5 | ||
|
|
c5bf168eed | ||
|
|
df260fd9a8 | ||
|
|
ed645d1faf | ||
|
|
51456f5b4c | ||
|
|
ea4810a576 | ||
|
|
68671c76ce | ||
|
|
c56f544993 | ||
|
|
268917646e | ||
|
|
d74b1c40df | ||
|
|
504330b1b5 | ||
|
|
b6327a458f | ||
|
|
2f6c369e02 |
No files matched your search
Generated
+341
-85
@@ -411,6 +411,23 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
@@ -893,8 +910,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -904,8 +923,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1079,6 +1101,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1338,6 +1361,12 @@ version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
@@ -1672,6 +1701,62 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
"pin-project-lite",
|
||||
"quinn-proto",
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand 0.10.4",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -1695,7 +1780,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"getrandom 0.4.3",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1705,7 +1801,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1717,6 +1813,21 @@ dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||
|
||||
[[package]]
|
||||
name = "rand_pcg"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df"
|
||||
dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
@@ -1771,6 +1882,8 @@ dependencies = [
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1778,6 +1891,7 @@ dependencies = [
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -1787,30 +1901,14 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-streams",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-agent-tools"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "839fa542e680de80f25876d6f54ea45dbace72a89d5f63f52c4423e54f048f82"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"minijinja",
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-autonomous-agent"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e3ee50c812fa93f31be669557cb642ed8d03154613234b2090fa9567374516e"
|
||||
checksum = "08fd6d5fe5f9551226d322491d03b14d5e42ac2ff73544c15a555fb97a04bbfd"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"rhema-core",
|
||||
@@ -1822,9 +1920,25 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-bash"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf9ae34e5c556e0abdf279dd7d0aa08632bdcd68cff965bce2b81c226ada8f1e"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"rhema-core",
|
||||
"rhema-submissions",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-calendar-integration"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"quick-xml",
|
||||
@@ -1843,27 +1957,31 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-claw"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"clap",
|
||||
"reqwest",
|
||||
"rhema-agent-tools",
|
||||
"rhema-autonomous-agent",
|
||||
"rhema-bash",
|
||||
"rhema-calendar-integration",
|
||||
"rhema-claw-tools-contract",
|
||||
"rhema-coding-agent",
|
||||
"rhema-config",
|
||||
"rhema-core",
|
||||
"rhema-forge-integration",
|
||||
"rhema-host-agent",
|
||||
"rhema-identity",
|
||||
"rhema-mcp",
|
||||
"rhema-memory",
|
||||
"rhema-prompt",
|
||||
"rhema-provider",
|
||||
"rhema-provider-registry",
|
||||
"rhema-rsd",
|
||||
"rhema-sandbox",
|
||||
"rhema-sandbox-http",
|
||||
"rhema-transcript",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
@@ -1879,7 +1997,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-claw-tools-contract"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1887,40 +2005,24 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-coding-agent"
|
||||
version = "0.2.3"
|
||||
name = "rhema-config"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b5ef3b970ced4f05b4d18b9df56ca6a46bb488af7579f8d3c4a10788ca47761"
|
||||
checksum = "a0bbfb885f219272d24534c004819db377cf5370de0f82a851f9329466a5349c"
|
||||
dependencies = [
|
||||
"minijinja",
|
||||
"rhema-agent-tools",
|
||||
"rhema-config",
|
||||
"keyring",
|
||||
"rhema-core",
|
||||
"rhema-transcript",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-config"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efd98e6c5dd53a6e30367ae4c259ea03e5d214962aae9c1d66ab03f464487988"
|
||||
dependencies = [
|
||||
"keyring",
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_yaml",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-core"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b399005d398dd0dca791415a07f6280bacebc0aedfa84f9d3a29640f45f91144"
|
||||
checksum = "c3cd4c7a28b121243a2e26371e53750f28368e96c1a1629f021847c717e1cd55"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"serde",
|
||||
@@ -1930,7 +2032,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-forge-integration"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"reqwest",
|
||||
@@ -1943,10 +2045,30 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-identity"
|
||||
version = "0.2.3"
|
||||
name = "rhema-host-agent"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f9355d075f5ff5800f9b6b4216e65ba087f681716bc0faf69986852eb13be26"
|
||||
checksum = "3c10a82a420f1ea5ad1e68cabf0da67e6d05f18ec9e6fa02993969c2dcc53a68"
|
||||
dependencies = [
|
||||
"minijinja",
|
||||
"rhema-bash",
|
||||
"rhema-config",
|
||||
"rhema-core",
|
||||
"rhema-prompt",
|
||||
"rhema-session-store",
|
||||
"rhema-session-store-file",
|
||||
"rhema-transcript",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-identity"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1bb799ae7395c647577b9cf26208d81c2913d893db050adc82976e88436226c"
|
||||
dependencies = [
|
||||
"rusqlite",
|
||||
"serde",
|
||||
@@ -1955,9 +2077,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-mcp"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efb7dff3b33b3931c9da4ea6577e55f41c820cf5b2b880b06b8581f15673e06e"
|
||||
checksum = "6ed674931827b5b5e3130b376bda837cf49bda6ca6c94392430b74e292b6f516"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"axum",
|
||||
@@ -1967,10 +2089,12 @@ dependencies = [
|
||||
"futures-util",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"mcp-to-cli",
|
||||
"rhema-agent-tools",
|
||||
"rhema-bash",
|
||||
"rhema-config",
|
||||
"rhema-prompt",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -1980,9 +2104,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-memory"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5a0f161c473ae19dc161a1ad898603150ec6be081f24262182e15ea348db3b5"
|
||||
checksum = "34d3b6763b7c567849b6f1787bae7152ce92ec38bdbe2ec27691d4ef2596c259"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"rhema-core",
|
||||
@@ -1993,13 +2117,27 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider"
|
||||
version = "0.2.3"
|
||||
name = "rhema-prompt"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d178053a9d5400cf001109670f2294e427ded6cb895b235b4f4ffc2bc20f2f09"
|
||||
checksum = "b70bba0a045879067817db80fcaa7578dc32ef699786cc004b8fdb73bccc47e4"
|
||||
dependencies = [
|
||||
"minijinja",
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c400c1ac8430f78184ecc12024605686a988ada7a3ee30dd67a4ce12114ccb9e"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-core",
|
||||
"reqwest",
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2009,9 +2147,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-anthropic"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc26ff01350bab0fb10a53fc11665dca939c3fda2ec1a3df93912a39b3fc8b0c"
|
||||
checksum = "a57458493f5b1fb540fa47f558f7743094dc123d2c06815d2078f9303d9df22f"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -2025,14 +2163,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-chatgpt"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb807b39e95c49d2a5e8c101220ac34a9d6770aece6bece1eebcf8113b1811a2"
|
||||
checksum = "7642b1e0bc194cc81d7f347182eecd6702a04a85de41912bd2d34b2cdf41ca7b"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"futures-util",
|
||||
"rand",
|
||||
"rand 0.8.8",
|
||||
"reqwest",
|
||||
"rhema-core",
|
||||
"rhema-provider",
|
||||
@@ -2044,9 +2182,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-copilot"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98cc6f041cb328de999c17abc34d3e050d586a2390d32ec9ae5fa543bd177fa0"
|
||||
checksum = "eb39fa7f059df415bdef2453e58ad5359fd74eeb39f7981179f03c78ffb5af7d"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -2062,9 +2200,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-google"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99cbbb477a94d995b09a3154288a0f5f10aee22fd35bc1d1145bbffee27ea388"
|
||||
checksum = "7dda76eea354cfbdfd4a2dfa1fc1ce8da823675699cf2bf4d3ace8560fec2cd7"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -2078,9 +2216,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-llama-cpp"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e3491fcb305e448492868473c6a146575174bdbb7ab328c85bf43a698052f56"
|
||||
checksum = "953181611b909688db511f891e8c59e034b90bd798034f1afef36cac05409566"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -2094,10 +2232,29 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-openai-compatible"
|
||||
version = "0.2.3"
|
||||
name = "rhema-provider-mistral"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98976f2fd5f8f09e5838405f53e2b9f113a5e9d2ed3823a80117f4919f0249a6"
|
||||
checksum = "1f657297d7d617a14b10bb6248e944d053d73a536d3b6ae4ee4cc8acabcb4a57"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"rand 0.8.8",
|
||||
"reqwest",
|
||||
"rhema-core",
|
||||
"rhema-provider",
|
||||
"rhema-provider-openai-compatible",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-openai-compatible"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a90f1620882b2a3dbdb00065b29c329622c5596f582027b29130fbd40003b450"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -2111,9 +2268,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-opencode"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9f6cc7db60525e63712ec2b66881cd57f3bb7b7b8c14001eebf86f64030302a"
|
||||
checksum = "2068c980362fe3d4f7876e5e842f51c0719626449afac64192592865e11a0108"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"reqwest",
|
||||
@@ -2126,9 +2283,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-openrouter"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ca68e90f9627c58e0908e52e010bd7c47e498290c40358c2ff326e95a9a20cc"
|
||||
checksum = "c2025f84d6a1fd1e513ffad4b374d280f0db600ffac635dfe08a58d04b03e91d"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures-util",
|
||||
@@ -2142,9 +2299,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-provider-registry"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8f6b0b10943f6fa4272490acc3c33040944d85490971a8a1acc8515d704bfc2"
|
||||
checksum = "be5ed790e3dc4fc3a42bd9b1a633ef72204c519810ce03dafb2792a8ff0b6bf8"
|
||||
dependencies = [
|
||||
"rhema-core",
|
||||
"rhema-provider",
|
||||
@@ -2153,6 +2310,7 @@ dependencies = [
|
||||
"rhema-provider-copilot",
|
||||
"rhema-provider-google",
|
||||
"rhema-provider-llama-cpp",
|
||||
"rhema-provider-mistral",
|
||||
"rhema-provider-openai-compatible",
|
||||
"rhema-provider-opencode",
|
||||
"rhema-provider-openrouter",
|
||||
@@ -2161,9 +2319,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rhema-rsd"
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1e05417b86144a2a0dbad3018a73c0b2376b5fec378676aea6b912678b059f6"
|
||||
checksum = "3a4bd0555ff3720c0501187f5e9c6ee19ebebb95c1ecdb296c509c2e2dd971ce"
|
||||
dependencies = [
|
||||
"rhema-core",
|
||||
"rusqlite",
|
||||
@@ -2173,10 +2331,75 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-transcript"
|
||||
version = "0.2.3"
|
||||
name = "rhema-sandbox"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b00234b8879bd894f0a45a1fd804c94c7cc3d31ea9f5361609041cb42587a719"
|
||||
checksum = "7030dbd46aa8a2398452dcf86b6b39d13b82909b9fdc654c49e1374183594779"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"rhema-bash",
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-sandbox-http"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5171470a8a56246e036aa10fc63e641ae7907a3ce70ac8f4816f3c9499eb75b"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"reqwest",
|
||||
"rhema-sandbox",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-session-store"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef2dd4aca030a56e438c136099d3f07d6fd4649a3db1be6c9838a68a6530cbf6"
|
||||
dependencies = [
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-session-store-file"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5ff65f110123026ae79679572b084c517693f81e0d464897e580b64985a9507"
|
||||
dependencies = [
|
||||
"rhema-config",
|
||||
"rhema-core",
|
||||
"rhema-session-store",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-submissions"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d054ba904c324ef057c8fb4b9c88a40703496c8b621768844af56a8893d3fb99"
|
||||
dependencies = [
|
||||
"rhema-core",
|
||||
"rhema-session-store",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-transcript"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "800261e8c1f29e6ceee48769bba2aaea19ccd3496ff8c6c76c617aa7d53ec2db"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"rhema-core",
|
||||
@@ -2224,6 +2447,12 @@ dependencies = [
|
||||
"sqlite-wasm-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.6"
|
||||
@@ -2244,6 +2473,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
@@ -2256,6 +2486,7 @@ version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -2661,6 +2892,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
@@ -3032,6 +3269,25 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-time"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/*", "integrations/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.3"
|
||||
version = "0.4.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.89"
|
||||
license = "MIT"
|
||||
|
||||
@@ -11,7 +11,7 @@ surface over HTTP — native routes plus an OpenAI-compatible shim,
|
||||
with a web UI and an Android client talking to it.
|
||||
|
||||
The framework it embeds (the crates under `crates/` it pulls from
|
||||
crates.io: `rhema-autonomous-agent`, `rhema-coding-agent`,
|
||||
crates.io: `rhema-autonomous-agent`, `rhema-host-agent`,
|
||||
`rhema-rsd`, and friends) lives in the
|
||||
[rhema repository](https://git.vhaudiquet.fr/vhaudiquet/rhema).
|
||||
|
||||
|
||||
+5
-2
@@ -77,8 +77,11 @@ manages the device fleet the claw keeps.
|
||||
**subscribe first, then POST**, the reply arrives on the stream. Thinking
|
||||
deltas render dim and collapsible, tool rows show name/summary with error
|
||||
coloring (bash-like tools render as shell lines instead: dim `$` prefix,
|
||||
the command line, and an exit-code badge), pasted payloads embedded in a
|
||||
message as paired `U+FFFC` marks render as compact `▣N 5L` chips, and
|
||||
the command line, and an exit-code badge), a message's paste chips render
|
||||
as compact `▣N 5L` labels sliced from the span record its
|
||||
`user_message` carries beside the plain text (rows recorded before
|
||||
spans rode the stream still scan the legacy paired-`U+FFFC` form in
|
||||
the text), and
|
||||
`attachment` events render as cards: file name, size, caption, an inline
|
||||
preview for small (≤ 2 MB) images, and a download-and-open row (bytes
|
||||
from `GET /v1/attachments/{id}` land in the app cache and open through a
|
||||
|
||||
@@ -11,6 +11,7 @@ import rs.rhema.phone.net.ClawApi
|
||||
import rs.rhema.phone.net.ClawEvent
|
||||
import rs.rhema.phone.net.ClawResult
|
||||
import rs.rhema.phone.net.OutboundImage
|
||||
import rs.rhema.phone.net.PasteSpan
|
||||
import rs.rhema.phone.net.SseFrame
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -61,6 +62,10 @@ class ChatController(
|
||||
override val id: Long,
|
||||
val text: String,
|
||||
val images: List<SentImage> = emptyList(),
|
||||
// The chip record this surface's rows never carry (its
|
||||
// composer sends plain text) but a replayed row — a web user's
|
||||
// chips in this conversation — does; the render slices on it.
|
||||
val pastes: List<PasteSpan> = emptyList(),
|
||||
) : Item
|
||||
data class Thinking(override val id: Long, val text: String) : Item
|
||||
data class ToolCall(
|
||||
@@ -355,14 +360,15 @@ class ChatController(
|
||||
is ClawEvent.UserMessage -> {
|
||||
// The recorded question — replayed on reload, echoed live
|
||||
// for a message this surface just sent. An identical last
|
||||
// row — same text, same image count — is that echo's
|
||||
// stand-in; skip it, previews and all.
|
||||
// row — same text, same image count, same chip record —
|
||||
// is that echo's stand-in; skip it, previews and all.
|
||||
val last = list.lastOrNull()
|
||||
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size)) {
|
||||
if (!(last is UserMessage && last.text == event.text && last.images.size == event.images.size && last.pastes == event.pastes)) {
|
||||
list = list + UserMessage(
|
||||
newId(),
|
||||
event.text,
|
||||
event.images.map { SentImage(attachmentId = it.id, file = null, mediaType = it.mediaType) },
|
||||
event.pastes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,13 @@ data class RhemaNotification(
|
||||
@Serializable
|
||||
data class UserImage(val id: String, @SerialName("media_type") val mediaType: String)
|
||||
|
||||
// One paste chip a user_message records: the byte span (UTF-8) of the
|
||||
// payload in the message's plain text, plus the payload's line count
|
||||
// — the session annotation's own shape (rhema-core `PasteSpan`), so a
|
||||
// chip renders from the record instead of rebuilding the wire form.
|
||||
@Serializable
|
||||
data class PasteSpan(val start: Int = 0, val end: Int = 0, val lines: Int = 0)
|
||||
|
||||
// One event of GET /v1/sessions/{key}/history: the record's seq for it,
|
||||
// beside the event itself. Seq order is the wire order.
|
||||
@Serializable
|
||||
@@ -138,11 +145,13 @@ data class HistoryPage(val events: List<HistoryEvent> = emptyList(), val more: B
|
||||
sealed interface ClawEvent {
|
||||
@Serializable
|
||||
@SerialName("user_message")
|
||||
// Rows recorded before images rode the stream carry no field at
|
||||
// all; absent folds to none, never a guessed shape.
|
||||
// Rows recorded before images — and then before chips — rode the
|
||||
// stream carry no field at all; absent folds to none, never a
|
||||
// guessed shape.
|
||||
data class UserMessage(
|
||||
val text: String = "",
|
||||
val images: List<UserImage> = emptyList(),
|
||||
val pastes: List<PasteSpan> = emptyList(),
|
||||
) : ClawEvent
|
||||
|
||||
@Serializable
|
||||
|
||||
@@ -82,6 +82,7 @@ import rs.rhema.phone.chat.MAX_STAGED_IMAGES
|
||||
import rs.rhema.phone.data.AgentIdentityCache
|
||||
import rs.rhema.phone.di.AppContainer
|
||||
import rs.rhema.phone.net.ClawResult
|
||||
import rs.rhema.phone.net.PasteSpan
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -438,6 +439,7 @@ private sealed interface TurnGroup {
|
||||
val id: Long,
|
||||
val text: String,
|
||||
val images: List<ChatController.SentImage>,
|
||||
val pastes: List<PasteSpan> = emptyList(),
|
||||
) : TurnGroup {
|
||||
override val key: String = "u$id"
|
||||
}
|
||||
@@ -451,7 +453,7 @@ private fun turnGroups(items: List<ChatController.Item>): List<TurnGroup> {
|
||||
val groups = mutableListOf<TurnGroup>()
|
||||
for (item in items) {
|
||||
when (item) {
|
||||
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images)
|
||||
is ChatController.UserMessage -> groups += TurnGroup.User(item.id, item.text, item.images, item.pastes)
|
||||
else -> {
|
||||
val last = groups.lastOrNull()
|
||||
if (last is TurnGroup.Agent) last.items += item else groups += TurnGroup.Agent(mutableListOf(item))
|
||||
@@ -501,10 +503,13 @@ private fun TurnGroupRow(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Embedded pastes render as chips, not payloads; the
|
||||
// text around them stays verbatim.
|
||||
// Chips render as chips, not payloads; the text
|
||||
// around them stays verbatim. The row's chip record
|
||||
// slices them out of the plain text; a row from
|
||||
// before the record rode the stream carries none
|
||||
// and still scans the mark form in the text.
|
||||
var chip = 0
|
||||
pasteParts(group.text).forEach { part ->
|
||||
messageParts(group.text, group.pastes).forEach { part ->
|
||||
when (part) {
|
||||
is PastePart.Text -> Text(part.text, style = MaterialTheme.typography.bodyLarge)
|
||||
is PastePart.Paste -> {
|
||||
@@ -740,20 +745,67 @@ private fun PasteChip(label: String) {
|
||||
)
|
||||
}
|
||||
|
||||
// --- embedded pastes --------------------------------------------------
|
||||
// The wire form a long paste travels in: MARK, payload, MARK — one
|
||||
// logical unit inside otherwise plain text (rhema-core's paste module
|
||||
// is the definition; these are its client-side shape). A mark with no
|
||||
// partner is literal text.
|
||||
// --- paste chips ------------------------------------------------------
|
||||
// A long paste rides as a chip the render stands in for its payload.
|
||||
// The record is the span list a user_message carries (the session
|
||||
// annotation's own shape); the marks in the text are the record's
|
||||
// legacy spelling, kept for rows that predate it — a mark with no
|
||||
// partner is literal text (rhema-core's paste module is the
|
||||
// definition; these are its client-side shape).
|
||||
|
||||
private const val PASTE_MARK = '\uFFFC'
|
||||
|
||||
/** One scanned piece of embedded-form text. */
|
||||
/** One piece of a rendered message: literal text, or a chip standing
|
||||
* for its payload. */
|
||||
private sealed interface PastePart {
|
||||
data class Text(val text: String) : PastePart
|
||||
data class Paste(val payload: String) : PastePart
|
||||
}
|
||||
|
||||
/** A message's parts. The chip record is the modern form — each span
|
||||
* names the payload's byte range in the plain text — and rows recorded
|
||||
* before it rode the stream carry none; those still scan the legacy
|
||||
* mark form in the text itself. */
|
||||
private fun messageParts(text: String, pastes: List<PasteSpan> = emptyList()): List<PastePart> =
|
||||
if (pastes.isEmpty()) pasteParts(text) else spanParts(text, pastes)
|
||||
|
||||
/** Splits a record-carrying message into its parts, left to right. The
|
||||
* spans' offsets are UTF-8 bytes, the plain form the fold measured —
|
||||
* every character boundary is mapped in one walk, and a span that
|
||||
* splits a character maps to none: the render skips it rather than cut
|
||||
* one in half. Malformed input never throws. */
|
||||
private fun spanParts(text: String, pastes: List<PasteSpan>): List<PastePart> {
|
||||
var bytes = 0
|
||||
var units = 0
|
||||
val at = mutableMapOf(0 to 0)
|
||||
var index = 0
|
||||
while (index < text.length) {
|
||||
val codePoint = text.codePointAt(index)
|
||||
val width = Character.charCount(codePoint)
|
||||
index += width
|
||||
units = index
|
||||
bytes += when {
|
||||
codePoint < 0x80 -> 1
|
||||
codePoint < 0x800 -> 2
|
||||
codePoint < 0x10000 -> 3
|
||||
else -> 4
|
||||
}
|
||||
at[bytes] = units
|
||||
}
|
||||
val parts = mutableListOf<PastePart>()
|
||||
var cut = 0
|
||||
for (span in pastes.sortedBy { it.start }) {
|
||||
val start = at[span.start]
|
||||
val end = at[span.end]
|
||||
if (start == null || end == null || start < cut || end < start) continue
|
||||
if (start > cut) parts += PastePart.Text(text.substring(cut, start))
|
||||
parts += PastePart.Paste(text.substring(start, end))
|
||||
cut = end
|
||||
}
|
||||
if (cut < text.length) parts += PastePart.Text(text.substring(cut))
|
||||
return parts
|
||||
}
|
||||
|
||||
/** Splits embedded-form text into its parts, left to right. A mark with
|
||||
* no partner is literal text; malformed input never throws. */
|
||||
private fun pasteParts(text: String): List<PastePart> {
|
||||
|
||||
@@ -26,29 +26,36 @@ mock = ["rhema-core/mock"]
|
||||
|
||||
[dependencies]
|
||||
# The shared toolkit: the resident agent assembles its agent from the
|
||||
# shell, the approval seam, paste expansion, and revive-on-resume
|
||||
rhema-agent-tools = "0.2.3"
|
||||
rhema-autonomous-agent = "0.2.3"
|
||||
rhema-coding-agent = "0.2.3"
|
||||
rhema-config = "0.2.3"
|
||||
rhema-core = "0.2.3"
|
||||
# shell, the approval seam, and revive-on-resume (rhema-bash), the
|
||||
# system-prompt renderer (rhema-prompt), and the driver that turns a
|
||||
# provider into a host-operating agent (rhema-host-agent)
|
||||
rhema-bash = "0.4.0"
|
||||
rhema-prompt = "0.4.0"
|
||||
rhema-host-agent = "0.4.0"
|
||||
rhema-autonomous-agent = "0.4.0"
|
||||
rhema-config = "0.4.0"
|
||||
rhema-core = "0.4.0"
|
||||
# The bounded request view over the claw sessions, on by default here
|
||||
rhema-transcript = "0.2.3"
|
||||
rhema-transcript = "0.4.0"
|
||||
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
|
||||
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
|
||||
# The accounts layer: identities hold the forge tokens the watches poll
|
||||
# with, and the identity tools manage them over chat
|
||||
rhema-identity = "0.2.3"
|
||||
rhema-rsd = "0.2.3"
|
||||
rhema-identity = "0.4.0"
|
||||
rhema-rsd = "0.4.0"
|
||||
# The sandbox seam: where `bash` runs, local process or a daemon speaking
|
||||
# the wire protocol over HTTP
|
||||
rhema-sandbox = "0.4.0"
|
||||
rhema-sandbox-http = "0.4.0"
|
||||
# The tool contract: the agent-token allowlist and version the auth
|
||||
# middleware enforces (rhema-tools spec). The arrow runs claw ->
|
||||
# contract only — never the reverse.
|
||||
rhema-claw-tools-contract = { path = "../../tools/contract" }
|
||||
# The resident tier's durable memory: its tools join the resolver chain
|
||||
rhema-memory = "0.2.3"
|
||||
rhema-memory = "0.4.0"
|
||||
# The shared ModelCard the backend registry's listings return
|
||||
rhema-provider = "0.2.3"
|
||||
rhema-provider-registry = "0.2.3"
|
||||
rhema-provider = "0.4.0"
|
||||
rhema-provider-registry = "0.4.0"
|
||||
# Args for the two-flag binary surface
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
serde = { workspace = true }
|
||||
@@ -59,6 +66,8 @@ thiserror = { workspace = true }
|
||||
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
|
||||
# concurrent handler runs share it. `net` is the HTTP listener.
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] }
|
||||
# The sandbox executor implements the shell seam
|
||||
async-trait = { workspace = true }
|
||||
# The chat surface: native routes plus SSE, and the OpenAI shim
|
||||
axum = { workspace = true }
|
||||
# Broadcast receivers as SSE bodies
|
||||
@@ -71,7 +80,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
|
||||
# Inbound chat images ride base64; the dispatch decodes them into the
|
||||
# attachment store
|
||||
base64 = "0.22"
|
||||
rhema-mcp = "0.2.3"
|
||||
rhema-mcp = "0.4.0"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -83,7 +92,7 @@ reqwest = { version = "0.12", features = ["json", "stream"] }
|
||||
bytes = "1"
|
||||
# The scripted provider for turn-level tests; mirrors rhema-code's mock
|
||||
# feature without a feature of our own — tests are the only consumer
|
||||
rhema-core = { version = "0.2.3", features = ["mock"] }
|
||||
rhema-core = { version = "0.4.0", features = ["mock"] }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -69,6 +69,10 @@ 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: http # local (default) or http
|
||||
url: https://box.example:7600 # the sandboxd base URL
|
||||
token: sandbox-secret # the daemon's shared secret, if it has one
|
||||
poll_interval_secs: 120
|
||||
max_turn_steps: 2048 # tool rounds one chat turn may run
|
||||
watches: # a seed: imported while the table is empty
|
||||
@@ -96,6 +100,14 @@ unattended for a long time, so a cap this deep is a runaway guard, not
|
||||
a work timer — a turn that hits it ends with a failed outcome and the
|
||||
conversation intact; a follow-up message keeps going.
|
||||
|
||||
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
|
||||
keeps the daemon's own processes. `kind: http` sends commands to a host
|
||||
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
|
||||
optional `token`. The settings screen writes the same choice to the
|
||||
settings table, and the next turn reads it; no restart is needed. On
|
||||
first use the claw copies the local workspace into the sandbox's
|
||||
`/workspace`. Later edits stay there; the claw does not copy them back.
|
||||
|
||||
The surface refuses to start on a non-loopback `listen` with no
|
||||
`token`: anything beyond loopback can reach the port, and the bearer
|
||||
token is what stands between it and the agent's tools. Set a token, or
|
||||
@@ -123,7 +135,7 @@ The native surface:
|
||||
```
|
||||
GET /healthz GET /v1/sessions
|
||||
POST /v1/sessions {"name"} — create an empty interactive session
|
||||
POST /v1/sessions/{key}/messages {"text": "..."} -> 202
|
||||
POST /v1/sessions/{key}/messages {"text": "...", "images"?, "pastes"?} -> 202
|
||||
GET /v1/sessions/{key}/events SSE turn events (see below); ?since=<seq> resumes a cursor
|
||||
GET /v1/sessions/{key}/history one page of older turns: ?before=<seq>&limit=<n>
|
||||
DELETE /v1/sessions/{key} drop a session and its turn history
|
||||
@@ -137,6 +149,8 @@ DELETE /v1/consents/{id} deny a pending ask
|
||||
GET /v1/attachments/{id} an attached file's bytes
|
||||
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
|
||||
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
|
||||
GET /v1/sandbox where the agent's bash runs
|
||||
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
|
||||
GET /v1/providers the backend instances + the active pair
|
||||
PUT /v1/providers/active {"provider","model"?} — switch, persisted
|
||||
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
|
||||
@@ -169,7 +183,10 @@ lets a UI badge setup state.
|
||||
|
||||
SSE frames are `id: <seq>` plus `data: {..}`: `user_message`,
|
||||
`thinking_delta`, `text_delta`, `tool_start`, `tool_result`,
|
||||
`turn_done`. Every streamed event is persisted as it streams, so both a
|
||||
`turn_done`. A `user_message` names its paste chips as the byte spans
|
||||
they stand for in its plain text (`paste::PasteSpan`, the session
|
||||
record's own shape) — a client renders from that record; rows recorded
|
||||
before spans arrived carry the legacy mark form in the text instead. Every streamed event is persisted as it streams, so both a
|
||||
reload and a daemon restart rebuild the transcript, and a session that
|
||||
runs for weeks keeps all of it.
|
||||
|
||||
@@ -244,7 +261,21 @@ 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. Acting with a stored account is `identity_exec`: it runs one shell
|
||||
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
|
||||
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
|
||||
|
||||
@@ -26,9 +26,9 @@ use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rhema_agent_tools::render_template;
|
||||
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
|
||||
use rhema_core::ToolSpec;
|
||||
use rhema_prompt::render_template;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The built-in system prompt, kept as data next to the code and read
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//! binary's startup, not here — the daemon library takes the built
|
||||
//! provider, so tests can inject a mock.
|
||||
|
||||
use std::num::NonZeroU32;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -22,10 +23,13 @@ use serde::{Deserialize, Serialize};
|
||||
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 60;
|
||||
|
||||
/// How many tool rounds one chat turn may run, when
|
||||
/// [`ClawConfig::max_turn_steps`] is unset — the coding driver's own
|
||||
/// budget shape and its default: deep enough that a cap is a runaway
|
||||
/// guard for an agent meant to work unattended, not a work timer.
|
||||
pub const DEFAULT_MAX_TURN_STEPS: u32 = 2048;
|
||||
/// [`ClawConfig::max_turn_steps`] is unset — the host agent driver's
|
||||
/// own budget shape and its default: deep enough that a cap is a
|
||||
/// runaway guard for an agent meant to work unattended, not a work
|
||||
/// timer. `NonZeroU32`, the driver's own spelling: a turn cannot have
|
||||
/// no step budget at all, and a config that names zero is refused at
|
||||
/// load instead of cutting every round dead.
|
||||
pub const DEFAULT_MAX_TURN_STEPS: NonZeroU32 = NonZeroU32::new(2048).unwrap();
|
||||
|
||||
/// Where the HTTP surface listens when [`ClawConfig::listen`] is unset:
|
||||
/// loopback only — the surface is for the machine's resident user.
|
||||
@@ -55,6 +59,9 @@ pub enum ConfigError {
|
||||
"agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
|
||||
)]
|
||||
SameAgentToken,
|
||||
/// The configured sandbox choice cannot run as written.
|
||||
#[error("sandbox: {0}")]
|
||||
Sandbox(String),
|
||||
/// The ingest credential is the same value as the human token or
|
||||
/// the agent token: boot refuses, because the ingest credential's
|
||||
/// safety is that it is write-only and the event door only — a
|
||||
@@ -127,7 +134,7 @@ pub struct ClawConfig {
|
||||
/// How many tool rounds one chat turn may run before it is cut off
|
||||
/// with a failed outcome, the conversation intact. A follow-up
|
||||
/// message keeps going. [`DEFAULT_MAX_TURN_STEPS`] when unset.
|
||||
pub max_turn_steps: u32,
|
||||
pub max_turn_steps: NonZeroU32,
|
||||
/// The handler's model backend: `google`, `llama-cpp`, `openrouter`,
|
||||
/// `anthropic`, `openai`, or `zai`; google when unset. Keys resolve
|
||||
/// through the stored rhema config's default profile, env vars
|
||||
@@ -171,6 +178,10 @@ pub struct ClawConfig {
|
||||
/// Unset closes the door to credentials; the human token can still
|
||||
/// ingest.
|
||||
pub ingest_token: Option<String>,
|
||||
/// Where the agent's `bash` runs: this host when unset, or a
|
||||
/// `rhema-sandboxd` over HTTP. The settings store owns the live
|
||||
/// choice; this seeds it at boot, before the first settings write.
|
||||
pub sandbox: Option<crate::sandbox::SandboxChoice>,
|
||||
}
|
||||
|
||||
impl ClawConfig {
|
||||
@@ -198,6 +209,7 @@ impl Default for ClawConfig {
|
||||
tools_bin: None,
|
||||
ingest_token: None,
|
||||
transcript: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -326,6 +338,12 @@ impl ClawConfig {
|
||||
{
|
||||
return Err(ConfigError::IngestTokenCollision);
|
||||
}
|
||||
if let Some(sandbox) = &self.sandbox {
|
||||
sandbox
|
||||
.clone()
|
||||
.normalized()
|
||||
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -422,10 +440,14 @@ model: claude-sonnet-4-5
|
||||
listen: 192.168.1.10:7800
|
||||
token: sekrit
|
||||
ingest_token: door-key
|
||||
sandbox:
|
||||
kind: http
|
||||
url: https://box.example:7600
|
||||
token: sandbox-secret
|
||||
";
|
||||
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
|
||||
assert_eq!(config.poll_interval_secs, 30);
|
||||
assert_eq!(config.max_turn_steps, 512);
|
||||
assert_eq!(config.max_turn_steps, NonZeroU32::new(512).unwrap());
|
||||
assert_eq!(config.provider.as_deref(), Some("anthropic"));
|
||||
assert_eq!(config.model.as_deref(), Some("claude-sonnet-4-5"));
|
||||
assert_eq!(config.listen.as_deref(), Some("192.168.1.10:7800"));
|
||||
@@ -438,6 +460,35 @@ ingest_token: door-key
|
||||
config.bootstrap_root.as_deref(),
|
||||
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap"))
|
||||
);
|
||||
let sandbox = config.sandbox.expect("the sandbox parses");
|
||||
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
|
||||
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
|
||||
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_http_sandbox_needs_a_url_at_boot() {
|
||||
let missing = ClawConfig {
|
||||
sandbox: Some(crate::sandbox::SandboxChoice {
|
||||
kind: crate::sandbox::SandboxKind::Http,
|
||||
url: None,
|
||||
token: None,
|
||||
}),
|
||||
..ClawConfig::default()
|
||||
};
|
||||
assert!(
|
||||
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
|
||||
"a remote sandbox without a URL is refused at boot"
|
||||
);
|
||||
let valid = ClawConfig {
|
||||
sandbox: Some(crate::sandbox::SandboxChoice {
|
||||
kind: crate::sandbox::SandboxKind::Http,
|
||||
url: Some("https://box.example:7600".to_owned()),
|
||||
token: None,
|
||||
}),
|
||||
..ClawConfig::default()
|
||||
};
|
||||
assert!(valid.validate().is_ok(), "a complete remote choice passes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -62,6 +62,9 @@ pub enum ClawError {
|
||||
/// The runtime settings table could not be opened or read.
|
||||
#[error(transparent)]
|
||||
Settings(#[from] crate::settings::SettingsError),
|
||||
/// The sandbox choice could not be loaded or is malformed.
|
||||
#[error(transparent)]
|
||||
Sandbox(#[from] crate::sandbox::SandboxError),
|
||||
/// The notification table could not be opened or read.
|
||||
#[error(transparent)]
|
||||
Notifications(#[from] crate::notifications::NotificationStoreError),
|
||||
@@ -225,6 +228,10 @@ impl Daemon {
|
||||
// The forge handler resolves its watches through the table at
|
||||
// dispatch time, so a watch added mid-run is answerable without a
|
||||
// restart.
|
||||
// The runtime settings table, opened before the handlers so the
|
||||
// sandbox choice and the provider write share one connection.
|
||||
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
|
||||
|
||||
// The client tools' connection, handed to the agent's shell as
|
||||
// environment: the URL the surface answers on, the scoped
|
||||
// agent token (the middleware keeps it to the contract's data
|
||||
@@ -252,6 +259,25 @@ impl Daemon {
|
||||
format!("{}:{inherited}", tools_bin.display()),
|
||||
);
|
||||
}
|
||||
// Where `bash` runs: the stored choice wins, the config seeds a
|
||||
// fresh store. The state is shared by every handler and the
|
||||
// surface, so a switch is live on the next turn.
|
||||
let sandbox = Arc::new(crate::sandbox::SandboxState::load(
|
||||
settings.clone(),
|
||||
config.sandbox.clone(),
|
||||
interactive_workspace.clone(),
|
||||
&tool_env,
|
||||
)?);
|
||||
let sandbox_choice = sandbox.choice();
|
||||
eprintln!(
|
||||
"[claw] sandbox: {}{}",
|
||||
sandbox_choice.kind.as_str(),
|
||||
sandbox_choice
|
||||
.url
|
||||
.as_deref()
|
||||
.map(|url| format!(" ({url})"))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let forge_handler = ClawHandler::new(
|
||||
backends.clone(),
|
||||
workspace_root,
|
||||
@@ -259,7 +285,8 @@ impl Daemon {
|
||||
accounts.clone(),
|
||||
config.transcript_enabled(),
|
||||
tool_env.clone(),
|
||||
);
|
||||
)
|
||||
.with_sandbox(sandbox.clone());
|
||||
// Three drivers over one store admit from the same table, so
|
||||
// each owns its slice of the key space: a forge pass must never
|
||||
// pick up a resident or job event (it would fail it, and
|
||||
@@ -292,7 +319,6 @@ impl Daemon {
|
||||
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
|
||||
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
|
||||
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
|
||||
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
|
||||
// The identity store shares the settings table and keeps its
|
||||
// images beside the database.
|
||||
let identity = Arc::new(crate::identity::IdentityStore::new(
|
||||
@@ -361,7 +387,8 @@ impl Daemon {
|
||||
extensions.clone(),
|
||||
config.transcript_enabled(),
|
||||
)
|
||||
.with_steer(steer.clone());
|
||||
.with_steer(steer.clone())
|
||||
.with_sandbox(sandbox.clone());
|
||||
let interactive_driver = Arc::new(
|
||||
Driver::new(
|
||||
interactive_dispatcher.clone(),
|
||||
@@ -381,7 +408,8 @@ impl Daemon {
|
||||
notifications.clone(),
|
||||
config.max_turn_steps,
|
||||
config.transcript_enabled(),
|
||||
);
|
||||
)
|
||||
.with_sandbox(sandbox.clone());
|
||||
let jobs_driver = Arc::new(
|
||||
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
|
||||
.with_holder("rhema-claw-jobs")
|
||||
@@ -410,6 +438,7 @@ impl Daemon {
|
||||
bridge,
|
||||
attachments,
|
||||
phone,
|
||||
sandbox,
|
||||
config.token.clone(),
|
||||
config.agent_token.clone(),
|
||||
config.ingest_token.clone(),
|
||||
|
||||
@@ -24,9 +24,10 @@ use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use rhema_autonomous_agent::{Source, SourceError, async_trait};
|
||||
use rhema_forge_integration::forge_key_fn;
|
||||
use rhema_forge_integration::triage::{self, Triage};
|
||||
use rhema_forge_integration::triage::{self, Role, Triage};
|
||||
use rhema_forge_integration::{
|
||||
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, Watcher, register_forge,
|
||||
Forge, GitHubForge, GitLabForge, GiteaForge, Notification, NotificationReason, RepoRef,
|
||||
Timestamp, Watcher, register_forge,
|
||||
};
|
||||
use rhema_identity::{IdentityStore, SecretKind};
|
||||
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
|
||||
@@ -315,7 +316,14 @@ impl Source for ForgeSource {
|
||||
}
|
||||
};
|
||||
let client = self.client_for(&record);
|
||||
let polled = self.watcher.poll(client.as_ref(), &repo).await;
|
||||
let since = self.cursor_for(&record)?;
|
||||
let polled = self
|
||||
.watcher
|
||||
.poll_since(client.as_ref(), &repo, Some(&since))
|
||||
.await;
|
||||
if polled.is_ok() {
|
||||
self.persist_cursor(&record, &repo)?;
|
||||
}
|
||||
// Health first, whatever the outcome: a watch that has been
|
||||
// failing since it was created must be able to say so.
|
||||
self.record_poll(
|
||||
@@ -366,6 +374,44 @@ impl Source for ForgeSource {
|
||||
}
|
||||
|
||||
impl ForgeSource {
|
||||
/// The cursor one repo watch polls from: the durable one when it has
|
||||
/// one, and otherwise a seed at *now*, 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.
|
||||
///
|
||||
/// A watch reports news, and a repository's history is not news.
|
||||
/// Replaying it meant one dispatch per old thread — and, from the
|
||||
/// handler, one comment posted on each. An unreadable cursor reads as
|
||||
/// absent: a corrupted row must not fire a backlog either.
|
||||
fn cursor_for(&self, record: &WatchRecord) -> Result<Timestamp, SourceError> {
|
||||
let stored = self
|
||||
.store
|
||||
.cursor(SCOPE_REPO, &record.forge, &record.repo)
|
||||
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
|
||||
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)
|
||||
.ok_or_else(|| SourceError::Backend("cannot spell this instant".to_owned()))?;
|
||||
self.store
|
||||
.set_cursor(SCOPE_REPO, &record.forge, &record.repo, now.raw())
|
||||
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
|
||||
Ok(now)
|
||||
}
|
||||
|
||||
/// Advances a watch's durable cursor to wherever the poll got to. The
|
||||
/// watcher's own map is per-process: a restart that lost it replayed
|
||||
/// the repository's history, the backlog [`Self::cursor_for`] exists to
|
||||
/// keep out.
|
||||
fn persist_cursor(&self, record: &WatchRecord, repo: &RepoRef) -> Result<(), SourceError> {
|
||||
let Some(cursor) = self.watcher.cursor(repo) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.store
|
||||
.set_cursor(SCOPE_REPO, &record.forge, &record.repo, cursor.raw())
|
||||
.map_err(|err| SourceError::Backend(format!("watch store: {err}")))
|
||||
}
|
||||
|
||||
/// Records one poll's outcome, and says something the first time a
|
||||
/// streak begins: a watch refused on every tick looks exactly like a
|
||||
/// quiet repository from the outside, and only the failing tick knows
|
||||
@@ -468,7 +514,7 @@ impl ForgeSource {
|
||||
let now = SystemClock.now_millis();
|
||||
let mut fed = 0;
|
||||
for notification in &page.notifications {
|
||||
match triage::classify(notification) {
|
||||
match claw_triage(notification) {
|
||||
Triage::Ignore => {}
|
||||
Triage::Surface => {
|
||||
if let Err(err) = self.notifications.push(
|
||||
@@ -530,6 +576,24 @@ impl ForgeSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`triage::classify`], plus the one reclassification a resident agent
|
||||
/// owes its own name: an @-mention of the daemon is an ask.
|
||||
///
|
||||
/// The shared vocabulary reads a mention as [`Triage::Surface`] — right
|
||||
/// for a consumer that only notifies its human, since a mention is not an
|
||||
/// assignment. This daemon is the party named: somebody typed `@handle` on
|
||||
/// a thread and is waiting for an answer, which is the same ask an
|
||||
/// assignment is. Left as a surface, a mention would be a phone buzz and
|
||||
/// nothing else — this loop never dispatches for a surface, so the turn
|
||||
/// that reads the thread would never run and the mention would go
|
||||
/// unanswered.
|
||||
fn claw_triage(notification: &Notification) -> Triage {
|
||||
match ¬ification.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.
|
||||
@@ -547,6 +611,83 @@ fn surface_body(notification: &Notification) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wiremock::matchers::{method, path};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
/// A watch installed on a repository full of history must not replay
|
||||
/// it: the first pass seeds its cursor to *now* and feeds nothing, and
|
||||
/// the poll that follows asks from that instant rather than from the
|
||||
/// beginning. Every replayed event used to be a dispatch, and every
|
||||
/// dispatch a comment posted on a thread nobody had just touched.
|
||||
#[tokio::test]
|
||||
async fn a_new_watch_starts_now_instead_of_replaying_history() {
|
||||
let server = MockServer::start().await;
|
||||
for endpoint in [
|
||||
"/api/v1/repos/acme/barn/issues",
|
||||
"/api/v1/repos/acme/barn/pulls",
|
||||
"/api/v1/repos/acme/barn/issues/comments",
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
|
||||
store
|
||||
.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);
|
||||
|
||||
assert_eq!(
|
||||
source.detect().await.expect("the pass runs"),
|
||||
0,
|
||||
"a watch's first pass feeds no history"
|
||||
);
|
||||
let cursor = store
|
||||
.cursor(SCOPE_REPO, "gitea", "acme/barn")
|
||||
.expect("cursor reads")
|
||||
.expect("the first pass seeded a cursor");
|
||||
assert!(
|
||||
Timestamp::parse(&cursor).is_some(),
|
||||
"the seed is spelled like a forge instant: {cursor}"
|
||||
);
|
||||
|
||||
// The poll asked from the seed: one request per feed, each
|
||||
// `since`-filtered where the feed takes one.
|
||||
let requests = server.received_requests().await.expect("recording is on");
|
||||
let issue_polls: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/api/v1/repos/acme/barn/issues")
|
||||
.collect();
|
||||
assert_eq!(issue_polls.len(), 1, "one issues poll");
|
||||
let since = issue_polls[0].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()));
|
||||
|
||||
// A second pass resumes from the same place, not from history.
|
||||
assert_eq!(source.detect().await.expect("the second pass runs"), 0);
|
||||
assert_eq!(
|
||||
store
|
||||
.cursor(SCOPE_REPO, "gitea", "acme/barn")
|
||||
.expect("cursor reads"),
|
||||
Some(cursor)
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.health(SCOPE_REPO, "gitea", "acme/barn")
|
||||
.expect("health reads")
|
||||
.map(|health| health.consecutive_failures),
|
||||
Some(0),
|
||||
"the watch polled cleanly"
|
||||
);
|
||||
}
|
||||
|
||||
/// The parts a test source polls through, all in memory.
|
||||
fn test_parts(
|
||||
@@ -862,4 +1003,53 @@ 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"),
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
//!
|
||||
//! Session continuity rides the dispatcher, not the filesystem: the
|
||||
//! agent's session JSON is stashed into `ctx.session.core.driver_state`
|
||||
//! before the run returns and restored with [`CodingAgent::from_session`]
|
||||
//! before the run returns and restored with [`HostAgent::from_session`]
|
||||
//! on the next dispatch of the same key, so a resumed thread keeps its
|
||||
//! conversation. Commit-before-execute rides it too: the run installs the
|
||||
//! context's commit hook, so the intent is in the store before the first
|
||||
@@ -25,9 +25,8 @@ use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
|
||||
use crate::watch_store::ClawStore;
|
||||
use rhema_agent_tools::AllowAll;
|
||||
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
|
||||
use rhema_coding_agent::{CodingAgent, CodingAgentConfig};
|
||||
use rhema_bash::{AllowAll, ShellTools};
|
||||
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
|
||||
use rhema_forge_integration::ForgeKind;
|
||||
use rhema_forge_integration::triage::Role;
|
||||
@@ -35,10 +34,13 @@ use rhema_forge_integration::{
|
||||
EventKind, Forge, ForgeError, ForgeEvent, Notification, RepoRef, Snapshot, ThreadState, decode,
|
||||
parse_key,
|
||||
};
|
||||
use rhema_host_agent::{HostAgent, HostAgentConfig};
|
||||
use rhema_identity::IdentityStore;
|
||||
use rhema_rsd::{InboxItem, Outcome, ResourceKey};
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use crate::backends::BackendRegistry;
|
||||
use crate::sandbox::SandboxState;
|
||||
|
||||
/// The handler's tool permissions, resolved deterministically before the
|
||||
/// agent's first step (spec §8) — never by the model, never mid-run. V1
|
||||
@@ -70,7 +72,10 @@ 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>,
|
||||
clients: Mutex<HashMap<String, Arc<dyn Forge>>>,
|
||||
/// Where commands run: this host when absent, a remote sandbox when
|
||||
/// the surface selected one. Read per dispatch.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
|
||||
}
|
||||
|
||||
impl ClawHandler {
|
||||
@@ -91,10 +96,18 @@ impl ClawHandler {
|
||||
watches,
|
||||
accounts,
|
||||
tool_env,
|
||||
sandbox: None,
|
||||
clients: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the deployment's sandbox choice: a forge turn's commands
|
||||
/// run where it says, seeded from the thread's host workspace.
|
||||
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
|
||||
self.sandbox = Some(sandbox);
|
||||
self
|
||||
}
|
||||
|
||||
/// The forge client a dispatch key answers to:
|
||||
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
|
||||
/// table at dispatch time — the table is the source of truth, not a
|
||||
@@ -120,6 +133,18 @@ 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
|
||||
@@ -192,7 +217,7 @@ impl ClawHandler {
|
||||
kind: ForgeKind,
|
||||
host: Option<&str>,
|
||||
credential: &WatchCredential,
|
||||
) -> Arc<dyn Forge> {
|
||||
) -> Arc<WatchClient> {
|
||||
// Everything that changes the client: the kind, its host, and the
|
||||
// credential — the login included, since one value sent two ways
|
||||
// is two credentials.
|
||||
@@ -206,7 +231,10 @@ impl ClawHandler {
|
||||
let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
clients
|
||||
.entry(cache_key)
|
||||
.or_insert_with(|| record_client(kind, host, credential))
|
||||
.or_insert_with(|| {
|
||||
let forge = record_client(kind, host, credential);
|
||||
Arc::new(WatchClient::new(forge, credential.login.clone()))
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
@@ -224,7 +252,22 @@ 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 forge = self.watch_forge_as(&ctx.key, delivery_account(&news))?;
|
||||
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 snapshot = forge
|
||||
.snapshot(&repo, thread_kind, number)
|
||||
@@ -252,7 +295,7 @@ impl ClawHandler {
|
||||
let prompt = build_prompt(&key, &snapshot, &news, workspace.as_path(), role);
|
||||
let mut sink = TurnSink;
|
||||
let output = agent
|
||||
.turn(prompt, &mut sink, Arc::new(AllowAll))
|
||||
.turn(prompt, &mut sink)
|
||||
.await
|
||||
.map_err(|err| format!("turn for {key} failed: {err}"))?;
|
||||
|
||||
@@ -299,35 +342,55 @@ impl ClawHandler {
|
||||
ctx: &SessionContext,
|
||||
workspace: &Path,
|
||||
key: &str,
|
||||
) -> Result<CodingAgent, String> {
|
||||
) -> Result<HostAgent, String> {
|
||||
let (provider, model) = self.backends.current();
|
||||
let config = self.agent_config(&model, workspace);
|
||||
let config = self.agent_config(provider, &model, workspace);
|
||||
let agent = match &ctx.session.core.driver_state {
|
||||
// A never-dispatched key carries no stash: start clean.
|
||||
serde_json::Value::Null => CodingAgent::new(provider, config),
|
||||
serde_json::Value::Null => HostAgent::new(config),
|
||||
stashed => {
|
||||
let session: Session = serde_json::from_value(stashed.clone())
|
||||
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
|
||||
CodingAgent::from_session(provider, config, session)
|
||||
HostAgent::from_session(config, session)
|
||||
}
|
||||
};
|
||||
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
|
||||
}
|
||||
|
||||
/// The config one dispatch's agent runs on: the default coding
|
||||
/// agent's, with the bounded request view when the config has it on.
|
||||
/// agent's, with the bounded request view when the config has it on
|
||||
/// and a remote shell when the sandbox choice says so.
|
||||
/// A forge thread answers for as long as the thread lives; without
|
||||
/// the view its history would ride whole on every step.
|
||||
fn agent_config(&self, model: &str, workspace: &Path) -> CodingAgentConfig {
|
||||
let mut config = CodingAgentConfig::new(model, workspace);
|
||||
fn agent_config(
|
||||
&self,
|
||||
provider: Arc<dyn rhema_core::ModelProvider>,
|
||||
model: &str,
|
||||
workspace: &Path,
|
||||
) -> HostAgentConfig {
|
||||
let display = match &self.sandbox {
|
||||
Some(sandbox) => sandbox.workspace_for(workspace),
|
||||
None => workspace.to_path_buf(),
|
||||
};
|
||||
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
|
||||
// Write the resolved value, not an override: the coding agent's
|
||||
// own default is on now, and the config's `false` must win.
|
||||
config.transcript = self
|
||||
.transcript
|
||||
.then(rhema_transcript::TranscriptSettings::default);
|
||||
config.shell_env = self.tool_env.clone();
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
match &self.sandbox {
|
||||
Some(sandbox) if sandbox.is_remote() => {
|
||||
config.tools = Some(Arc::new(ShellTools::with_executor(
|
||||
display,
|
||||
sandbox.executor(workspace.to_path_buf()),
|
||||
)));
|
||||
}
|
||||
_ => {
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
@@ -343,6 +406,45 @@ 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 {
|
||||
@@ -440,6 +542,60 @@ 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:
|
||||
@@ -712,6 +868,89 @@ 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(
|
||||
@@ -861,6 +1100,7 @@ mod tests {
|
||||
Content::Text("on it".into()),
|
||||
Content::Text(" — closing.".into()),
|
||||
],
|
||||
annotations: Default::default(),
|
||||
};
|
||||
assert_eq!(final_text(&message).as_deref(), Some("on it — closing."));
|
||||
let tool_only = Message {
|
||||
@@ -871,6 +1111,7 @@ mod tests {
|
||||
args: serde_json::json!({}),
|
||||
provider_data: serde_json::Value::Null,
|
||||
})],
|
||||
annotations: Default::default(),
|
||||
};
|
||||
assert_eq!(final_text(&tool_only), None, "no text, no reply");
|
||||
}
|
||||
@@ -1014,6 +1255,7 @@ mod tests {
|
||||
.expect("constructs"),
|
||||
);
|
||||
let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new());
|
||||
let provider = registry.current().0;
|
||||
let on = ClawHandler::new(
|
||||
registry.clone(),
|
||||
"/tmp/w",
|
||||
@@ -1031,12 +1273,12 @@ mod tests {
|
||||
std::collections::BTreeMap::new(),
|
||||
);
|
||||
assert!(
|
||||
on.agent_config("m", Path::new("/tmp/w"))
|
||||
on.agent_config(provider.clone(), "m", Path::new("/tmp/w"))
|
||||
.transcript
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
off.agent_config("m", Path::new("/tmp/w"))
|
||||
off.agent_config(provider, "m", Path::new("/tmp/w"))
|
||||
.transcript
|
||||
.is_none()
|
||||
);
|
||||
|
||||
@@ -123,6 +123,9 @@ pub struct ClawState {
|
||||
/// The phone tables: the command queue the device polls and the
|
||||
/// reported state the ingest door feeds.
|
||||
phone: Arc<crate::phone::PhoneStore>,
|
||||
/// Where the agent's `bash` runs: the live choice `/v1/sandbox`
|
||||
/// edits, shared with every handler.
|
||||
sandbox: Arc<crate::sandbox::SandboxState>,
|
||||
token: Option<String>,
|
||||
/// The scoped agent token the client tools hold: a second bearer
|
||||
/// answering only the contract's data routes (see
|
||||
@@ -146,7 +149,7 @@ impl ClawState {
|
||||
/// `agent_token`.
|
||||
#[expect(
|
||||
clippy::too_many_arguments,
|
||||
reason = "eighteen parts, each load-bearing"
|
||||
reason = "twenty-one parts, each load-bearing"
|
||||
)]
|
||||
pub fn new(
|
||||
dispatcher: Arc<Dispatcher>,
|
||||
@@ -167,6 +170,7 @@ impl ClawState {
|
||||
bridge: Arc<crate::consents::WaitBridge>,
|
||||
attachments: Arc<crate::attachments::AttachmentStore>,
|
||||
phone: Arc<crate::phone::PhoneStore>,
|
||||
sandbox: Arc<crate::sandbox::SandboxState>,
|
||||
token: Option<String>,
|
||||
agent_token: Option<String>,
|
||||
ingest_token: Option<String>,
|
||||
@@ -190,6 +194,7 @@ impl ClawState {
|
||||
bridge,
|
||||
attachments,
|
||||
phone,
|
||||
sandbox,
|
||||
token,
|
||||
agent_token,
|
||||
ingest_token,
|
||||
@@ -289,6 +294,11 @@ impl ClawState {
|
||||
pub fn watches(&self) -> &ClawStore {
|
||||
&self.watches
|
||||
}
|
||||
|
||||
/// Where the agent's `bash` runs.
|
||||
pub fn sandbox(&self) -> &crate::sandbox::SandboxState {
|
||||
&self.sandbox
|
||||
}
|
||||
}
|
||||
|
||||
/// The app router: `/healthz` open, `/v1` behind the bearer check when
|
||||
@@ -343,6 +353,7 @@ pub fn router(state: ClawState) -> Router {
|
||||
)
|
||||
.route("/providers/{id}", delete(providers_remove))
|
||||
.route("/providers/{id}/models", get(providers_models))
|
||||
.route("/sandbox", get(sandbox_get).put(sandbox_put))
|
||||
.route(
|
||||
"/chat/completions",
|
||||
post(crate::openai::chat_completions)
|
||||
@@ -652,12 +663,20 @@ pub const MAX_INBOUND_IMAGES: usize = 8;
|
||||
pub const MAX_MESSAGE_BODY_BYTES: usize =
|
||||
MAX_INBOUND_IMAGE_BYTES * 4 / 3 * MAX_INBOUND_IMAGES + 1024 * 1024;
|
||||
|
||||
/// `{"text": "..."}` — one chat message, plus the images it carries.
|
||||
/// A body without `images` is the old shape, unchanged.
|
||||
/// `{"text": "..."}` — one chat message, plus the images and the chip
|
||||
/// payloads it carries. A body without `images` or `pastes` is the old
|
||||
/// shape, unchanged.
|
||||
#[derive(Deserialize)]
|
||||
pub struct MessageBody {
|
||||
/// The message text.
|
||||
/// The message text, plain: each paste payload appended to it in
|
||||
/// the fold, its chip noted as a span in the recorded event — no
|
||||
/// mark form on the wire.
|
||||
pub text: String,
|
||||
/// The message's staged chips, payloads in order. A sender that
|
||||
/// mints the legacy mark form sends none; the fold rewrites that
|
||||
/// form too.
|
||||
#[serde(default)]
|
||||
pub pastes: Vec<String>,
|
||||
/// The message's inline images, each the full MIME type plus bare
|
||||
/// base64. The route checks the budget, then the dispatch copies
|
||||
/// the bytes into the attachment store — the stream carries ids,
|
||||
@@ -729,6 +748,7 @@ async fn messages(
|
||||
if let Err(err) = state.dispatcher.ingest(crate::interactive::user_event(
|
||||
key.as_str(),
|
||||
&body.text,
|
||||
&body.pastes,
|
||||
&body.images,
|
||||
)) {
|
||||
return (
|
||||
@@ -1982,6 +2002,63 @@ pub(crate) async fn drain_owned(
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /v1/sandbox`: where the agent's `bash` runs. The token never
|
||||
/// rides the wire: `token_set` says whether one is stored.
|
||||
async fn sandbox_get(State(state): State<ClawState>) -> Json<Value> {
|
||||
Json(sandbox_json(&state))
|
||||
}
|
||||
|
||||
/// The sandbox state as the wire sees it: the shared body of the read
|
||||
/// and of the write that answers with the new choice.
|
||||
fn sandbox_json(state: &ClawState) -> Value {
|
||||
let choice = state.sandbox().choice();
|
||||
json!({
|
||||
"kind": choice.kind.as_str(),
|
||||
"url": choice.url,
|
||||
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
|
||||
"workspace": state.sandbox().workspace().display().to_string(),
|
||||
"local_workspace": state.sandbox().local_workspace().display().to_string(),
|
||||
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
|
||||
})
|
||||
}
|
||||
|
||||
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
|
||||
/// persist the choice. `token` is write-only; `clear_token` drops the
|
||||
/// stored one. The choice applies on the next turn, no restart.
|
||||
async fn sandbox_put(
|
||||
State(state): State<ClawState>,
|
||||
Json(body): Json<Value>,
|
||||
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
|
||||
let Some(kind) = body["kind"].as_str() else {
|
||||
return Err(bad_request("body must carry a sandbox kind"));
|
||||
};
|
||||
let kind = crate::sandbox::SandboxKind::parse(kind)
|
||||
.ok_or_else(|| bad_request(format!("unknown sandbox kind {kind:?}")))?;
|
||||
let current = state.sandbox().choice();
|
||||
let clear_token = body["clear_token"].as_bool().unwrap_or(false);
|
||||
let token = if clear_token {
|
||||
None
|
||||
} else {
|
||||
body["token"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| current.token.clone())
|
||||
};
|
||||
let choice = crate::sandbox::SandboxChoice {
|
||||
kind,
|
||||
url: body["url"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| current.url.clone()),
|
||||
token,
|
||||
};
|
||||
state.sandbox().set(choice).map_err(|err| match err {
|
||||
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
|
||||
crate::sandbox::SandboxError::Store(_) => internal_error(err),
|
||||
})?;
|
||||
Ok(Json(sandbox_json(&state)))
|
||||
}
|
||||
|
||||
/// `GET /v1/providers`: every constructible backend and the active pair.
|
||||
/// The active pair is runtime state — the config file seeded it, the
|
||||
/// settings store owns it now. Each provider is one instance, named by
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use rhema_core::paste::PasteSpan;
|
||||
use rhema_rsd::ResourceKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::broadcast;
|
||||
@@ -74,13 +75,23 @@ pub enum TurnEvent {
|
||||
/// shows its own messages as it sends them, and skips the live
|
||||
/// echo.
|
||||
UserMessage {
|
||||
/// The input text, verbatim.
|
||||
/// The input text in the plain form the model read — each
|
||||
/// paste's payload in place, no marks.
|
||||
text: String,
|
||||
/// The batch's images, in arrival order, as the attachment
|
||||
/// store holds them. `default` because rows recorded before
|
||||
/// images rode the transcript carry no field.
|
||||
#[serde(default)]
|
||||
images: Vec<UserImage>,
|
||||
/// The paste chips the input carried, the same span record the
|
||||
/// session's `rhema-code` annotation holds: the byte range
|
||||
/// each chip stands for in `text`, plus its line count for the
|
||||
/// label. `default` because rows recorded before chips rode
|
||||
/// as spans carry the marks in the text instead — a client
|
||||
/// that finds none scans for them; skipped when empty, so
|
||||
/// rows without chips replay byte-for-byte as they landed.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pastes: Vec<PasteSpan>,
|
||||
},
|
||||
/// A piece of the model's reasoning trace, in stream order.
|
||||
ThinkingDelta {
|
||||
@@ -565,10 +576,27 @@ mod tests {
|
||||
serde_json::to_string(&TurnEvent::UserMessage {
|
||||
text: "hi".into(),
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new(),
|
||||
})
|
||||
.unwrap(),
|
||||
r#"{"type":"user_message","text":"hi","images":[]}"#
|
||||
);
|
||||
// The chip record rides only when there is one: the span
|
||||
// shape is the session annotation's own, byte offsets over
|
||||
// the plain text.
|
||||
assert_eq!(
|
||||
serde_json::to_string(&TurnEvent::UserMessage {
|
||||
text: "hi".into(),
|
||||
images: Vec::new(),
|
||||
pastes: vec![PasteSpan {
|
||||
start: 3,
|
||||
end: 9,
|
||||
lines: 4,
|
||||
}],
|
||||
})
|
||||
.unwrap(),
|
||||
r#"{"type":"user_message","text":"hi","images":[],"pastes":[{"start":3,"end":9,"lines":4}]}"#
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&TurnEvent::ToolResult {
|
||||
name: "bash".into(),
|
||||
@@ -600,7 +628,8 @@ mod tests {
|
||||
event,
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -614,7 +643,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
TurnEvent::UserMessage {
|
||||
text: "x".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
.kind(),
|
||||
"user_message"
|
||||
@@ -659,6 +689,7 @@ mod tests {
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new(),
|
||||
},
|
||||
);
|
||||
hub.emit(&key, text("hi"));
|
||||
@@ -669,7 +700,8 @@ mod tests {
|
||||
vec![
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
},
|
||||
text("hi"),
|
||||
],
|
||||
@@ -795,6 +827,7 @@ mod tests {
|
||||
TurnEvent::UserMessage {
|
||||
text: "earlier".into(),
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new(),
|
||||
},
|
||||
);
|
||||
let (history, mut receiver) = hub.subscribe_with_history(&key);
|
||||
@@ -896,6 +929,7 @@ mod tests {
|
||||
TurnEvent::UserMessage {
|
||||
text: format!("q{turn}"),
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new(),
|
||||
},
|
||||
);
|
||||
hub.emit(&key, text(&format!("a{turn}")));
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
//! v1's starting point — and the resolver chain are assembled before
|
||||
//! the first model call; the model never decides its own permissions.
|
||||
//! The chain is the core toolsets (the shell over the interactive
|
||||
//! workspace, memory, `bootstrap_save`) plus every
|
||||
//! workspace, or over the sandbox root when one is selected; memory,
|
||||
//! `bootstrap_save`) plus every
|
||||
//! [`crate::extension::ClawExtension`]'s tools in the standard set's
|
||||
//! order. The system prompt is rendered per dispatch from the
|
||||
//! bootstrap template over the live SOUL/USER files.
|
||||
@@ -63,16 +64,18 @@
|
||||
//! rhema-code's UI draws for a steered turn.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::num::NonZeroU32;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rhema_agent_tools::{AllowAll, ExpandPastes, ShellTools, revive_dangling_calls};
|
||||
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait};
|
||||
use rhema_bash::{AllowAll, ShellTools};
|
||||
use rhema_core::{
|
||||
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
|
||||
ModelProvider, Role, Session, ToolContext, ToolResolver, close_orphaned_calls, run_turn,
|
||||
ModelProvider, Role, Session, ToolContext, ToolResolver, close_orphaned_calls,
|
||||
revive_dangling_calls, run_turn,
|
||||
};
|
||||
use rhema_memory::{MemoryResolver, MemoryStore, Scope};
|
||||
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
|
||||
@@ -82,6 +85,7 @@ use crate::backends::BackendRegistry;
|
||||
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
|
||||
use crate::hub::{EventHub, TurnEvent, UserImage};
|
||||
use crate::notifications::NotificationStore;
|
||||
use crate::sandbox::SandboxState;
|
||||
use crate::steer::{SteerGuard, SteerRegistry};
|
||||
|
||||
/// The key prefixes of the resident context (see the module docs):
|
||||
@@ -162,10 +166,10 @@ pub struct WireImage {
|
||||
|
||||
/// The event one chat message becomes. The id is unique per message (a
|
||||
/// wall-clock millisecond plus a process counter), so a redelivery
|
||||
/// never dedups a different message away. The payload carries the
|
||||
/// message's images when it has any, and no `images` key when it has
|
||||
/// none — old payloads stay byte-identical.
|
||||
pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
|
||||
/// never dedups a different message away. The chips' payloads ride
|
||||
/// beside the text, and the images with them, each only when the
|
||||
/// message staged any — payloads without chips stay byte-identical.
|
||||
pub fn user_event(key: &str, text: &str, pastes: &[String], images: &[WireImage]) -> Event {
|
||||
static MESSAGE_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
@@ -177,10 +181,18 @@ pub fn user_event(key: &str, text: &str, images: &[WireImage]) -> Event {
|
||||
MESSAGE_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
),
|
||||
source: SOURCE.to_owned(),
|
||||
payload: if images.is_empty() {
|
||||
json!({ "key": key, "text": text })
|
||||
} else {
|
||||
json!({ "key": key, "text": text, "images": images })
|
||||
// The chips' payloads ride only when the message staged any,
|
||||
// and images only when it carried any: the old two-field shape
|
||||
// rides byte-for-byte otherwise.
|
||||
payload: {
|
||||
let mut payload = json!({ "key": key, "text": text });
|
||||
if !pastes.is_empty() {
|
||||
payload["pastes"] = json!(pastes);
|
||||
}
|
||||
if !images.is_empty() {
|
||||
payload["images"] = json!(images);
|
||||
}
|
||||
payload
|
||||
},
|
||||
received_at: now.as_millis() as u64,
|
||||
}
|
||||
@@ -232,7 +244,7 @@ pub struct InteractiveHandler {
|
||||
/// How many tool rounds one turn may run before it is cut off — the
|
||||
/// config's runaway guard for an agent meant to work unattended; a
|
||||
/// follow-up message keeps going.
|
||||
max_turn_steps: u32,
|
||||
max_turn_steps: NonZeroU32,
|
||||
/// The extension set the tool half of the chain is cut from, per
|
||||
/// dispatch, in the standard set's order — the same set whose
|
||||
/// sources the daemon's tick drives and whose boot pass runs first.
|
||||
@@ -241,10 +253,14 @@ pub struct InteractiveHandler {
|
||||
/// decorator refreshes it per request, `zoom` reads it, and it
|
||||
/// lives here — the agent rebuilds per dispatch, the log must not.
|
||||
transcript_mirror: Option<Arc<std::sync::Mutex<rhema_transcript::Transcript>>>,
|
||||
/// The wired [`vision`](rhema_agent_tools::vision) section for the
|
||||
/// The wired [`vision`](rhema_bash::vision) section for the
|
||||
/// prompt, when provisioning succeeded — the same wiring whose env
|
||||
/// map lights the shell's inbox up.
|
||||
vision: Option<String>,
|
||||
/// Where commands run: this host when absent, a remote sandbox
|
||||
/// when the surface selected one. Read per dispatch, so a switch
|
||||
/// takes effect on the next turn.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
}
|
||||
|
||||
impl InteractiveHandler {
|
||||
@@ -265,7 +281,7 @@ impl InteractiveHandler {
|
||||
hub: Arc<EventHub>,
|
||||
notifications: Arc<NotificationStore>,
|
||||
attachments: Arc<crate::attachments::AttachmentStore>,
|
||||
max_turn_steps: u32,
|
||||
max_turn_steps: NonZeroU32,
|
||||
extensions: Arc<crate::extension::Extensions>,
|
||||
transcript: bool,
|
||||
) -> Self {
|
||||
@@ -274,7 +290,7 @@ impl InteractiveHandler {
|
||||
// chat's commands, and its staged images attach to their
|
||||
// results. Local shells only — the interactive handler's
|
||||
// executor is this host's by construction.
|
||||
let vision = rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV"));
|
||||
let vision = rhema_bash::vision::wire(std::env::var_os("BASH_ENV"));
|
||||
let tools = Arc::new(match vision {
|
||||
Some(wiring) => ShellTools::with_env(&workspace, &wiring.shell_env),
|
||||
None => ShellTools::new(&workspace),
|
||||
@@ -301,9 +317,17 @@ impl InteractiveHandler {
|
||||
)))
|
||||
}),
|
||||
vision: vision.map(|wiring| wiring.section.to_owned()),
|
||||
sandbox: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the deployment's sandbox choice: commands run where it
|
||||
/// says, and a remote sandbox replaces the host shell for `bash`.
|
||||
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
|
||||
self.sandbox = Some(sandbox);
|
||||
self
|
||||
}
|
||||
|
||||
/// The agent for one dispatch: rebuilt per run over the restored
|
||||
/// session (the engine's own step counter is per-agent; the
|
||||
/// conversation lives in the session, not the agent). The system
|
||||
@@ -314,12 +338,7 @@ impl InteractiveHandler {
|
||||
/// request advertises.
|
||||
fn agent(&self, key: &ResourceKey) -> Result<Agent, String> {
|
||||
let (provider, model) = self.backends.current();
|
||||
// Chat input may carry embedded pastes — the compact chip form
|
||||
// the UIs mint and the session keeps — so the provider wraps in
|
||||
// the same expansion the coding driver wraps its own with: the
|
||||
// model sees plain text, the transcript keeps the chips.
|
||||
let provider: Arc<dyn ModelProvider> = Arc::new(ExpandPastes::new(provider));
|
||||
// The view rides outside the expansion: stubs, whole messages,
|
||||
// The view rides outside the engine: stubs, whole messages,
|
||||
// and zoom output all show the text the model would have seen.
|
||||
let provider: Arc<dyn ModelProvider> = match &self.transcript_mirror {
|
||||
Some(mirror) => Arc::new(rhema_transcript::TranscriptView::new(
|
||||
@@ -329,13 +348,23 @@ impl InteractiveHandler {
|
||||
None => provider,
|
||||
};
|
||||
let resolver = self.resolver(key);
|
||||
let workspace = self.workspace();
|
||||
let vision = if self
|
||||
.sandbox
|
||||
.as_ref()
|
||||
.is_some_and(|sandbox| sandbox.is_remote())
|
||||
{
|
||||
None
|
||||
} else {
|
||||
self.vision.as_deref()
|
||||
};
|
||||
let system = render_system(
|
||||
DEFAULT_SYSTEM_MD,
|
||||
key.as_str(),
|
||||
&self.workspace,
|
||||
&workspace,
|
||||
&self.bootstrap,
|
||||
&resolver.specs(),
|
||||
self.vision.as_deref(),
|
||||
vision,
|
||||
)
|
||||
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
|
||||
Agent::builder()
|
||||
@@ -356,6 +385,15 @@ impl InteractiveHandler {
|
||||
self
|
||||
}
|
||||
|
||||
/// The workspace the prompt names: the host path locally, the
|
||||
/// sandbox root when commands run elsewhere.
|
||||
fn workspace(&self) -> PathBuf {
|
||||
match &self.sandbox {
|
||||
Some(sandbox) => sandbox.workspace_for(&self.workspace),
|
||||
None => self.workspace.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolver chain one dispatch runs under: the core toolsets —
|
||||
/// the shell over the interactive workspace, memory,
|
||||
/// `bootstrap_save` — then every extension's tools in the standard
|
||||
@@ -364,8 +402,18 @@ impl InteractiveHandler {
|
||||
/// their asks and cards to the session that asked, and the handler
|
||||
/// serves every session.
|
||||
fn resolver(&self, key: &ResourceKey) -> Arc<ResolverChain> {
|
||||
let shell: Arc<dyn rhema_core::ToolResolver> = match &self.sandbox {
|
||||
Some(sandbox) if sandbox.is_remote() => {
|
||||
let workspace = sandbox.workspace_for(&self.workspace);
|
||||
let tools =
|
||||
ShellTools::with_executor(workspace, sandbox.executor(self.workspace.clone()));
|
||||
tools.install_approval(Arc::new(AllowAll));
|
||||
Arc::new(tools)
|
||||
}
|
||||
_ => self.tools.clone(),
|
||||
};
|
||||
let mut resolvers: Vec<Arc<dyn rhema_core::ToolResolver>> = vec![
|
||||
self.tools.clone(),
|
||||
shell,
|
||||
Arc::new(MemoryResolver::new(
|
||||
self.memory.clone(),
|
||||
Scope::Workspace(self.workspace.clone()),
|
||||
@@ -401,7 +449,9 @@ impl InteractiveHandler {
|
||||
.await
|
||||
.map_err(|err| format!("inbox poll for {key} failed: {err}"))?;
|
||||
// Texts fold in arrival order, and so do the images, across
|
||||
// the whole batch whichever events carried them.
|
||||
// the whole batch whichever events carried them — each text
|
||||
// with its chips already composed in, their spans measured
|
||||
// over it.
|
||||
let mut texts = Vec::new();
|
||||
let mut images = Vec::new();
|
||||
for item in &items {
|
||||
@@ -411,7 +461,35 @@ impl InteractiveHandler {
|
||||
.or_else(|| payload.get("prompt"))
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
texts.push(text);
|
||||
// The fold owns the chip record. A legacy sender's
|
||||
// marks ride the text and migrate here, per message;
|
||||
// a payload chip appends in order right after —
|
||||
// plain either way before the join, its span
|
||||
// measured where it lands.
|
||||
let mut message = [Message::text(Role::User, text.to_owned())];
|
||||
rhema_core::paste::migrate(&mut message);
|
||||
let mut spans = rhema_core::paste::spans(&message[0]);
|
||||
let mut composed = match &message[0].content[0] {
|
||||
Content::Text(text) => text.clone(),
|
||||
_ => unreachable!("the message was built with one text block"),
|
||||
};
|
||||
for paste in payload
|
||||
.get("pastes")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(rhema_core::paste::normalize)
|
||||
{
|
||||
let span = rhema_core::paste::PasteSpan {
|
||||
start: composed.len(),
|
||||
end: composed.len() + paste.len(),
|
||||
lines: paste.lines().count(),
|
||||
};
|
||||
composed.push_str(&paste);
|
||||
spans.push(span);
|
||||
}
|
||||
texts.push((composed, spans));
|
||||
}
|
||||
if let Some(carried) = payload.get("images").and_then(Value::as_array) {
|
||||
images.extend(
|
||||
@@ -421,7 +499,22 @@ impl InteractiveHandler {
|
||||
);
|
||||
}
|
||||
}
|
||||
let input = texts.join("\n\n");
|
||||
let mut input = String::new();
|
||||
let mut pastes = Vec::new();
|
||||
let mut first = true;
|
||||
for (text, spans) in texts {
|
||||
if !first {
|
||||
input.push_str("\n\n");
|
||||
}
|
||||
let base = input.len();
|
||||
input.push_str(&text);
|
||||
pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan {
|
||||
start: span.start + base,
|
||||
end: span.end + base,
|
||||
lines: span.lines,
|
||||
}));
|
||||
first = false;
|
||||
}
|
||||
if input.trim().is_empty() {
|
||||
// Round one's emptiness is the dispatch bug it always was:
|
||||
// the lease exists because something waited. A steered
|
||||
@@ -472,13 +565,17 @@ impl InteractiveHandler {
|
||||
}
|
||||
// The transcript's question, recorded before anything else can
|
||||
// stream: a replay shows what was asked, not only what was
|
||||
// answered. Raw input — the notification-contract framing below
|
||||
// is the model's business, not the viewer's.
|
||||
// answered. The fold composed the record — plain text, the
|
||||
// chip spans beside it — and the turn runs this exact input;
|
||||
// the notification-contract framing below is the model's
|
||||
// business, not the viewer's.
|
||||
let recorded_len = input.len();
|
||||
self.hub.emit(
|
||||
&ctx.key,
|
||||
TurnEvent::UserMessage {
|
||||
text: input.clone(),
|
||||
images: transcript_images,
|
||||
pastes: pastes.clone(),
|
||||
},
|
||||
);
|
||||
// A non-chat resident key has no subscriber to read the reply:
|
||||
@@ -532,10 +629,29 @@ impl InteractiveHandler {
|
||||
// future at its current await — a streaming request, or a
|
||||
// running shell command, whose child dies with the drop. The
|
||||
// next round revives whatever committed before the drop.
|
||||
// The input rides in the plain form the fold recorded — the
|
||||
// payloads sit in the text and the model never sees a mark —
|
||||
// with the span note riding the message, so the checkpoint
|
||||
// (and a session resumed from it) keeps the chips beside the
|
||||
// plain text. The framings above live in the model's copy:
|
||||
// their bytes are known exactly, and each span shifts by them,
|
||||
// still pointing into the text it annotates.
|
||||
let framed_len = input.len();
|
||||
let pastes = pastes
|
||||
.iter()
|
||||
.map(|span| rhema_core::paste::PasteSpan {
|
||||
start: span.start + framed_len - recorded_len,
|
||||
end: span.end + framed_len - recorded_len,
|
||||
lines: span.lines,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut question = [Message::text_with_images(Role::User, input, core_images)];
|
||||
rhema_core::paste::annotate(&mut question[0], &pastes);
|
||||
let [turn_input] = question;
|
||||
let mut turn = Box::pin(run_turn(
|
||||
&mut agent,
|
||||
&mut session,
|
||||
Message::text_with_images(Role::User, input, core_images),
|
||||
turn_input,
|
||||
&mut sink,
|
||||
&tools,
|
||||
self.max_turn_steps,
|
||||
@@ -679,8 +795,16 @@ enum Round {
|
||||
fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
|
||||
match stashed {
|
||||
Value::Null => Ok(Session::default()),
|
||||
stashed => serde_json::from_value(stashed.clone())
|
||||
.map_err(|err| format!("stashed session for {key} does not parse: {err}")),
|
||||
stashed => {
|
||||
let mut session: Session = serde_json::from_value(stashed.clone())
|
||||
.map_err(|err| format!("stashed session for {key} does not parse: {err}"))?;
|
||||
// A session stashed before paste spans existed carries the
|
||||
// embedded form in its prompts; the provider must never see
|
||||
// a mark. One rewrite on the way in, chips survive as the
|
||||
// span note — the same pass the driver's from_session runs.
|
||||
rhema_core::paste::migrate(&mut session.history);
|
||||
Ok(session)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -794,6 +918,10 @@ impl EventSink for HubSink {
|
||||
| ModelEvent::Usage(_)
|
||||
| ModelEvent::RetryWait { .. }
|
||||
| ModelEvent::StepEnd { .. } => return,
|
||||
// The engine's event enum is non-exhaustive: a future
|
||||
// event arrives here, dropped like the rest of the engine's
|
||||
// own bookkeeping until a turn-event shape exists for it.
|
||||
_ => return,
|
||||
};
|
||||
self.hub.emit(&self.key, turn);
|
||||
}
|
||||
@@ -1056,12 +1184,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The paste contract across the provider seam: a chat input that
|
||||
/// carries an embedded paste (the compact form the UIs mint) is
|
||||
/// expanded before the request leaves, while the transcript the hub
|
||||
/// streams keeps the compact form.
|
||||
#[tokio::test]
|
||||
async fn an_embedded_paste_expands_for_the_model_and_not_for_the_transcript() {
|
||||
/// The environment a paste test drives: the recording provider, the
|
||||
/// hub, and a dispatcher wired to one interactive handler over a
|
||||
/// throwaway workspace.
|
||||
fn paste_env() -> (
|
||||
Arc<RecordingProvider>,
|
||||
Arc<EventHub>,
|
||||
Arc<Dispatcher>,
|
||||
InteractiveHandler,
|
||||
Key,
|
||||
tempfile::TempDir,
|
||||
) {
|
||||
let recorder = RecordingProvider::new();
|
||||
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
|
||||
let hub = Arc::new(EventHub::default());
|
||||
@@ -1087,7 +1220,7 @@ mod tests {
|
||||
Arc::new(rhema_memory::VolatileStore::new()),
|
||||
Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")),
|
||||
hub.clone(),
|
||||
notifications.clone(),
|
||||
notifications,
|
||||
attachments(),
|
||||
crate::config::DEFAULT_MAX_TURN_STEPS,
|
||||
extensions,
|
||||
@@ -1102,14 +1235,31 @@ mod tests {
|
||||
Arc::new(VolatileStore::new()),
|
||||
));
|
||||
register_user(&dispatcher);
|
||||
(
|
||||
recorder,
|
||||
hub,
|
||||
dispatcher,
|
||||
handler,
|
||||
Key::from("interactive:web"),
|
||||
workspace,
|
||||
)
|
||||
}
|
||||
|
||||
/// The legacy intake: a chat input still carrying the embedded
|
||||
/// mark form migrates at the fold — the model reads the payload in
|
||||
/// place, and the recorded question is the plain form with the
|
||||
/// chip noted beside it.
|
||||
#[tokio::test]
|
||||
async fn an_embedded_arrival_migrates_at_the_fold() {
|
||||
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
|
||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||
.with_holder("test");
|
||||
let key = Key::from("interactive:web");
|
||||
dispatcher
|
||||
.ingest(user_event(
|
||||
key.as_str(),
|
||||
"review this:\u{FFFC}fn main() {}\nfn other() {}\u{FFFC}",
|
||||
&[],
|
||||
&[],
|
||||
))
|
||||
.expect("ingests");
|
||||
driver.run_once().await.expect("the run happens");
|
||||
@@ -1119,17 +1269,61 @@ mod tests {
|
||||
"review this:fn main() {}\nfn other() {}",
|
||||
"the model saw the payload, not the marks"
|
||||
);
|
||||
// The recorded question is the plain form, the chip record
|
||||
// riding beside it as spans: the mark form lives on only in
|
||||
// rows recorded before chips rode as spans.
|
||||
let (history, _) = hub.subscribe_with_history(&key);
|
||||
let saw_input = history.into_iter().find_map(|event| match event {
|
||||
TurnEvent::UserMessage { text, .. } => Some(text),
|
||||
let question = history.into_iter().find_map(|event| match event {
|
||||
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
|
||||
_ => None,
|
||||
});
|
||||
assert!(
|
||||
saw_input
|
||||
.expect("the transcript saw the question")
|
||||
.contains('\u{FFFC}'),
|
||||
"the transcript keeps the compact chip form"
|
||||
let (text, pastes) = question.expect("the transcript saw the question");
|
||||
let payload = "fn main() {}\nfn other() {}";
|
||||
assert_eq!(text, "review this:fn main() {}\nfn other() {}", "no marks");
|
||||
assert_eq!(pastes.len(), 1, "the chip is one span");
|
||||
assert_eq!(pastes[0].start, "review this:".len());
|
||||
assert_eq!(pastes[0].end, "review this:".len() + payload.len());
|
||||
assert_eq!(pastes[0].lines, 2);
|
||||
}
|
||||
|
||||
/// The modern intake: chips ride as payloads beside their message,
|
||||
/// each appending to it — no mark on the wire, the span record born
|
||||
/// at the fold. A payload's carriage returns and stray marks
|
||||
/// normalize there too, so a chip can never re-cut the scan.
|
||||
#[tokio::test]
|
||||
async fn a_staged_chip_rides_its_payload_beside_the_question() {
|
||||
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
|
||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||
.with_holder("test");
|
||||
dispatcher
|
||||
.ingest(user_event(
|
||||
key.as_str(),
|
||||
"review this:",
|
||||
&["fn main() {}\r\nfn other() {}\u{FFFC}".to_owned()],
|
||||
&[],
|
||||
))
|
||||
.expect("ingests");
|
||||
driver.run_once().await.expect("the run happens");
|
||||
|
||||
// The model read the draft with the normalized payload
|
||||
// appended: what the record says is what the request carried.
|
||||
assert_eq!(
|
||||
recorder.last_user_text(),
|
||||
"review this:fn main() {}\nfn other() {}",
|
||||
"the model saw the payload, normalized, in place"
|
||||
);
|
||||
let (history, _) = hub.subscribe_with_history(&key);
|
||||
let question = history.into_iter().find_map(|event| match event {
|
||||
TurnEvent::UserMessage { text, pastes, .. } => Some((text, pastes)),
|
||||
_ => None,
|
||||
});
|
||||
let (text, pastes) = question.expect("the transcript saw the question");
|
||||
let payload = "fn main() {}\nfn other() {}";
|
||||
assert_eq!(text, format!("review this:{payload}"), "the plain form");
|
||||
assert_eq!(pastes.len(), 1, "the chip is one span");
|
||||
assert_eq!(pastes[0].start, "review this:".len());
|
||||
assert_eq!(pastes[0].end, "review this:".len() + payload.len());
|
||||
assert_eq!(pastes[0].lines, 2);
|
||||
}
|
||||
|
||||
/// A scripted tool-call turn: the model asking for `name` with `args`.
|
||||
@@ -1143,6 +1337,7 @@ mod tests {
|
||||
args,
|
||||
provider_data: serde_json::Value::Null,
|
||||
})],
|
||||
annotations: Default::default(),
|
||||
},
|
||||
stop_reason: StopReason::ToolUse,
|
||||
usage: Usage::default(),
|
||||
@@ -1253,8 +1448,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn user_events_carry_the_key_and_unique_ids() {
|
||||
let first = user_event("interactive:web", "hello", &[]);
|
||||
let second = user_event("interactive:web", "again", &[]);
|
||||
let first = user_event("interactive:web", "hello", &[], &[]);
|
||||
let second = user_event("interactive:web", "again", &[], &[]);
|
||||
assert_eq!(first.source, "user");
|
||||
assert_eq!(first.id, first.id, "stable within itself");
|
||||
assert_ne!(first.id, second.id, "messages never share a dedup id");
|
||||
@@ -1268,7 +1463,7 @@ mod tests {
|
||||
/// order; a plain message carries no `images` key at all.
|
||||
#[test]
|
||||
fn user_events_carry_images_only_when_the_message_has_any() {
|
||||
let bare = user_event("interactive:web", "plain", &[]);
|
||||
let bare = user_event("interactive:web", "plain", &[], &[]);
|
||||
assert_eq!(
|
||||
bare.payload,
|
||||
json!({"key": "interactive:web", "text": "plain"}),
|
||||
@@ -1277,6 +1472,7 @@ mod tests {
|
||||
let carried = user_event(
|
||||
"interactive:web",
|
||||
"look",
|
||||
&[],
|
||||
&[
|
||||
WireImage {
|
||||
media_type: "image/png".to_owned(),
|
||||
@@ -1309,7 +1505,7 @@ mod tests {
|
||||
Arc::new(VolatileStore::new()),
|
||||
);
|
||||
register_user(&dispatcher);
|
||||
let event = user_event("interactive:web", "hello", &[]);
|
||||
let event = user_event("interactive:web", "hello", &[], &[]);
|
||||
// Ingesting resolves the key through the registered fn: the
|
||||
// record lands under exactly the payload's key.
|
||||
dispatcher.ingest(event).expect("ingests");
|
||||
@@ -1344,11 +1540,13 @@ mod tests {
|
||||
Content::Text("on it".into()),
|
||||
Content::Text(" — done.".into()),
|
||||
],
|
||||
annotations: Default::default(),
|
||||
};
|
||||
assert_eq!(final_text(&message).as_deref(), Some("on it — done."));
|
||||
let empty = Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![Content::Text(" ".into())],
|
||||
annotations: Default::default(),
|
||||
};
|
||||
assert_eq!(final_text(&empty), None);
|
||||
}
|
||||
@@ -1459,6 +1657,42 @@ mod tests {
|
||||
assert!(err.contains("does not parse"), "{err}");
|
||||
}
|
||||
|
||||
/// A session stashed before paste spans existed carries the embedded
|
||||
/// form in its prompts; the restore pass rewrites it so a provider
|
||||
/// never sees a mark, and the chip rides as the span note instead.
|
||||
#[test]
|
||||
fn a_legacy_stash_is_migrated_on_restore() {
|
||||
let payload = "l1\nl2\nl3";
|
||||
let embedded = format!("review this:\u{FFFC}{payload}\u{FFFC} please");
|
||||
let stashed = json!({
|
||||
"history": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [embedded]
|
||||
}
|
||||
],
|
||||
"driver_state": serde_json::Value::Null
|
||||
});
|
||||
let session = restore_session(&stashed, "interactive:web").expect("the legacy stash loads");
|
||||
assert_eq!(
|
||||
final_text(&session.history[0]),
|
||||
Some(format!("review this:{payload} please")),
|
||||
"the mark and its payload land as plain text"
|
||||
);
|
||||
let text = final_text(&session.history[0]).expect("the prompt is text");
|
||||
// The chip rides as the span note: one span, over exactly the
|
||||
// payload's range, and no mark survives the restore.
|
||||
assert_eq!(
|
||||
rhema_core::paste::spans(&session.history[0]).as_slice(),
|
||||
&[rhema_core::paste::PasteSpan {
|
||||
start: "review this:".len(),
|
||||
end: "review this:".len() + payload.len(),
|
||||
lines: 3,
|
||||
}]
|
||||
);
|
||||
assert!(!text.contains('\u{FFFC}'), "no mark survives the restore");
|
||||
}
|
||||
|
||||
/// The full dispatch, in-process: one message in, one scripted reply
|
||||
/// out, the turn streamed through the hub, the conversation stashed.
|
||||
#[tokio::test]
|
||||
@@ -1507,7 +1741,7 @@ mod tests {
|
||||
let key = Key::from("interactive:web");
|
||||
let mut receiver = hub.subscribe(&key);
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "hello", &[]))
|
||||
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||
.expect("ingests");
|
||||
|
||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||
@@ -1520,7 +1754,8 @@ mod tests {
|
||||
receiver.try_recv().unwrap(),
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -1596,7 +1831,7 @@ mod tests {
|
||||
let key = Key::from("interactive:web");
|
||||
let mut receiver = hub.subscribe(&key);
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "hello", &[]))
|
||||
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||
.expect("ingests");
|
||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
|
||||
.with_holder("test");
|
||||
@@ -1616,7 +1851,7 @@ mod tests {
|
||||
|
||||
// Steer, in the route's order: ingest first, signal second.
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "stop that", &[]))
|
||||
.ingest(user_event(key.as_str(), "stop that", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert!(registry.signal(key.as_str()));
|
||||
|
||||
@@ -1633,7 +1868,8 @@ mod tests {
|
||||
receiver.try_recv().unwrap(),
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -1647,7 +1883,8 @@ mod tests {
|
||||
receiver.try_recv().unwrap(),
|
||||
TurnEvent::UserMessage {
|
||||
text: "stop that".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -1821,6 +2058,7 @@ mod tests {
|
||||
.ingest(user_event(
|
||||
key.as_str(),
|
||||
"look at this",
|
||||
&[],
|
||||
&[WireImage {
|
||||
media_type: "image/png".to_owned(),
|
||||
data: png.clone(),
|
||||
@@ -1831,6 +2069,7 @@ mod tests {
|
||||
.ingest(user_event(
|
||||
key.as_str(),
|
||||
"and at this",
|
||||
&[],
|
||||
&[WireImage {
|
||||
media_type: "Image/JPEG".to_owned(),
|
||||
data: jpeg.clone(),
|
||||
@@ -1838,7 +2077,7 @@ mod tests {
|
||||
))
|
||||
.expect("ingests");
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "no picture here", &[]))
|
||||
.ingest(user_event(key.as_str(), "no picture here", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("the run happens"),
|
||||
@@ -1851,7 +2090,11 @@ mod tests {
|
||||
let question = history
|
||||
.iter()
|
||||
.find_map(|event| match event {
|
||||
TurnEvent::UserMessage { text, images } => Some((text.clone(), images.clone())),
|
||||
TurnEvent::UserMessage {
|
||||
text,
|
||||
pastes,
|
||||
images,
|
||||
} => Some((text.clone(), images.clone(), pastes.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the transcript saw the question");
|
||||
@@ -1957,7 +2200,7 @@ mod tests {
|
||||
|
||||
// Dispatch 1: the model saves through the chain's memory tools.
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "remember the channel", &[]))
|
||||
.ingest(user_event(key.as_str(), "remember the channel", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("first run"),
|
||||
@@ -1976,7 +2219,7 @@ mod tests {
|
||||
// Dispatch 2: the model searches the same chain and answers from
|
||||
// memory — a fresh session turn, the same durable store.
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "where do releases go?", &[]))
|
||||
.ingest(user_event(key.as_str(), "where do releases go?", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("second run"),
|
||||
@@ -2064,7 +2307,7 @@ mod tests {
|
||||
// Dispatch 1: the model writes SOUL.md through the chain. A key
|
||||
// with a session continues, so both calls ride one key.
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "call me claw", &[]))
|
||||
.ingest(user_event(key.as_str(), "call me claw", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("first run"),
|
||||
@@ -2083,7 +2326,7 @@ mod tests {
|
||||
|
||||
// Dispatch 2: USER.md, same chain — and the pending flag clears.
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "and I am Ana", &[]))
|
||||
.ingest(user_event(key.as_str(), "and I am Ana", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("second run"),
|
||||
@@ -2141,7 +2384,7 @@ mod tests {
|
||||
register_user(&dispatcher);
|
||||
let key = Key::from("interactive:web");
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "hello", &[]))
|
||||
.ingest(user_event(key.as_str(), "hello", &[], &[]))
|
||||
.expect("ingests");
|
||||
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
|
||||
driver.run_once().await.expect("the run happens");
|
||||
@@ -2281,7 +2524,7 @@ mod tests {
|
||||
// An interactive reply is the chat surface's business: notified
|
||||
// nowhere.
|
||||
dispatcher
|
||||
.ingest(user_event("interactive:web", "hello", &[]))
|
||||
.ingest(user_event("interactive:web", "hello", &[], &[]))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("the run happens"),
|
||||
@@ -2359,7 +2602,12 @@ mod tests {
|
||||
|
||||
// The evening's work, in the chat session.
|
||||
dispatcher
|
||||
.ingest(user_event(key.as_str(), "we shipped the claw tonight", &[]))
|
||||
.ingest(user_event(
|
||||
key.as_str(),
|
||||
"we shipped the claw tonight",
|
||||
&[],
|
||||
&[],
|
||||
))
|
||||
.expect("ingests");
|
||||
assert_eq!(
|
||||
driver.run_once().await.expect("first run"),
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
//! instance and job resolve through the store, the workspace is the
|
||||
//! instance's path, the session blob (or a fresh agent) is loaded, the
|
||||
//! allowlist is permissive exactly as the forge path's — and then one
|
||||
//! `CodingAgent` turn runs. The final text lands in the job row and
|
||||
//! `HostAgent` turn runs. The final text lands in the job row and
|
||||
//! the user's notifications; the turn itself streams nowhere, its
|
||||
//! observability is the stderr tool log.
|
||||
//!
|
||||
@@ -22,11 +22,13 @@
|
||||
//! fails before any model call. The trust boundary is unchanged from
|
||||
//! the forge path — the bearer-gated surface and the instance list.
|
||||
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
|
||||
use rhema_coding_agent::{AllowAll, CodingAgent, CodingAgentConfig};
|
||||
use rhema_bash::{AllowAll, ShellTools};
|
||||
use rhema_core::{Event as ModelEvent, EventSink};
|
||||
use rhema_host_agent::{HostAgent, HostAgentConfig};
|
||||
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
|
||||
|
||||
use crate::backends::BackendRegistry;
|
||||
@@ -34,6 +36,7 @@ use crate::handler::final_text;
|
||||
use crate::interactive::passthrough_key_fn;
|
||||
use crate::job_store::{CodingJobStore, JobStatus};
|
||||
use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
|
||||
use crate::sandbox::SandboxState;
|
||||
|
||||
/// The source name the coding jobs ingest under.
|
||||
pub const JOBS_SOURCE: &str = "jobs";
|
||||
@@ -137,10 +140,13 @@ pub struct CodingJobHandler {
|
||||
backends: Arc<BackendRegistry>,
|
||||
store: Arc<CodingJobStore>,
|
||||
notifications: Arc<NotificationStore>,
|
||||
max_turn_steps: u32,
|
||||
max_turn_steps: NonZeroU32,
|
||||
/// Whether the jobs run the bounded request view (the config's
|
||||
/// `transcript`, on unless set false).
|
||||
transcript: bool,
|
||||
/// Where commands run: this host when absent, a remote sandbox when
|
||||
/// the surface selected one. Read per job.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
}
|
||||
|
||||
impl CodingJobHandler {
|
||||
@@ -151,7 +157,7 @@ impl CodingJobHandler {
|
||||
backends: Arc<BackendRegistry>,
|
||||
store: Arc<CodingJobStore>,
|
||||
notifications: Arc<NotificationStore>,
|
||||
max_turn_steps: u32,
|
||||
max_turn_steps: NonZeroU32,
|
||||
transcript: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -160,9 +166,17 @@ impl CodingJobHandler {
|
||||
notifications,
|
||||
max_turn_steps,
|
||||
transcript,
|
||||
sandbox: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the deployment's sandbox choice: a job's commands run
|
||||
/// where it says, seeded from the instance's host path.
|
||||
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
|
||||
self.sandbox = Some(sandbox);
|
||||
self
|
||||
}
|
||||
|
||||
/// One dispatch, failed with a reason on any step; every failure
|
||||
/// lands in the job row before it lands in the outcome, so the
|
||||
/// model's `status` read and the user's notification agree.
|
||||
@@ -212,7 +226,11 @@ impl CodingJobHandler {
|
||||
.map_err(|err| format!("job {job_id} could not start: {err}"))?;
|
||||
|
||||
let (provider, model) = self.backends.current();
|
||||
let mut config = CodingAgentConfig::new(model, &workspace);
|
||||
let display = match &self.sandbox {
|
||||
Some(sandbox) => sandbox.workspace_for(&workspace),
|
||||
None => workspace.clone(),
|
||||
};
|
||||
let mut config = HostAgentConfig::new(provider, model, &display, AllowAll);
|
||||
config.max_turn_steps = self.max_turn_steps;
|
||||
// A job's stashed session carries across runs and only ever
|
||||
// grows; the view is what keeps a repeat run's steps cheap.
|
||||
@@ -221,8 +239,18 @@ impl CodingJobHandler {
|
||||
config.transcript = self
|
||||
.transcript
|
||||
.then(rhema_transcript::TranscriptSettings::default);
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
match &self.sandbox {
|
||||
Some(sandbox) if sandbox.is_remote() => {
|
||||
config.tools = Some(Arc::new(ShellTools::with_executor(
|
||||
display,
|
||||
sandbox.executor(workspace.clone()),
|
||||
)));
|
||||
}
|
||||
_ => {
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
}
|
||||
}
|
||||
let stashed = self
|
||||
.store
|
||||
.session(&instance_name)
|
||||
@@ -236,9 +264,9 @@ impl CodingJobHandler {
|
||||
self.fail(job_id, &instance_name, &reason);
|
||||
reason
|
||||
})?;
|
||||
CodingAgent::from_session(provider, config, session)
|
||||
HostAgent::from_session(config, session)
|
||||
}
|
||||
None => CodingAgent::new(provider, config),
|
||||
None => HostAgent::new(config),
|
||||
}
|
||||
.map_err(|err| {
|
||||
let reason = format!("cannot start the coding agent for {instance_name:?}: {err}");
|
||||
@@ -248,12 +276,12 @@ impl CodingJobHandler {
|
||||
// Commit-before-execute rides the dispatcher exactly as the
|
||||
// forge handler's does: the intent is in the store before the
|
||||
// first tool runs, and a crash-left dangling call revives at
|
||||
// turn entry (CodingAgent::turn's own revive, over the resumed
|
||||
// turn entry (HostAgent::turn's own revive, over the resumed
|
||||
// session).
|
||||
agent.set_commit_hook(Some(ctx.commit_hook()));
|
||||
|
||||
let mut sink = JobSink;
|
||||
let output = match agent.turn(&job.prompt, &mut sink, Arc::new(AllowAll)).await {
|
||||
let output = match agent.turn(&job.prompt, &mut sink).await {
|
||||
Ok(output) => output,
|
||||
Err(err) => {
|
||||
let reason = format!("the coding turn for {instance_name:?} failed: {err}");
|
||||
@@ -280,7 +308,7 @@ impl CodingJobHandler {
|
||||
Ok(Outcome::Handled)
|
||||
}
|
||||
|
||||
fn save_session(&self, instance: &str, agent: &CodingAgent) {
|
||||
fn save_session(&self, instance: &str, agent: &HostAgent) {
|
||||
match serde_json::to_string(agent.session()) {
|
||||
Ok(blob) => {
|
||||
let _ = self.store.save_session(instance, &blob);
|
||||
@@ -360,7 +388,13 @@ mod tests {
|
||||
BackendRegistry::new(vec![Backend::headless("mock", provider)], None)
|
||||
.expect("a single mock backend always constructs"),
|
||||
);
|
||||
CodingJobHandler::new(backends, store, notifications, 16, true)
|
||||
CodingJobHandler::new(
|
||||
backends,
|
||||
store,
|
||||
notifications,
|
||||
NonZeroU32::new(16).unwrap(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn reply(text: &str) -> ModelOutput {
|
||||
|
||||
@@ -42,6 +42,8 @@
|
||||
//! workspace files handed to the human as fetchable cards
|
||||
//! - [`phone`] — the phone state and command queue: reported status to
|
||||
//! read, consent-gated control actions the device executes
|
||||
//! - [`sandbox`]: where `bash` runs, this host, or a remote daemon
|
||||
//! speaking the sandbox protocol over HTTP
|
||||
//! - [`watch_tools`] — the agent's watch-management tool set
|
||||
//! - [`notify_tools`] — the `notify` tool: the queue a device polls
|
||||
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
|
||||
@@ -89,6 +91,7 @@ pub mod notifications;
|
||||
pub mod notify_tools;
|
||||
pub mod openai;
|
||||
pub mod phone;
|
||||
pub mod sandbox;
|
||||
pub mod settings;
|
||||
pub mod steer;
|
||||
pub mod task_source;
|
||||
@@ -117,8 +120,11 @@ 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};
|
||||
pub use turn_store::{TurnStore, TurnStoreError};
|
||||
pub use watch_store::{ClawStore, Watch, WatchRecord, WatchShapeError, WatchStoreError};
|
||||
pub use watch_store::{
|
||||
ClawStore, SCOPE_ACCOUNT, SCOPE_REPO, Watch, WatchRecord, WatchShapeError, WatchStoreError,
|
||||
};
|
||||
@@ -74,9 +74,9 @@ async fn main() {
|
||||
}
|
||||
if let Some(Command::Vision { args: rest }) = &args.command {
|
||||
let mut argv = Vec::with_capacity(rest.len() + 1);
|
||||
argv.push(std::ffi::OsString::from(rhema_agent_tools::vision::MODE));
|
||||
argv.push(std::ffi::OsString::from(rhema_bash::vision::MODE));
|
||||
argv.extend(rest.iter().cloned());
|
||||
std::process::exit(rhema_agent_tools::vision::cli_run(&argv));
|
||||
std::process::exit(rhema_bash::vision::cli_run(&argv));
|
||||
}
|
||||
if let Err(err) = run(args).await {
|
||||
eprintln!("error: {err}");
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use rhema_coding_agent::CodingAgentConfig;
|
||||
use rhema_host_agent::HostAgentConfig;
|
||||
|
||||
/// What one wiring produced, held for the process.
|
||||
struct Wired {
|
||||
@@ -61,7 +61,7 @@ fn wired() -> Option<&'static Wired> {
|
||||
/// init file, the socket, the token), the prompt's `mcp` lines, and
|
||||
/// the persisted off switch. A frontend without wiring changes
|
||||
/// nothing.
|
||||
pub(crate) fn apply(config: &mut CodingAgentConfig) {
|
||||
pub(crate) fn apply(config: &mut HostAgentConfig) {
|
||||
let Some(wired) = wired() else {
|
||||
return;
|
||||
};
|
||||
@@ -82,7 +82,12 @@ mod tests {
|
||||
/// same map).
|
||||
#[test]
|
||||
fn apply_without_any_wiring_leaves_the_config_alone() {
|
||||
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
|
||||
let mut config = HostAgentConfig::new(
|
||||
rhema_core::mock::MockProvider::new([]),
|
||||
"m",
|
||||
std::path::Path::new("/tmp"),
|
||||
rhema_bash::AllowAll,
|
||||
);
|
||||
let before = config.shell_env.clone();
|
||||
apply(&mut config);
|
||||
// The wiring only appears when the machine's global mcp.yaml
|
||||
|
||||
@@ -65,6 +65,7 @@ impl ModelProvider for MockLoop {
|
||||
message: Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![Content::Text(text)],
|
||||
annotations: Default::default(),
|
||||
},
|
||||
stop_reason: StopReason::EndTurn,
|
||||
usage: Usage::default(),
|
||||
|
||||
@@ -259,6 +259,7 @@ pub async fn chat_completions(
|
||||
if let Err(err) = state.dispatcher().ingest(crate::interactive::user_event(
|
||||
key.as_str(),
|
||||
&input.text,
|
||||
&[],
|
||||
&input.images,
|
||||
)) {
|
||||
return error_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string());
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
//! Where the claw's `bash` runs: this host's processes, or a daemon
|
||||
//! speaking the sandbox protocol over HTTP.
|
||||
//!
|
||||
//! The choice is deployment state, persisted in the settings table and
|
||||
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
|
||||
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
|
||||
//! and gives the handlers a `ShellSandbox` executor over it. The tool
|
||||
//! spec, approval gate, output caps, and error shaping stay in
|
||||
//! `ShellTools`; only the machine changes.
|
||||
//!
|
||||
//! A remote sandbox starts empty. On the first command for a
|
||||
//! workspace, the executor probes `/workspace` and, when it is empty,
|
||||
//! sends the host workspace as a tarball through the protocol's seed
|
||||
//! route. Later edits stay in the sandbox; the claw does not copy them
|
||||
//! back.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use base64::Engine as _;
|
||||
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
|
||||
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
|
||||
use rhema_sandbox_http::HttpSandbox;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::settings::SettingsStore;
|
||||
|
||||
/// The settings key the chosen sandbox is persisted under.
|
||||
pub const SANDBOX_KEY: &str = "sandbox";
|
||||
|
||||
/// The workspace path a remote sandbox exposes: one root per session,
|
||||
/// fixed by the protocol.
|
||||
pub const REMOTE_WORKSPACE: &str = "/workspace";
|
||||
|
||||
/// The per-command budget of the emptiness probe before a seed: long
|
||||
/// enough for a fresh sandbox, short enough that an unreachable daemon
|
||||
/// fails the turn rather than stalling it.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// Which machine runs the shell.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SandboxKind {
|
||||
/// The daemon's own host, the original path.
|
||||
#[default]
|
||||
Local,
|
||||
/// A host speaking the sandbox protocol over HTTP.
|
||||
Http,
|
||||
}
|
||||
|
||||
impl SandboxKind {
|
||||
/// The stored spelling.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Local => "local",
|
||||
Self::Http => "http",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a stored spelling. Anything else is `None`, which every
|
||||
/// caller turns into the local default.
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"local" => Some(Self::Local),
|
||||
"http" => Some(Self::Http),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One sandbox choice: the kind and whatever it needs. `local` needs
|
||||
/// nothing; `http` needs a base URL and may carry a token.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub struct SandboxChoice {
|
||||
/// The machine kind.
|
||||
pub kind: SandboxKind,
|
||||
/// The `http` sandbox's base URL, no trailing slash after
|
||||
/// normalization.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
/// The shared secret the daemon checks, when it guards its routes.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
impl SandboxChoice {
|
||||
/// Trims the strings, drops blank ones, and validates what `http`
|
||||
/// needs to run. A choice that fails reads as a 400 at the route,
|
||||
/// never as a silent fallback.
|
||||
pub fn normalized(mut self) -> Result<Self, SandboxError> {
|
||||
self.url = self
|
||||
.url
|
||||
.map(|url| url.trim().trim_end_matches('/').to_owned())
|
||||
.filter(|url| !url.is_empty());
|
||||
self.token = self
|
||||
.token
|
||||
.map(|token| token.trim().to_owned())
|
||||
.filter(|token| !token.is_empty());
|
||||
if self.kind == SandboxKind::Http {
|
||||
let url = self
|
||||
.url
|
||||
.as_deref()
|
||||
.ok_or_else(|| SandboxError::Invalid("the http sandbox needs a url".to_owned()))?;
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
return Err(SandboxError::Invalid(
|
||||
"the http sandbox url must start with http:// or https://".to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Whether commands leave this host.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.kind == SandboxKind::Http
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a sandbox choice or operation failed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SandboxError {
|
||||
/// The choice cannot run as written.
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
/// The settings table failed.
|
||||
#[error("sandbox store failed: {0}")]
|
||||
Store(String),
|
||||
}
|
||||
|
||||
/// The chosen sandbox and the executors built over it, shared by every
|
||||
/// handler so a switch takes effect on the next turn without a restart.
|
||||
pub struct SandboxState {
|
||||
choice: RwLock<SandboxChoice>,
|
||||
settings: Arc<SettingsStore>,
|
||||
local_workspace: PathBuf,
|
||||
local: Arc<dyn ShellExecutor>,
|
||||
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
|
||||
}
|
||||
|
||||
impl SandboxState {
|
||||
/// The state over `settings`, seeded by `seed` when no choice was
|
||||
/// stored. `local_workspace` is the chat workspace the settings
|
||||
/// surface reports; `shell_env` is layered over local commands.
|
||||
pub fn load(
|
||||
settings: Arc<SettingsStore>,
|
||||
seed: Option<SandboxChoice>,
|
||||
local_workspace: PathBuf,
|
||||
shell_env: &BTreeMap<String, String>,
|
||||
) -> Result<Self, SandboxError> {
|
||||
let stored = settings
|
||||
.get(SANDBOX_KEY)
|
||||
.map_err(|err| SandboxError::Store(err.to_string()))?;
|
||||
let choice = stored
|
||||
.as_deref()
|
||||
.and_then(|raw| serde_json::from_str::<SandboxChoice>(raw).ok())
|
||||
.and_then(|choice| choice.normalized().ok())
|
||||
.or_else(|| seed.and_then(|choice| choice.normalized().ok()))
|
||||
.unwrap_or_default();
|
||||
Ok(Self {
|
||||
choice: RwLock::new(choice),
|
||||
settings,
|
||||
local_workspace,
|
||||
local: default_executor_with(shell_env),
|
||||
remote: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The current choice.
|
||||
pub fn choice(&self) -> SandboxChoice {
|
||||
self.choice
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Whether commands leave this host.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.choice
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.is_remote()
|
||||
}
|
||||
|
||||
/// Saves and applies a choice. The next turn reads it; nothing is
|
||||
/// rebuilt in place. Answers the normalized choice that was stored.
|
||||
pub fn set(&self, choice: SandboxChoice) -> Result<SandboxChoice, SandboxError> {
|
||||
let choice = choice.normalized()?;
|
||||
let raw =
|
||||
serde_json::to_string(&choice).map_err(|err| SandboxError::Store(err.to_string()))?;
|
||||
self.settings
|
||||
.set(SANDBOX_KEY, &raw)
|
||||
.map_err(|err| SandboxError::Store(err.to_string()))?;
|
||||
*self.choice.write().unwrap_or_else(PoisonError::into_inner) = choice.clone();
|
||||
self.remote
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clear();
|
||||
Ok(choice)
|
||||
}
|
||||
|
||||
/// The workspace a handler should name and start commands in: the
|
||||
/// host path locally, `/workspace` on a remote sandbox.
|
||||
pub fn workspace_for(&self, host: &Path) -> PathBuf {
|
||||
if self.is_remote() {
|
||||
PathBuf::from(REMOTE_WORKSPACE)
|
||||
} else {
|
||||
host.to_path_buf()
|
||||
}
|
||||
}
|
||||
|
||||
/// The chat workspace under the current choice, for the settings
|
||||
/// surface.
|
||||
pub fn workspace(&self) -> PathBuf {
|
||||
self.workspace_for(&self.local_workspace)
|
||||
}
|
||||
|
||||
/// The host workspace path, whatever the current choice.
|
||||
pub fn local_workspace(&self) -> &Path {
|
||||
&self.local_workspace
|
||||
}
|
||||
|
||||
/// An executor for one host workspace. Remote sessions are derived
|
||||
/// from the workspace path, so two workspaces never share a root.
|
||||
pub fn executor(
|
||||
self: &Arc<Self>,
|
||||
host_workspace: impl Into<PathBuf>,
|
||||
) -> Arc<dyn ShellExecutor> {
|
||||
Arc::new(ClawShell {
|
||||
state: Arc::clone(self),
|
||||
host_workspace: host_workspace.into(),
|
||||
local: self.local.clone(),
|
||||
seeded: AtomicBool::new(false),
|
||||
last: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// The cached HTTP client for one session. The map is cleared
|
||||
/// whenever the choice changes, so a new URL or token builds a new
|
||||
/// client.
|
||||
fn remote_sandbox(
|
||||
&self,
|
||||
choice: &SandboxChoice,
|
||||
host: &Path,
|
||||
) -> Result<Arc<HttpSandbox>, ShellError> {
|
||||
let url = choice
|
||||
.url
|
||||
.as_deref()
|
||||
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
|
||||
let session = session_name(host);
|
||||
{
|
||||
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(sandbox) = remote.get(&session) {
|
||||
return Ok(sandbox.clone());
|
||||
}
|
||||
}
|
||||
let token = choice.token.as_deref().unwrap_or("");
|
||||
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
|
||||
self.remote
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(session, sandbox.clone());
|
||||
Ok(sandbox)
|
||||
}
|
||||
}
|
||||
|
||||
/// One handler's view of the choice: local commands go straight to the
|
||||
/// host executor; remote commands go through the sandbox, seeded from
|
||||
/// the host workspace once per choice.
|
||||
struct ClawShell {
|
||||
state: Arc<SandboxState>,
|
||||
host_workspace: PathBuf,
|
||||
local: Arc<dyn ShellExecutor>,
|
||||
seeded: AtomicBool,
|
||||
last: Mutex<Option<SandboxChoice>>,
|
||||
}
|
||||
|
||||
impl ClawShell {
|
||||
/// Seeds the sandbox once per choice. An empty `/workspace` gets
|
||||
/// the host workspace as a tarball; a non-empty one is left alone
|
||||
/// so a restart never overwrites work done in the sandbox.
|
||||
async fn seed(
|
||||
&self,
|
||||
sandbox: &Arc<HttpSandbox>,
|
||||
cancelled: &AtomicBool,
|
||||
) -> Result<(), ShellError> {
|
||||
let mut sink = |_line: &str| {};
|
||||
let probe = sandbox
|
||||
.exec(
|
||||
ExecRequest {
|
||||
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
|
||||
cwd: REMOTE_WORKSPACE.to_owned(),
|
||||
timeout: PROBE_TIMEOUT,
|
||||
},
|
||||
cancelled,
|
||||
&mut sink,
|
||||
)
|
||||
.await
|
||||
.map_err(protocol_error)?;
|
||||
if !probe.stdout.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let root = self.host_workspace.clone();
|
||||
let archive = tokio::task::spawn_blocking(move || tarball(&root))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
ShellError::Failed(format!("the workspace archive task failed: {err}"))
|
||||
})??;
|
||||
let Some(tar_gz_base64) = archive else {
|
||||
return Ok(());
|
||||
};
|
||||
sandbox
|
||||
.seed(&WorkspaceSeed::Tarball {
|
||||
name: "workspace.tar.gz".to_owned(),
|
||||
tar_gz_base64,
|
||||
})
|
||||
.await
|
||||
.map_err(protocol_error)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ShellExecutor for ClawShell {
|
||||
async fn run(
|
||||
&self,
|
||||
command: &str,
|
||||
cwd: &Path,
|
||||
timeout: Duration,
|
||||
cancelled: &AtomicBool,
|
||||
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
|
||||
) -> Result<Executed, ShellError> {
|
||||
let choice = self.state.choice();
|
||||
if !choice.is_remote() {
|
||||
return self
|
||||
.local
|
||||
.run(command, cwd, timeout, cancelled, progress)
|
||||
.await;
|
||||
}
|
||||
{
|
||||
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if last.as_ref() != Some(&choice) {
|
||||
*last = Some(choice.clone());
|
||||
self.seeded.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let sandbox = self.state.remote_sandbox(&choice, &self.host_workspace)?;
|
||||
if !self.seeded.load(Ordering::Relaxed) {
|
||||
self.seed(&sandbox, cancelled).await?;
|
||||
self.seeded.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let sandbox: Arc<dyn Sandbox> = sandbox;
|
||||
ShellSandbox::new(sandbox)
|
||||
.run(
|
||||
command,
|
||||
Path::new(REMOTE_WORKSPACE),
|
||||
timeout,
|
||||
cancelled,
|
||||
progress,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a protocol failure onto the shell error the tool shapes into an
|
||||
/// `is_error` result.
|
||||
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
|
||||
match err {
|
||||
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
|
||||
rhema_sandbox::SandboxError::Unavailable(message)
|
||||
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
|
||||
// The error enum is non-exhaustive: an unknown failure is still
|
||||
// a failure, reported in-band with its own text.
|
||||
_ => ShellError::Failed(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sandbox session name for one host workspace: a stable FNV-1a
|
||||
/// hash of the path, so the daemon can multiplex one root per session
|
||||
/// and a restart finds the same root.
|
||||
fn session_name(host: &Path) -> String {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in host.to_string_lossy().as_bytes() {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
format!("rhema-claw-{hash:016x}")
|
||||
}
|
||||
|
||||
/// One host workspace as a gzipped tar, base64 for the protocol.
|
||||
/// `None` when the directory is missing or empty: nothing to seed.
|
||||
fn tarball(root: &Path) -> Result<Option<String>, ShellError> {
|
||||
if !root.is_dir() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut entries = std::fs::read_dir(root)
|
||||
.map_err(|err| ShellError::Failed(format!("cannot read the workspace {root:?}: {err}")))?;
|
||||
if entries.next().is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let output = std::process::Command::new("tar")
|
||||
.arg("-czf")
|
||||
.arg("-")
|
||||
.arg("-C")
|
||||
.arg(root)
|
||||
.arg(".")
|
||||
.output()
|
||||
.map_err(|err| {
|
||||
ShellError::Failed(format!("cannot archive the workspace with tar: {err}"))
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
let detail = String::from_utf8_lossy(&output.stderr);
|
||||
let detail = detail.trim();
|
||||
return Err(ShellError::Failed(if detail.is_empty() {
|
||||
"tar failed to archive the workspace".to_owned()
|
||||
} else {
|
||||
format!("tar failed to archive the workspace: {detail}")
|
||||
}));
|
||||
}
|
||||
Ok(Some(
|
||||
base64::engine::general_purpose::STANDARD.encode(output.stdout),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wiremock::matchers::{method, path_regex};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
fn state(choice: SandboxChoice) -> Arc<SandboxState> {
|
||||
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
|
||||
Arc::new(
|
||||
SandboxState::load(
|
||||
settings,
|
||||
Some(choice),
|
||||
PathBuf::from("/state/claw/workspaces/interactive"),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.expect("the state loads"),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_choice_is_local() {
|
||||
let choice = SandboxChoice::default().normalized().unwrap();
|
||||
assert_eq!(choice.kind, SandboxKind::Local);
|
||||
assert!(!choice.is_remote());
|
||||
assert_eq!(choice.kind.as_str(), "local");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_http_choice_needs_an_absolute_url() {
|
||||
let missing = SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: None,
|
||||
token: None,
|
||||
}
|
||||
.normalized();
|
||||
assert!(missing.is_err(), "a URL is required");
|
||||
|
||||
let relative = SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some("box.example:7600".to_owned()),
|
||||
token: None,
|
||||
}
|
||||
.normalized();
|
||||
assert!(relative.is_err(), "a bare host is not a URL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_remote_workspace_is_the_sandbox_root() {
|
||||
let state = state(SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some("http://box:7600/".to_owned()),
|
||||
token: None,
|
||||
});
|
||||
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
|
||||
assert_eq!(
|
||||
state.choice().url.as_deref(),
|
||||
Some("http://box:7600"),
|
||||
"the trailing slash is trimmed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_choice_persists_and_reloads() {
|
||||
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
|
||||
let state = SandboxState::load(
|
||||
settings.clone(),
|
||||
None,
|
||||
PathBuf::from("/tmp/ws"),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.expect("the state loads");
|
||||
assert_eq!(state.choice().kind, SandboxKind::Local);
|
||||
|
||||
state
|
||||
.set(SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some("https://box:7600".to_owned()),
|
||||
token: Some("secret".to_owned()),
|
||||
})
|
||||
.expect("the choice saves");
|
||||
|
||||
let reloaded =
|
||||
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
|
||||
.expect("the state reloads");
|
||||
assert_eq!(reloaded.choice().kind, SandboxKind::Http);
|
||||
assert_eq!(reloaded.choice().url.as_deref(), Some("https://box:7600"));
|
||||
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
|
||||
let server = MockServer::start().await;
|
||||
// The emptiness probe: nothing at /workspace.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"exit_code": 0,
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"timed_out": false
|
||||
})))
|
||||
.up_to_n_times(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
// The command itself.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"exit_code": 0,
|
||||
"stdout": "hi\n",
|
||||
"stderr": "",
|
||||
"timed_out": false
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
// The seed: accepted, and the host workspace is not empty.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/seed$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"error": null
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
std::fs::write(dir.path().join("README.md"), "seed me").expect("the file writes");
|
||||
let state = state(SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some(server.uri()),
|
||||
token: None,
|
||||
});
|
||||
let executor = state.executor(dir.path());
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let mut sink = |_line: &str| {};
|
||||
let executed = executor
|
||||
.run(
|
||||
"echo hi",
|
||||
Path::new(REMOTE_WORKSPACE),
|
||||
Duration::from_secs(5),
|
||||
&cancelled,
|
||||
&mut sink,
|
||||
)
|
||||
.await
|
||||
.expect("the remote command answers");
|
||||
assert_eq!(executed.stdout, b"hi\n");
|
||||
assert_eq!(executed.code, Some(0));
|
||||
}
|
||||
}
|
||||
@@ -325,6 +325,7 @@ mod tests {
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new(),
|
||||
},
|
||||
text_delta("hi"),
|
||||
],
|
||||
@@ -348,7 +349,8 @@ mod tests {
|
||||
0,
|
||||
TurnEvent::UserMessage {
|
||||
text: "hello".into(),
|
||||
images: Vec::new()
|
||||
images: Vec::new(),
|
||||
pastes: Vec::new()
|
||||
}
|
||||
),
|
||||
(1, text_delta("hi")),
|
||||
|
||||
@@ -9,21 +9,15 @@
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rhema_coding_agent::CodingAgentConfig;
|
||||
use rhema_host_agent::HostAgentConfig;
|
||||
|
||||
static WIRED: OnceLock<Option<Arc<rhema_agent_tools::vision::Wiring>>> = OnceLock::new();
|
||||
|
||||
/// The daemon's wiring, established at first use and kept for the
|
||||
/// process's life. `None` only when provisioning failed, cached like
|
||||
/// every answer this static gives.
|
||||
pub(crate) fn wired() -> Option<&'static Arc<rhema_agent_tools::vision::Wiring>> {
|
||||
WIRED
|
||||
.get_or_init(|| {
|
||||
rhema_agent_tools::vision::wire(std::env::var_os("BASH_ENV")).map(Arc::clone)
|
||||
})
|
||||
.as_ref()
|
||||
/// The daemon's wiring, provisioned at first use and kept for the
|
||||
/// process's life — the toolkit's own process-wide cache holds it, so
|
||||
/// `None` only when provisioning failed, and a failure does not retry.
|
||||
pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
|
||||
rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
|
||||
}
|
||||
|
||||
/// The init file a later provisioner chains through — `None` when the
|
||||
@@ -36,7 +30,7 @@ pub(crate) fn init_path() -> Option<std::ffi::OsString> {
|
||||
/// Layers the wiring onto one agent config: the shell env map (the
|
||||
/// init file, the binary, the staging directory) and the prompt's
|
||||
/// vision section. A frontend without wiring changes nothing.
|
||||
pub(crate) fn apply(config: &mut CodingAgentConfig) {
|
||||
pub(crate) fn apply(config: &mut HostAgentConfig) {
|
||||
let Some(wired) = wired() else {
|
||||
return;
|
||||
};
|
||||
@@ -52,7 +46,12 @@ mod tests {
|
||||
/// values are constants, so extending twice is the same map.
|
||||
#[test]
|
||||
fn apply_twice_is_apply_once() {
|
||||
let mut config = CodingAgentConfig::new("m", std::path::Path::new("/tmp"));
|
||||
let mut config = HostAgentConfig::new(
|
||||
rhema_core::mock::MockProvider::new([]),
|
||||
"m",
|
||||
std::path::Path::new("/tmp"),
|
||||
rhema_bash::AllowAll,
|
||||
);
|
||||
apply(&mut config);
|
||||
let once = config.shell_env.clone();
|
||||
apply(&mut config);
|
||||
|
||||
@@ -114,6 +114,13 @@ CREATE TABLE IF NOT EXISTS watch_health (
|
||||
consecutive_failures INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (scope, forge, subject)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS watch_cursors (
|
||||
scope TEXT NOT NULL,
|
||||
forge TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
cursor TEXT NOT NULL,
|
||||
PRIMARY KEY (scope, forge, subject)
|
||||
);
|
||||
";
|
||||
|
||||
/// Why a watch-table operation failed.
|
||||
@@ -315,6 +322,14 @@ impl ClawStore {
|
||||
"DELETE FROM watches WHERE forge = ?1 AND repo = ?2",
|
||||
params![forge.trim(), repo.trim()],
|
||||
)?;
|
||||
// The cursor goes with the watch: a re-add is a new watch, and it
|
||||
// starts at *now* like any other rather than resuming where the
|
||||
// old one stopped (which would replay everything that happened in
|
||||
// between as fresh news).
|
||||
conn.execute(
|
||||
"DELETE FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3",
|
||||
params![SCOPE_REPO, forge.trim(), repo.trim()],
|
||||
)?;
|
||||
Ok(removed == 1)
|
||||
}
|
||||
|
||||
@@ -419,6 +434,51 @@ impl ClawStore {
|
||||
.map_err(WatchStoreError::from)?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// The cursor one watch polls from: the last position it reported to
|
||||
/// the dispatcher, in the forge's own spelling. `None` before the
|
||||
/// watch has ever polled.
|
||||
pub fn cursor(
|
||||
&self,
|
||||
scope: &str,
|
||||
forge: &str,
|
||||
subject: &str,
|
||||
) -> Result<Option<String>, WatchStoreError> {
|
||||
let conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut statement = conn
|
||||
.prepare(
|
||||
"SELECT cursor FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3",
|
||||
)
|
||||
.map_err(WatchStoreError::from)?;
|
||||
let mut rows = statement
|
||||
.query_map(params![scope, forge, subject], |row| row.get(0))
|
||||
.map_err(WatchStoreError::from)?;
|
||||
match rows.next() {
|
||||
Some(row) => Ok(Some(row.map_err(WatchStoreError::from)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances one watch's cursor. Last write wins: the cursor only ever
|
||||
/// moves forward, and a stale write is one poll's worth of replay that
|
||||
/// the dispatcher's dedup lane already covers.
|
||||
pub fn set_cursor(
|
||||
&self,
|
||||
scope: &str,
|
||||
forge: &str,
|
||||
subject: &str,
|
||||
cursor: &str,
|
||||
) -> Result<(), WatchStoreError> {
|
||||
let conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
conn.execute(
|
||||
"INSERT INTO watch_cursors (scope, forge, subject, cursor) VALUES (?1, ?2, ?3, ?4)
|
||||
ON CONFLICT(scope, forge, subject) DO UPDATE SET cursor = excluded.cursor",
|
||||
params![scope, forge, subject, cursor],
|
||||
)
|
||||
.map_err(WatchStoreError::from)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records a successful poll: the streak resets, and the row stops
|
||||
/// reading as broken.
|
||||
pub fn record_poll_ok(
|
||||
@@ -637,6 +697,60 @@ mod tests {
|
||||
assert_eq!(store.list_health().expect("list reads").len(), 1);
|
||||
}
|
||||
|
||||
/// A watch remembers where it was: the cursor is a row, so a daemon
|
||||
/// restart resumes instead of replaying the repository's history.
|
||||
#[test]
|
||||
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"),
|
||||
None,
|
||||
"a watch that never polled has no cursor"
|
||||
);
|
||||
|
||||
store
|
||||
.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"),
|
||||
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"),
|
||||
None
|
||||
);
|
||||
|
||||
store
|
||||
.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"),
|
||||
Some("2026-10-09T00:00:00Z".to_owned())
|
||||
);
|
||||
|
||||
// Removing the watch forgets its place: a re-add starts over from
|
||||
// now instead of resuming into a backlog.
|
||||
store
|
||||
.add("gitea", "acme/barn", Some("https://git.example"), "tok")
|
||||
.expect("add");
|
||||
store.remove("gitea", "acme/barn").expect("remove");
|
||||
assert_eq!(
|
||||
store
|
||||
.cursor(SCOPE_REPO, "gitea", "acme/barn")
|
||||
.expect("read"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_fails_a_watch_loudly_and_specificly() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -13,10 +13,22 @@ 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) {
|
||||
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");
|
||||
// An established watch: it already has a cursor, so the pass reads
|
||||
// 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",
|
||||
)
|
||||
.expect("the cursor seeds");
|
||||
}
|
||||
use rhema_core::{Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
|
||||
use rhema_rsd::{KeyState, Outcome, ResourceKey, SqliteStore, Store};
|
||||
@@ -81,6 +93,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
transcript: None,
|
||||
ingest_token: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
transcript: None,
|
||||
ingest_token: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -67,10 +68,22 @@ 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) {
|
||||
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");
|
||||
// An established watch: it already has a cursor, so the pass reads
|
||||
// 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",
|
||||
)
|
||||
.expect("the cursor seeds");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+237
-15
@@ -18,7 +18,7 @@ use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, Sto
|
||||
use rhema_rsd::{ResourceKey, SqliteStore, Store};
|
||||
use serde_json::{Value, json};
|
||||
use tokio_stream::StreamExt;
|
||||
use wiremock::matchers::{method, path};
|
||||
use wiremock::matchers::{method, path, query_param};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
/// The scripted assistant turn: one text reply, nothing else.
|
||||
@@ -34,6 +34,7 @@ fn reply(text: &str) -> ModelOutput {
|
||||
fn tool_call(id: &str, name: &str, args: Value) -> ModelOutput {
|
||||
ModelOutput {
|
||||
message: Message {
|
||||
annotations: Default::default(),
|
||||
role: Role::Assistant,
|
||||
content: vec![Content::ToolCall(rhema_core::ToolCall {
|
||||
id: id.to_owned(),
|
||||
@@ -65,6 +66,7 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
ingest_token: None,
|
||||
transcript: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -232,21 +234,34 @@ 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!([{
|
||||
"id": 1007,
|
||||
"number": 7,
|
||||
"state": "closed",
|
||||
"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": "2026-10-02T10:00:00Z",
|
||||
"html_url": "https://github.com/acme/widgets/issues/7"
|
||||
}]);
|
||||
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",
|
||||
"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": "2026-10-02T10:00:00Z",
|
||||
"html_url": "https://github.com/acme/widgets/issues/7"
|
||||
}])))
|
||||
.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"))
|
||||
@@ -655,6 +670,77 @@ async fn chat_messages_carry_images_into_the_attachment_store() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A staged chip rides beside its draft and records as spans: the
|
||||
/// echo on the stream and the stashed session both carry the plain
|
||||
/// text with the `rhema-code` annotation beside it, and no mark ever
|
||||
/// crosses the wire.
|
||||
#[tokio::test]
|
||||
async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
|
||||
let provider = Arc::new(MockProvider::new([reply("on it")]));
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let daemon = Daemon::build(
|
||||
&config(&dir, None),
|
||||
mock_registry(provider),
|
||||
rhema_rsd::DispatcherConfig::default(),
|
||||
)
|
||||
.expect("the daemon assembles");
|
||||
let base = serve(&daemon).await;
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
// The chip rides as a payload beside the plain draft.
|
||||
let accepted = client
|
||||
.post(format!("{base}/v1/sessions/interactive:web/messages"))
|
||||
.json(&json!({
|
||||
"text": "review this:",
|
||||
"pastes": ["fn main() {}\nfn other() {}"],
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the message posts");
|
||||
assert_eq!(accepted.status(), 202);
|
||||
|
||||
// The echo on the stream: the payload in place, the span record
|
||||
// beside it, no marks in the text.
|
||||
let events = client
|
||||
.get(format!("{base}/v1/sessions/interactive:web/events"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the events request goes out");
|
||||
let mut stream = sse_body(events).await;
|
||||
let mut seen = String::new();
|
||||
read_until(&mut stream, &mut seen, r#""type":"turn_done""#).await;
|
||||
assert!(
|
||||
seen.contains(r#""type":"user_message","text":"review this:fn main() {}\nfn other() {}""#),
|
||||
"the echo carries the composed plain form: {seen}"
|
||||
);
|
||||
assert!(
|
||||
seen.contains(r#""pastes":[{"start":12,"end":38,"lines":2}]"#),
|
||||
"the chip notes itself as the span it stands for: {seen}"
|
||||
);
|
||||
assert!(!seen.contains('\u{FFFC}'), "no marks ride the wire: {seen}");
|
||||
|
||||
// The stash: the checkpoint's user message carries the payload in
|
||||
// the text and the annotation that outlives the turn.
|
||||
let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
|
||||
let key = ResourceKey::from("interactive:web");
|
||||
let record = store
|
||||
.load(&key)
|
||||
.expect("the record loads")
|
||||
.expect("the key has a record");
|
||||
let stashed: Session =
|
||||
serde_json::from_value(record.session.expect("a session").core.driver_state)
|
||||
.expect("the stash parses");
|
||||
let ask = stashed
|
||||
.history
|
||||
.iter()
|
||||
.find(|message| message.role == Role::User)
|
||||
.expect("the question is stashed");
|
||||
assert_eq!(rhema_core::paste::spans(ask).len(), 1);
|
||||
assert_eq!(rhema_core::paste::spans(ask)[0].start, 12);
|
||||
assert_eq!(rhema_core::paste::spans(ask)[0].end, 38);
|
||||
assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2);
|
||||
}
|
||||
|
||||
/// A turn nobody watched is still replayable: a client arriving after
|
||||
/// the fact — a reloaded browser, a reopened phone — subscribes cold and
|
||||
/// gets the finished turns back before the live feed. The same holds
|
||||
@@ -1109,7 +1195,23 @@ async fn watches_added_over_http_feed_the_next_detect_pass() {
|
||||
"the token is not serialized: {listed}"
|
||||
);
|
||||
|
||||
// The next pass detects through the new watch — no restart.
|
||||
// The next pass reads the new watch — no restart. Its first pass only
|
||||
// seeds a cursor: a watch starts at *now* and reports news, so the
|
||||
// repository's existing history is not replayed as a burst of
|
||||
// dispatches (and, from the handler, a burst of comments).
|
||||
let report = daemon.tick().await.expect("the pass runs");
|
||||
assert_eq!(report.detected, 0, "a fresh watch seeds its cursor");
|
||||
|
||||
// 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",
|
||||
)
|
||||
.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");
|
||||
|
||||
@@ -2209,6 +2311,126 @@ 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 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,
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! 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,
|
||||
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"),
|
||||
)
|
||||
}
|
||||
@@ -48,7 +48,7 @@ FROM debian:stable-slim
|
||||
# bash and git are load-bearing, not conveniences: the coding agent shells
|
||||
# out via `bash -c` and clones/fetches in its per-thread workspaces.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash git ca-certificates \
|
||||
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
|
||||
|
||||
@@ -67,7 +67,7 @@ FROM debian:stable-slim
|
||||
# load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
|
||||
# neither).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash git ca-certificates \
|
||||
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
|
||||
|
||||
@@ -3,5 +3,5 @@ name: rhema-claw
|
||||
description: "The resident forge-watching agent daemon: forge watches and a
|
||||
chat HTTP surface over one SQLite store."
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "0.1.0"
|
||||
version: 0.4.0
|
||||
appVersion: "0.4.0"
|
||||
@@ -15,10 +15,10 @@ publish = false
|
||||
rusqlite = { version = "0.40", features = ["bundled"] }
|
||||
# The reminder source: one `Source` over the feeds, detect-pass shaped
|
||||
# like the task scheduler's
|
||||
rhema-autonomous-agent = "0.2.3"
|
||||
rhema-autonomous-agent = "0.4.0"
|
||||
# The reminder source ingests its slots into a `Dispatcher`; the event
|
||||
# and key-function shapes are the dispatcher's
|
||||
rhema-rsd = "0.2.3"
|
||||
rhema-rsd = "0.4.0"
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -13,7 +13,7 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
# The dispatch seam: watches ingest into a Dispatcher
|
||||
rhema-rsd = "0.2.3"
|
||||
rhema-rsd = "0.4.0"
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -380,6 +380,46 @@ impl Timestamp {
|
||||
pub fn epoch_secs(&self) -> i64 {
|
||||
self.secs
|
||||
}
|
||||
|
||||
/// The instant `millis` milliseconds past the Unix epoch, in the
|
||||
/// canonical `YYYY-MM-DDThh:mm:ss[.mmm]Z` spelling.
|
||||
///
|
||||
/// This is how a cursor is born without a forge: a subsystem that
|
||||
/// starts watching *now* (rather than replaying a feed's history)
|
||||
/// needs a `since` spelled the way the forges spell theirs, and this
|
||||
/// is the one place that conversion lives.
|
||||
pub fn from_epoch_millis(millis: i64) -> Option<Self> {
|
||||
let secs = millis.div_euclid(1000);
|
||||
let sub_millis = millis.rem_euclid(1000);
|
||||
let (days, of_day) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
|
||||
let (year, month, day) = civil_from_days(days);
|
||||
let (hour, minute, second) = (of_day / 3_600, (of_day / 60) % 60, of_day % 60);
|
||||
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"
|
||||
)
|
||||
};
|
||||
Self::parse(&raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// The civil date `days` days past 1970-01-01, as `(year, month, day)` —
|
||||
/// the inverse of [`days_from_civil`] (Howard Hinnant's algorithm).
|
||||
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||
let z = days + 719_468;
|
||||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||||
let day_of_era = z - era * 146_097;
|
||||
let year_of_era =
|
||||
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
||||
let year = year_of_era + era * 400;
|
||||
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
||||
let mp = (5 * day_of_year + 2) / 153;
|
||||
let day = day_of_year - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = if month <= 2 { year + 1 } else { year };
|
||||
(year, month as u32, day as u32)
|
||||
}
|
||||
|
||||
/// A run of ASCII digits at `range`, as its number.
|
||||
@@ -524,4 +564,32 @@ mod tests {
|
||||
.expect("deserializes");
|
||||
assert_eq!(round, event);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timestamp_is_born_from_epoch_millis() {
|
||||
// The whole-second spelling the forges send, and the fractional
|
||||
// one GitLab sends: both round-trip back to the same instant.
|
||||
let whole =
|
||||
Timestamp::from_epoch_millis(1_791_417_600_000).expect("a millis instant parses");
|
||||
assert_eq!(whole.raw(), "2026-10-08T00:00:00Z");
|
||||
assert_eq!(whole.epoch_secs(), 1_791_417_600);
|
||||
|
||||
let fractional =
|
||||
Timestamp::from_epoch_millis(1_791_417_600_081).expect("a millis instant parses");
|
||||
assert_eq!(fractional.raw(), "2026-10-08T00:00:00.081Z");
|
||||
assert_eq!(fractional.epoch_secs(), whole.epoch_secs());
|
||||
|
||||
// The epoch itself, and a leap day, so the civil-date inverse is
|
||||
// exercised somewhere other than "today".
|
||||
assert_eq!(
|
||||
Timestamp::from_epoch_millis(0).expect("parses").raw(),
|
||||
"1970-01-01T00:00:00Z"
|
||||
);
|
||||
assert_eq!(
|
||||
Timestamp::from_epoch_millis(1_709_164_800_000)
|
||||
.expect("parses")
|
||||
.raw(),
|
||||
"2024-02-29T00:00:00Z"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,19 @@ pub trait Forge: Send + Sync {
|
||||
&self,
|
||||
since: Option<&Timestamp>,
|
||||
) -> Result<NotificationPage, ForgeError>;
|
||||
|
||||
/// 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)]
|
||||
|
||||
@@ -477,20 +477,17 @@ fn review_event(
|
||||
/// The comment event a repo-wide comments row carries.
|
||||
fn comment_event(row: &WireComment, repo: &RepoRef) -> Result<Option<ForgeEvent>, ForgeError> {
|
||||
let id = required(row.id, "comment id")?;
|
||||
let issue_url = required(row.issue_url.clone(), "comment issue_url")?;
|
||||
let number = parent_number(&issue_url).ok_or_else(|| {
|
||||
let number = comment_parent(row).ok_or_else(|| {
|
||||
ForgeError::Parse(format!(
|
||||
"comment issue_url without a thread number: {issue_url}"
|
||||
"comment {id} names no thread: issue_url {:?}, pull_request_url {:?}, html_url {:?}",
|
||||
row.issue_url, row.pull_request_url, row.html_url
|
||||
))
|
||||
})?;
|
||||
let timestamp = required(
|
||||
row.updated_at.clone().or_else(|| row.created_at.clone()),
|
||||
"comment timestamp",
|
||||
)?;
|
||||
let is_pr = row
|
||||
.pull_request_url
|
||||
.as_deref()
|
||||
.is_some_and(|url| !url.is_empty());
|
||||
let is_pr = comment_is_pr(row);
|
||||
Ok(Some(ForgeEvent {
|
||||
id: format!("gitea:comment:{id}"),
|
||||
kind: EventKind::Comment,
|
||||
@@ -505,9 +502,48 @@ fn comment_event(row: &WireComment, repo: &RepoRef) -> Result<Option<ForgeEvent>
|
||||
}))
|
||||
}
|
||||
|
||||
/// The parent thread number: a forge thread URL's trailing segment.
|
||||
/// Every URL a comment row carries, most specific first.
|
||||
fn comment_urls(row: &WireComment) -> [Option<&str>; 3] {
|
||||
[
|
||||
row.issue_url.as_deref(),
|
||||
row.pull_request_url.as_deref(),
|
||||
row.html_url.as_deref(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The thread number a comment row names.
|
||||
///
|
||||
/// `issue_url` is the field the API documents for it, but it is not
|
||||
/// reliable: the instance behind `git.vhaudiquet.fr` (28.3.0) sends it
|
||||
/// as an empty string on every row of the repo-wide `/issues/comments`
|
||||
/// feed, while `pull_request_url` and `html_url` stay populated. The
|
||||
/// 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_parent`]'s "is it a pull request" half: `pull_request_url`
|
||||
/// is set exactly on PR conversation comments, and stays set on the
|
||||
/// instances whose `issue_url` is blank — but a row that lost both still
|
||||
/// says so in its `html_url` path.
|
||||
fn comment_is_pr(row: &WireComment) -> bool {
|
||||
comment_urls(row)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|url| url.contains("/pulls/") || url.contains("/pull/"))
|
||||
}
|
||||
|
||||
/// The parent thread number: a forge thread URL's trailing segment,
|
||||
/// with any fragment dropped first — a comment's `html_url` points at
|
||||
/// the comment (`…/pulls/1#issuecomment-164`), and its fragment is not
|
||||
/// a number at all.
|
||||
fn parent_number(url: &str) -> Option<u64> {
|
||||
url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
|
||||
let path = url.split('#').next()?;
|
||||
path.trim_end_matches('/').rsplit('/').next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The fixed [`NotificationReason::Other`] spelling every reason-less
|
||||
@@ -690,6 +726,11 @@ 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,
|
||||
@@ -895,4 +936,57 @@ mod tests {
|
||||
.expect("comment carries an event");
|
||||
assert!(!event.is_pr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_with_a_blank_issue_url_still_names_its_thread() {
|
||||
// git.vhaudiquet.fr (28.3.0) sends `issue_url: ""` on every row
|
||||
// of the repo-wide comments feed. The poll used to fail on the
|
||||
// first such row, which is why that watch never reported a single
|
||||
// event: a PR comment must still resolve to its pull request.
|
||||
let comment: WireComment = serde_json::from_str(
|
||||
r#"{"id": 164, "user": {"login": "alice"}, "body": "thanks",
|
||||
"created_at": "2026-10-19T08:14:39Z",
|
||||
"updated_at": "2026-10-19T08:14:39Z",
|
||||
"issue_url": "",
|
||||
"pull_request_url": "https://forge.example/acme/widgets/pulls/3",
|
||||
"html_url": "https://forge.example/acme/widgets/pulls/3#issuecomment-164"}"#,
|
||||
)
|
||||
.expect("comment fixture parses");
|
||||
let event = comment_event(&comment, &repo())
|
||||
.expect("a blank issue_url is not a parse failure")
|
||||
.expect("comment carries an event");
|
||||
assert_eq!(event.number, 3);
|
||||
assert!(event.is_pr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_with_only_an_html_url_reads_the_thread_off_its_path() {
|
||||
// The last resort: no issue_url and no pull_request_url. The
|
||||
// html_url points at the comment, so the fragment has to go
|
||||
// before the trailing segment means anything.
|
||||
let comment: WireComment = serde_json::from_str(
|
||||
r#"{"id": 165, "created_at": "2026-10-19T09:00:00Z",
|
||||
"updated_at": "2026-10-19T09:00:00Z",
|
||||
"html_url": "https://forge.example/acme/widgets/issues/7#issuecomment-165"}"#,
|
||||
)
|
||||
.expect("comment fixture parses");
|
||||
let event = comment_event(&comment, &repo())
|
||||
.expect("maps")
|
||||
.expect("comment carries an event");
|
||||
assert_eq!(event.number, 7);
|
||||
assert!(!event.is_pr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_whose_urls_name_no_thread_is_still_loud() {
|
||||
// The fallbacks must not degrade into a silent skip: a row with
|
||||
// no number anywhere is a vocabulary gap, and the poll says so.
|
||||
let comment: WireComment = serde_json::from_str(
|
||||
r#"{"id": 166, "created_at": "2026-10-19T09:00:00Z",
|
||||
"issue_url": "", "html_url": "https://forge.example/acme/widgets/issues/"}"#,
|
||||
)
|
||||
.expect("comment fixture parses");
|
||||
let err = comment_event(&comment, &repo()).expect_err("no thread number names a thread");
|
||||
assert!(matches!(err, ForgeError::Parse(_)), "got {err:?}");
|
||||
}
|
||||
}
|
||||
@@ -646,6 +646,16 @@ 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,
|
||||
|
||||
@@ -523,6 +523,18 @@ 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,
|
||||
|
||||
@@ -177,12 +177,24 @@ impl Watcher {
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// One poll of `repo`: the page's events are ingested in feed order
|
||||
/// and the cursor advances to the page's. Returns how many events were
|
||||
/// fed to the dispatcher — replayed ids included, they dedup there.
|
||||
/// One poll of `repo` from the watcher's own cursor.
|
||||
pub async fn poll(&self, forge: &dyn Forge, repo: &RepoRef) -> Result<usize, WatchError> {
|
||||
let since = self.cursor(repo);
|
||||
let page = forge.poll(repo, since.as_ref()).await?;
|
||||
self.poll_since(forge, repo, since.as_ref()).await
|
||||
}
|
||||
|
||||
/// One poll of `repo` from an explicit `since`, for the embedder that
|
||||
/// keeps the cursor somewhere durable: the page's events are ingested
|
||||
/// in feed order and the watcher's cursor advances to the page's.
|
||||
/// Returns how many events were fed to the dispatcher — replayed ids
|
||||
/// included, they dedup there while they sit in an inbox.
|
||||
pub async fn poll_since(
|
||||
&self,
|
||||
forge: &dyn Forge,
|
||||
repo: &RepoRef,
|
||||
since: Option<&Timestamp>,
|
||||
) -> Result<usize, WatchError> {
|
||||
let page = forge.poll(repo, since).await?;
|
||||
let now = SystemClock.now_millis();
|
||||
let mut fed = 0;
|
||||
for event in &page.events {
|
||||
|
||||
@@ -557,3 +557,74 @@ async fn notifications_poll_maps_the_subject_feed() {
|
||||
assert_eq!(note.repo, RepoRef::new("acme", "widgets"));
|
||||
assert_eq!(note.title.as_deref(), Some("Fix the gate"));
|
||||
}
|
||||
|
||||
/// The instance behind `git.vhaudiquet.fr` sends `issue_url: ""` on every
|
||||
/// row of the repo-wide comments feed. A poll with one such row used to
|
||||
/// fail outright, so the watch it fed never reported anything at all.
|
||||
#[tokio::test]
|
||||
async fn poll_survives_a_comments_feed_with_blank_issue_urls() {
|
||||
let server = MockServer::start().await;
|
||||
for (endpoint, body) in [
|
||||
("/api/v1/repos/acme/widgets/issues", json!([])),
|
||||
("/api/v1/repos/acme/widgets/pulls", json!([])),
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/v1/repos/acme/widgets/issues/comments"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!([
|
||||
{ "id": 164, "user": { "login": "alice" }, "body": "thanks",
|
||||
"created_at": "2026-10-19T08:14:39Z",
|
||||
"updated_at": "2026-10-19T08:14:39Z",
|
||||
"issue_url": "",
|
||||
"pull_request_url": "https://forge.example/acme/widgets/pulls/1",
|
||||
"html_url": "https://forge.example/acme/widgets/pulls/1#issuecomment-164" },
|
||||
{ "id": 165, "user": { "login": "bob" }, "body": "still broken",
|
||||
"created_at": "2026-10-19T09:00:00Z",
|
||||
"updated_at": "2026-10-19T09:00:00Z",
|
||||
"issue_url": "",
|
||||
"pull_request_url": Value::Null,
|
||||
"html_url": "https://forge.example/acme/widgets/issues/2#issuecomment-165" }
|
||||
])))
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let since = Timestamp::parse(SINCE).expect("cursor parses");
|
||||
let page = forge(&server)
|
||||
.poll(&RepoRef::new("acme", "widgets"), Some(&since))
|
||||
.await
|
||||
.expect("a blank issue_url is not a poll failure");
|
||||
|
||||
let summary: Vec<(EventKind, u64, bool)> = page
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| (event.kind, event.number, event.is_pr))
|
||||
.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())
|
||||
);
|
||||
}
|
||||
@@ -532,3 +532,19 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
|
||||
Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses"))
|
||||
);
|
||||
}
|
||||
|
||||
/// 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,3 +572,20 @@ 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())
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
# rhema-tools — the claw's model-facing tools as bash skills + thin clients
|
||||
|
||||
*One project, independent of the claw: the resident's data tools become small
|
||||
executables and the markdown that teaches them, speaking the daemon's existing
|
||||
HTTP surface through a scoped agent credential.*
|
||||
|
||||
## 0. Scope
|
||||
|
||||
This spec moves the claw's model-facing data tools out of the daemon binary and
|
||||
its system prompt. After it, the model's view of tasks, watches, identity,
|
||||
notifications, and the phone is: `bash`, a handful of short-named executables
|
||||
on `PATH`, and one markdown skill per domain. The daemon keeps the state, the
|
||||
schedulers, and the sources; the tools project owns everything the model
|
||||
touches.
|
||||
|
||||
Two consumers change:
|
||||
|
||||
- the model, which stops seeing sixteen tool schemas on every step of every
|
||||
session and starts composing tool calls in the shell;
|
||||
- the claw, which stops being the only place a tool can live;
|
||||
- tool authors — users or the agent itself — who can add a capability without
|
||||
touching rhema at all (§8).
|
||||
|
||||
Non-goals v1: extracting the server side (stores, schedulers, sources) out of
|
||||
the claw; extracting memory, attachments, or the bootstrap prompt; any
|
||||
transport other than the daemon's existing HTTP surface; a daemon-side timer
|
||||
service (tier-1 tools use system schedulers; §8).
|
||||
|
||||
## 1. Problem statement
|
||||
|
||||
The claw's tools are native: one `TOOL.yaml` manifest and one Rust builtin per
|
||||
tool, resolved through the `ClawExtension` chain, rendered as a JSON-schema
|
||||
bullet into every `SYSTEM.md` render. Sixteen of them today, and the list
|
||||
grows with every feature.
|
||||
|
||||
Four costs, all structural:
|
||||
|
||||
1. **Context.** Every session pays the schema of every tool on every step, the
|
||||
resident's whole life long, whether or not the turn touches them.
|
||||
2. **Round trips.** "Unwatch every archived repo" is one native call per repo —
|
||||
one model step each. The model cannot loop, filter, or pipeline across tool
|
||||
results; only the harness can.
|
||||
3. **Coupling.** A new tool is a manifest, a builtin, an extension-struct line,
|
||||
and a registry test — all inside `rhema-claw`. Nothing tool-shaped can be
|
||||
written, versioned, or shipped without the daemon crate.
|
||||
4. **Reuse.** A second agent (a forge worker, a phone-side helper) cannot share
|
||||
the tools without depending on the daemon's binary.
|
||||
|
||||
That is the signal that the tool surface is a missing boundary, not a missing
|
||||
feature list. The boundary is a wire contract.
|
||||
|
||||
## 2. Design goals
|
||||
|
||||
- The model-facing surface is code: `bash` + executables + skills. Skills are
|
||||
read when a domain is relevant; `--help` is always current.
|
||||
- The tools project compiles with zero `rhema-claw` dependencies. Independence
|
||||
is a dependency arrow, not a directory layout, and CI enforces the arrow.
|
||||
- The daemon's state stays in the daemon. Clients hold no stores, no
|
||||
schedulers, no caches; they are request printers.
|
||||
- One trust boundary, made explicit and enforced: a scoped agent credential
|
||||
that cannot answer consents, forge chats, or ingest events.
|
||||
- Incremental: each domain migrates alone, and its native tool stays until its
|
||||
client ships.
|
||||
|
||||
## 3. The shape
|
||||
|
||||
Three pieces:
|
||||
|
||||
1. **Skills.** One markdown file per domain, shipped next to its binary and
|
||||
installed into the global skills directory that
|
||||
`rhema_agent_tools::skills::discover` already reads. The skill carries the
|
||||
examples; the binary carries the behavior; they never drift apart because
|
||||
they are versioned and installed together.
|
||||
2. **Thin clients.** One short-named executable per domain: `notify`, `tasks`,
|
||||
`watches`, `identity`, `phone`. Parse arguments, make one or a few HTTP
|
||||
calls, print JSON, exit.
|
||||
3. **The contract.** The daemon's `/v1` HTTP surface — the same routes the web
|
||||
UI and the phone client already speak. The contract is the tools project's
|
||||
entire knowledge of the claw.
|
||||
|
||||
One call, end to end — `schedule_task` becoming `tasks add`:
|
||||
|
||||
1. The user: "check CI hourly for me."
|
||||
2. The model runs `bash`: `tasks add --every 3600 "check CI" --json`.
|
||||
3. The `bash` tool spawns `tasks` inside the sandbox.
|
||||
4. `tasks` reads `RHEMA_URL` and `RHEMA_TOKEN` from its environment and does
|
||||
`POST /v1/tasks` with the JSON body.
|
||||
5. The daemon's route writes the same `TaskStore` row the native builtin used
|
||||
to write. The scheduler picks it up exactly as before — it never notices
|
||||
the row arrived over HTTP.
|
||||
6. `tasks` prints `{"id":"t-7"}` and exits 0. The model reads stdout and
|
||||
replies.
|
||||
|
||||
```
|
||||
model turn
|
||||
| bash: tasks add --every 3600 "check CI"
|
||||
v
|
||||
+----------------+ POST /v1/tasks +----------------------+
|
||||
| tools project | Authorization: agent | claw daemon |
|
||||
| tasks, notify, | --------------------> | route -> TaskStore |
|
||||
| watches, ... | <-------------------- | (state lives HERE) |
|
||||
| (stateless) | {"id":"t-7"} | scheduler fires |
|
||||
+----------------+ +----------------------+
|
||||
```
|
||||
|
||||
"HTTP client" is the role, not a framework: the client is to the daemon what
|
||||
`gh` is to GitHub. The state cannot live in the client — it is a different,
|
||||
short-lived process, possibly inside a sandbox container — so it forwards, and
|
||||
the independence is precisely that forwarding: no `rhema-claw` import exists
|
||||
anywhere in the tools project.
|
||||
|
||||
## 4. The wire contract
|
||||
|
||||
Transport: the daemon's existing axum router (`crates/rhema-claw/src/http.rs`)
|
||||
— loopback plus bearer today, an env-provisioned base URL when a deployment
|
||||
puts the sandbox on another host.
|
||||
|
||||
Routes that already serve clients as-is: `GET/POST /v1/watches`,
|
||||
`DELETE /v1/watches/{forge}/{repo}`, `GET/POST/DELETE /v1/calendars`
|
||||
(removal takes `/v1/calendars/{name}`; the reminders source reads the
|
||||
calendar table fresh every pass, so a route write is live without a
|
||||
restart), `GET/POST /v1/accounts`, `DELETE /v1/accounts/{id}`,
|
||||
`GET /v1/notifications`, `POST /v1/notifications/{id}/ack`,
|
||||
`GET /v1/phones`.
|
||||
|
||||
Watches and calendars are the pattern for every data domain the
|
||||
daemon reconfigures at runtime: the domain lives in a SQLite table —
|
||||
not in `claw.yaml` — the routes are the one write door, validation
|
||||
runs at the door (an invalid watch or calendar is refused loudly
|
||||
wherever it enters), and the config file carries only what boot
|
||||
needs. A config still carrying the retired `watches:` or
|
||||
`calendars:` keys is refused at parse time, not silently ignored.
|
||||
|
||||
Routes the extraction adds, because the operation exists today only as an
|
||||
in-process tool: `POST /v1/notifications` (the push), `GET/POST /v1/tasks`,
|
||||
`DELETE /v1/tasks/{id}`, `POST /v1/phones/{device}/commands`. Promoting a tool
|
||||
to a route is not new work twice — the web UI and phone gain the same
|
||||
operations the model does.
|
||||
|
||||
Conventions, fixed once:
|
||||
|
||||
- Every client prints JSON: one object per call, one object per line for
|
||||
lists. `--json` exists as a no-op flag for readability of examples.
|
||||
- Exit codes: `0` ok, `1` usage (clap), `2` daemon unreachable, `3` denied.
|
||||
- On failure the last stdout line is a single JSON object
|
||||
`{"error": "..."}` — the model parses one shape, always.
|
||||
- Version: every request carries `X-Rhema-Contract: 1`; a daemon speaking a
|
||||
different contract answers `409` with that same error shape. A stale
|
||||
installed binary fails loudly on first use, with no discovery round trip.
|
||||
|
||||
## 5. The agent credential
|
||||
|
||||
Today one `token: Option<String>` guards all of `/v1`, and the model never
|
||||
holds it — tools run in-process. Bash-accessible clients change who holds a
|
||||
credential, and the current token is the wrong one to hold:
|
||||
`POST /v1/consents/{id}` answers a consent, and an agent that can answer
|
||||
consents can answer its own `ask_secret`.
|
||||
|
||||
Two token classes, checked per route in the router:
|
||||
|
||||
- the **human token**, unchanged, for the web UI, the phone, and the scripts a
|
||||
user runs themselves;
|
||||
- the **agent token** (`agent_token` in the claw config), provisioned into the
|
||||
agent environment as `RHEMA_URL` + `RHEMA_TOKEN`, allowed on exactly the
|
||||
data routes the clients speak (§4), denied on consent resolve/deny, session
|
||||
and message creation, `phones_forget`, and `/v1/ingest`.
|
||||
|
||||
Boot refuses to start extracted-tool mode without `agent_token` configured —
|
||||
the failure belongs at boot, where the operator is looking, not mid-turn,
|
||||
where the model is. This is the step that turns the README's "the
|
||||
bearer-gated surface plus the watch list are the trust boundary" from a
|
||||
sentence into enforced code.
|
||||
|
||||
## 6. What stays native
|
||||
|
||||
- `bash` — the substrate the whole design stands on.
|
||||
- `ask_secret` — the consent round-trip waits inside the tool call, woken by
|
||||
the hub, its answer arriving through routes the agent credential must never
|
||||
reach (§5). Making it a client would hand the model its own approval path.
|
||||
- `coding_agent` — spawns a whole coding session, inherits the parent turn's
|
||||
approval hook, answers with a job id. Orchestration, not data access.
|
||||
- `zoom` — reads the in-process transcript mirror; no daemon state behind it.
|
||||
- memory and `attach_file` — native in v1. Memory is the first later-extraction
|
||||
candidate: its store is already behind a `MemoryStore` contract, so a
|
||||
`/v1/memory` route family plus a client is a shape, not a research project.
|
||||
|
||||
## 7. What moves
|
||||
|
||||
| current tool | client | route | wave |
|
||||
|---|---|---|---|
|
||||
| `list_watches` / `watch_repo` / `unwatch_repo` | `watches ls/add/rm` | `/v1/watches` (exists) | 1 |
|
||||
| `notify` | `notify push` | `POST /v1/notifications` (new) | 1 |
|
||||
| `schedule_task` / `cancel_task` / `list_tasks` | `tasks add/rm/ls` | `/v1/tasks` (new) | 2 |
|
||||
| `identity_save` / `identity_set` / `identity_list` / `identity_forget` | `identity save/set/ls/forget` | `/v1/accounts` (exists) | 3 |
|
||||
| `phone` | `phone run` | `POST /v1/phones/{device}/commands` (new) | 3 |
|
||||
| `bootstrap_save` | — | `PUT /v1/agent` (exists) | later candidate |
|
||||
|
||||
Wave 1 is watches plus notify: watches has complete routes, notify has the
|
||||
smallest state, and between them they exercise the whole path — scoped
|
||||
credential, `PATH` provisioning, skill discovery, contract versioning —
|
||||
before anything harder follows it.
|
||||
|
||||
## 8. Self-contained tools
|
||||
|
||||
The client extraction frees the tools from the daemon's binary. A second
|
||||
question follows: can a tool exist that was never part of rhema at all —
|
||||
written by a user, or by the agent itself mid-session, without a fork or a
|
||||
patch? Yes — and it needs no new API, because the generic API is the surface
|
||||
this spec already builds on. Three primitives, all HTTP, all daemon-side:
|
||||
|
||||
- **`POST /v1/ingest`** — wake the agent with an event. The route takes
|
||||
`{source, key, payload}`, registers unknown source names lazily on the RSD
|
||||
dispatcher, and rejects the daemon's reserved source names. A third-party
|
||||
tool's events therefore get the same guarantees the built-in integrations
|
||||
get: at most one live handler per resource key, races queued into the live
|
||||
inbox, crash recovery by lease.
|
||||
- **`POST /v1/notifications`** (§4) — reach the user's devices.
|
||||
- **`GET /v1/sessions/{key}/events`** — read back what the agent said.
|
||||
|
||||
Plus two non-daemon primitives: **files** (the tool keeps its own state in its
|
||||
own directory) and **system schedulers** (cron, launchd, schtasks — the tool
|
||||
installs its own trigger).
|
||||
|
||||
### Anatomy
|
||||
|
||||
A self-contained tool is four files and no rhema code:
|
||||
|
||||
- an executable, dropped in a bin directory the daemon puts on the agent's
|
||||
`PATH`;
|
||||
- a skill markdown next to it, installed into the global skills directory;
|
||||
- its own state directory under the state root (one subdir per tool, owned by
|
||||
the tool, `0600` for anything credential-shaped);
|
||||
- optionally one scheduler entry it installed itself.
|
||||
|
||||
### The watch table, from outside
|
||||
|
||||
Even the case that motivated native integration works through the front door.
|
||||
A third-party CI watcher: a cron entry runs its poller every five minutes; the
|
||||
poller calls the forge's API itself, with a token kept in its own state
|
||||
directory; it triages what is new against its own last-seen file; and for each
|
||||
new item it does
|
||||
`POST /v1/ingest {source: "ciwatch", key: "github/acme/widgets#123", payload: {...}}`.
|
||||
The dispatcher admits the key, the resident gets a turn, and a second event
|
||||
racing a live handler queues instead of doubling the work. The tool is a
|
||||
script; nothing in rhema changed.
|
||||
|
||||
### The two tiers
|
||||
|
||||
- **Tier 1 — self-contained.** Executable + skill + state dir + scheduler.
|
||||
Writable by anyone, including the agent. No daemon custody of anything.
|
||||
- **Tier 2 — native extension.** The `ClawExtension` seam stays for what
|
||||
genuinely needs the daemon: secret custody (rhema-identity's use-never-read
|
||||
contract — a tier-1 tool cannot receive a secret through the consent
|
||||
round-trip, whose answers land in the identity store, not in the tool),
|
||||
tick-rate and webhook latency (cron is minute-grained, has no catch-up, and
|
||||
the task table's re-arm semantics are the reference for what a daemon-side
|
||||
timer would have to do), and deep hub integration (auto-notify on non-chat
|
||||
replies, the phone command loop). The forge and calendar integrations live
|
||||
here and are not demoted — they are just no longer the only way.
|
||||
|
||||
### What this forbids
|
||||
|
||||
No plugin SDK, no tool manifest registry, no new IPC protocol. The platform is
|
||||
HTTP + files + `PATH` — the same surface the model itself uses. The only
|
||||
daemon additions this spec asks for are the §4 routes and the directory
|
||||
conventions. A `toolctl` helper in the tools project (`toolctl new`,
|
||||
`toolctl schedule` wrapping crontab/launchd/schtasks) is convenience, not
|
||||
contract.
|
||||
|
||||
### The agent as tool author
|
||||
|
||||
Tier 1 is writable from inside a session: the model writes a script into the
|
||||
bin dir, a skill into the skills dir, a crontab line — and the resident has
|
||||
grown itself a capability. That is the codemode endgame, and it costs only the
|
||||
conventions. One honest line comes with it: such a tool runs with the agent's
|
||||
privileges and persists past the session through its scheduler entry. The
|
||||
trust boundary is the shell, exactly as it already is, and `ENVIRONMENT.md`
|
||||
says what is installed.
|
||||
|
||||
## 9. Provisioning and discovery
|
||||
|
||||
The daemon installs the clients (a `bin` directory it controls, added to the
|
||||
agent's `PATH`) and their skills (the global skills directory). Boot-time
|
||||
`ENVIRONMENT.md` already inventories what is on `PATH`, so a missing binary is
|
||||
visible before the first model call. A client that cannot reach the daemon
|
||||
prints which environment variable is missing or wrong — the model reports it
|
||||
instead of retrying.
|
||||
|
||||
## 10. Approvals, replay, crash
|
||||
|
||||
A `bash` call that runs three clients is one approval unit and one
|
||||
commit-before-execute unit — coarser than three native calls, and already true
|
||||
of any compound shell command. Resident sessions auto-approve the shell
|
||||
anyway (the daemon says so at startup), so nothing is lost in practice. In
|
||||
exchange, mutating verbs are upsert-shaped (`add`, `rm`, `save`), so a replay
|
||||
after a mid-command crash converges instead of duplicating. The manifests'
|
||||
`replay_safety: safe` moves into the contract: `GET` verbs are safe,
|
||||
`POST`/`DELETE` are not, and the exit code says which one ran.
|
||||
|
||||
## 11. Layout and the dependency arrow
|
||||
|
||||
New project — `rhema-tools`:
|
||||
|
||||
- `rhema-claw-tools-contract` — route constants, JSON payload types, a mock router,
|
||||
and the conformance suite. Depends on nothing.
|
||||
- one crate per domain — the binary and its skills directory.
|
||||
- one thin shared client crate — base-URL/token env handling, the HTTP calls,
|
||||
the error printing every binary shares.
|
||||
|
||||
Dependency arrows, both enforced in CI: the claw depends on
|
||||
`rhema-claw-tools-contract` (to run the conformance suite against its real router)
|
||||
and never on the domain crates; the tools project depends on nothing of
|
||||
rhema-claw.
|
||||
|
||||
`TOOL.yaml` is retired for extracted domains. The manifest existed to make a
|
||||
Rust builtin model-facing; a clap surface plus a skill markdown is that now.
|
||||
The old guarantee — every manifest loads against its builtin — becomes two:
|
||||
every skill's examples parse against the binary (`--help`/dry-run), and every
|
||||
route the contract names is exercised by the conformance suite.
|
||||
|
||||
## 12. Migration
|
||||
|
||||
1. The scoped agent credential lands in the claw: token classes, route
|
||||
middleware, boot check. No model-facing change.
|
||||
2. The contract crate lands; the claw grows the new routes
|
||||
(`POST /v1/notifications`, the `/v1/tasks` family) and passes conformance.
|
||||
3. Wave 1: `watches` and `notify` clients + skills; the agent environment gets
|
||||
`PATH`, skills, `RHEMA_URL`/`RHEMA_TOKEN`, and the tier-1 state root; the
|
||||
two domains' manifests and builtins stop rendering and are deleted.
|
||||
4. Waves 2–3 repeat step 3 per domain: routes if new, client + skill, delete
|
||||
manifest + builtin + extension line.
|
||||
5. When the last wave lands, the claw's `SYSTEM.md` tools section lists
|
||||
`bash`, `zoom`, `ask_secret`, `coding_agent`, memory — plus a two-line
|
||||
pointer to the installed skills.
|
||||
|
||||
## 13. How we know it works
|
||||
|
||||
- Conformance: the contract's suite runs against the claw's real router and
|
||||
against the contract's mock router, with the same results.
|
||||
- Arrow test: the tools workspace builds with `rhema-claw` absent.
|
||||
- End to end: a mock-provider turn whose scripted model runs `tasks add`
|
||||
through `bash`; the daemon's scheduler fires the task; the phone poll sees
|
||||
the notification; the agent token's `POST /v1/consents/{id}` answers `403`.
|
||||
- Skill lint: every fenced shell example in every skill parses (usage check /
|
||||
dry-run), so doc rot fails a test instead of fooling a model.
|
||||
- Tier-1 end to end: a test drops a two-line shell script and a skill into the
|
||||
provisioned dirs, runs it, and its `POST /v1/ingest` lands as a turn;
|
||||
`POST /v1/ingest` under a reserved source name answers `400`.
|
||||
|
||||
## 14. Explicitly not decided here
|
||||
|
||||
- Binary naming: short domain names (`tasks`) versus a prefix
|
||||
(`rhema-tasks`). Short names read best in skills; switch if a collision
|
||||
appears on a real system.
|
||||
- Whether the project starts as a repo-local directory (the `integrations/`
|
||||
shape) and extracts to its own repo later, or is born separate.
|
||||
- Extraction waves for memory, `attach_file`, and `bootstrap_save`.
|
||||
- Transports beyond bearer-over-HTTP: a unix-socket listener, mTLS for a
|
||||
remote daemon, a quota on client calls per turn.
|
||||
- Whether `toolctl` (scaffolder + scheduler wrapper) ships in v1 or stays
|
||||
documentation.
|
||||
- A daemon-side timer service (`POST /v1/timers`) for cronless hosts — the
|
||||
task table's fire-guards are the reference semantics. Not v1.
|
||||
- Whether tier-1 tools ever get a consent-shaped way to receive secrets. V1
|
||||
answer: no — users place credentials in the tool's state dir themselves.
|
||||
|
||||
## 15. Decisions
|
||||
|
||||
- Model-facing data tools become bash skills + thin executables; the schema
|
||||
list leaves `SYSTEM.md`.
|
||||
- Wire contract, not crate dependency; the arrows claw → contract ← tools are
|
||||
enforced.
|
||||
- The scoped agent credential precedes every client; consents, sessions, and
|
||||
ingest are unreachable by it.
|
||||
- Native keeps: `bash`, `ask_secret`, `coding_agent`, `zoom`, memory,
|
||||
`attach_file` (v1).
|
||||
- Waves: watches + notify, then tasks, then identity + phone.
|
||||
- Self-contained tools are files + system schedulers + the three HTTP
|
||||
primitives; no plugin SDK, no manifest registry, no new IPC.
|
||||
- Two tiers: tier 1 writable by anyone, including the agent mid-session;
|
||||
tier 2 (`ClawExtension`) keeps secret custody, tick/webhook latency, and
|
||||
hub depth.
|
||||
|
||||
---
|
||||
|
||||
## Status
|
||||
|
||||
Wave 1 is built: `tools/contract` (allowlist, header, conformance
|
||||
suite), `tools/notify` (the first client tool), the claw's contract
|
||||
enforcement (the scoped agent token, the allowlist middleware, the
|
||||
push and schedule routes, the JSON error shape everywhere), and the
|
||||
provisioning seam (`agent_token` + `tools_bin` → the daemon's tool
|
||||
environment → `ShellTools::with_env` → the coding agent's commands).
|
||||
The conformance suite runs against the daemon's real router in
|
||||
`crates/rhema-claw/tests/http.rs`; `tools/notify/tests` drives the
|
||||
`notify` binary against a mock. Waves 2–4 (skills mounts, packaging,
|
||||
more tools) are still future work.
|
||||
+19
-9
@@ -90,12 +90,21 @@ Two consequences worth knowing before changing this code:
|
||||
|
||||
## What the transcript does with the stream
|
||||
|
||||
- **Replies, asks and files only.** The stream carries tool calls and
|
||||
the model's thinking trace; this surface drops both and renders the
|
||||
reply. A consent card and an attachment card still appear inline,
|
||||
because the reader has to answer or open them. The mirror still
|
||||
folds those other events; only the render ignores them.
|
||||
- **Long pastes travel as chips.** A paste over three lines (the TUI's
|
||||
`PASTE_INLINE_LINES`) never lands in the composer; it stages as a
|
||||
droppable chip (`▣1 42L`) and embeds into the sent text as
|
||||
U+FFFC-payload-U+FFFC — the same record `rhema-core`'s
|
||||
`paste::embed` keeps — so the transcript renders each embed back as
|
||||
a chip in place of the payload. An unpaired mark is literal text.
|
||||
droppable chip (`▣1 42L`) and rides the body's `pastes` array beside
|
||||
the plain draft — the claw composes the record (the payload in
|
||||
place, the span note beside it) — so no mark ever crosses the wire.
|
||||
The `user_message` echo names each chip as the byte span it stands
|
||||
for (the session record's own shape, `paste::PasteSpan`), and the
|
||||
transcript renders from that. Rows recorded before spans rode the
|
||||
stream carry the legacy mark form in the text instead; the render
|
||||
still scans for those, and an unpaired mark stays literal.
|
||||
- **The agent can ask.** A `consent_request` event renders as an
|
||||
inline card: kind `secret` gets a password input plus submit, kind
|
||||
`phone` gets Approve/Deny, and both carry a deny link
|
||||
@@ -175,10 +184,10 @@ app/
|
||||
raw HTML escaped, styles in main.css .md)
|
||||
ClawBanner.vue the one error/notice banner surface
|
||||
ChatPanel.vue transcript: sent lines (paste chips),
|
||||
streamed turns as bash shell lines and
|
||||
glyph rows, consent + attachment
|
||||
cards; the growing composer; agent
|
||||
replies render through AppMarkdown
|
||||
streamed turns as reply text plus
|
||||
consent + attachment cards; the growing
|
||||
composer; agent replies render through
|
||||
AppMarkdown
|
||||
SessionsSidebar.vue conversable dispatch keys (phone status
|
||||
keys hidden), interactive first; the
|
||||
+ form creates a session
|
||||
@@ -193,7 +202,8 @@ app/
|
||||
composables/
|
||||
useClaw.ts the typed API client + fetch-based SSE
|
||||
useTranscript.ts folds TurnEvents into renderable turn
|
||||
blocks; owns the paste-embed text form
|
||||
blocks; owns the paste span record (and
|
||||
the legacy mark form old rows carry)
|
||||
server/
|
||||
middleware/claw-proxy.ts dev-only same-origin proxy to a running claw
|
||||
```
|
||||
+55
-8
@@ -17,9 +17,11 @@ import type {
|
||||
NewAccount,
|
||||
ProviderCredentials,
|
||||
ProvidersState,
|
||||
SandboxSelection,
|
||||
SandboxState,
|
||||
StreamStatus,
|
||||
} from '~/composables/useClaw'
|
||||
import { useTranscript } from '~/composables/useTranscript'
|
||||
import { composeChips, useTranscript } from '~/composables/useTranscript'
|
||||
import type { StagedImage } from '~/composables/useTranscript'
|
||||
|
||||
const TOKEN_STORE_KEY = 'claw.token'
|
||||
@@ -58,7 +60,13 @@ const SETTINGS_SECTIONS: { label: string; entries: { id: string; label: string }
|
||||
],
|
||||
},
|
||||
{ label: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] },
|
||||
{ label: 'System', entries: [{ id: 'about', label: 'About' }] },
|
||||
{
|
||||
label: 'System',
|
||||
entries: [
|
||||
{ id: 'sandbox', label: 'Sandbox' },
|
||||
{ id: 'about', label: 'About' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
function parseHash(): Route {
|
||||
@@ -265,6 +273,8 @@ const mutatingIdentity = ref(false)
|
||||
const accounts = ref<ClawAccount[] | null>(null)
|
||||
const accountsLoading = ref(false)
|
||||
const mutatingAccounts = ref(false)
|
||||
const sandboxState = ref<SandboxState | null>(null)
|
||||
const savingSandbox = ref(false)
|
||||
const streamStatus = ref<StreamStatus>('connecting')
|
||||
const busy = ref(false)
|
||||
const authRequired = ref(false)
|
||||
@@ -499,21 +509,50 @@ async function removeProvider(id: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
|
||||
// The optimistic row renders the staged previews; the stream's
|
||||
// user_message echo carries the stored ids and dedupes against it.
|
||||
async function refreshSandbox(): Promise<void> {
|
||||
try {
|
||||
sandboxState.value = await claw.sandbox()
|
||||
apiError.value = null
|
||||
} catch (err) {
|
||||
noteApiError(err)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSandbox(choice: SandboxSelection): Promise<void> {
|
||||
savingSandbox.value = true
|
||||
try {
|
||||
sandboxState.value = await claw.setSandbox(choice)
|
||||
pushNotice(
|
||||
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine',
|
||||
)
|
||||
apiError.value = null
|
||||
} catch (err) {
|
||||
noteApiError(err)
|
||||
} finally {
|
||||
savingSandbox.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
|
||||
// The optimistic row renders the staged previews and the composed
|
||||
// chip record — the same plain text and spans the fold records on
|
||||
// the other side — so the stream's user_message echo, which
|
||||
// carries the stored ids beside that record, dedupes against it.
|
||||
const composed = composeChips(message.text, message.pastes)
|
||||
const rowId = transcript.addSent(
|
||||
message.text,
|
||||
composed.text,
|
||||
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
|
||||
composed.pastes,
|
||||
)
|
||||
busy.value = true
|
||||
try {
|
||||
// Fire-and-forget by design: the claw answers 202 and the reply
|
||||
// arrives on the event stream. The body carries the images only
|
||||
// when there are some.
|
||||
// arrives on the event stream. The chips and the images ride the
|
||||
// body only when there are some.
|
||||
await claw.sendMessage(
|
||||
activeKey.value,
|
||||
message.text,
|
||||
message.pastes,
|
||||
message.images.map(({ media_type, data }) => ({ media_type, data })),
|
||||
)
|
||||
apiError.value = null
|
||||
@@ -581,6 +620,7 @@ function saveToken(): void {
|
||||
void refreshSessions()
|
||||
void refreshIdentity()
|
||||
void refreshAccounts()
|
||||
void refreshSandbox()
|
||||
}
|
||||
|
||||
// --- the one live subscription ---------------------------------------
|
||||
@@ -657,6 +697,7 @@ onMounted(() => {
|
||||
void refreshIdentity()
|
||||
void refreshProviders()
|
||||
void refreshAccounts()
|
||||
void refreshSandbox()
|
||||
void refreshSessions()
|
||||
healthTimer = setInterval(checkHealth, 30000)
|
||||
sessionsTimer = setInterval(() => void refreshSessions(), 20000)
|
||||
@@ -789,6 +830,12 @@ onUnmounted(() => {
|
||||
@add="addProvider"
|
||||
@remove="removeProvider"
|
||||
/>
|
||||
<SettingsSandboxPage
|
||||
v-show="route.section === 'sandbox'"
|
||||
:state="sandboxState"
|
||||
:saving="savingSandbox"
|
||||
@save="saveSandbox"
|
||||
/>
|
||||
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
|
||||
</template>
|
||||
</main>
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
import {
|
||||
PASTE_INLINE_LINES,
|
||||
chipLabel,
|
||||
embedPastes,
|
||||
byteToIndex,
|
||||
chipLinesLabel,
|
||||
lineCount,
|
||||
normalizePaste,
|
||||
pasteParts,
|
||||
} from '~/composables/useTranscript'
|
||||
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
|
||||
import type { PasteSpan } from '~/composables/useClaw'
|
||||
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
|
||||
* the staged images, previews included for the optimistic row. */
|
||||
interface SendPayload {
|
||||
text: string
|
||||
/** The chip payloads, in staging order — the wire carries them
|
||||
* beside the plain draft; the fold composes the record. */
|
||||
pastes: string[]
|
||||
images: StagedImage[]
|
||||
}
|
||||
|
||||
@@ -136,20 +141,12 @@ watch(
|
||||
},
|
||||
)
|
||||
|
||||
// Thinking grows inside the trailing entry without changing the
|
||||
// entries length, so its total length joins the watch to keep the
|
||||
// stream pinned at the bottom.
|
||||
function liveThinkingLength(): number {
|
||||
return (
|
||||
props.live?.entries.reduce(
|
||||
(count, entry) => (entry.kind === 'thinking' ? count + entry.text.length : count),
|
||||
0,
|
||||
) ?? 0
|
||||
)
|
||||
}
|
||||
|
||||
// A consent or attachment card opening inside the trailing turn
|
||||
// changes the rendered height, so the reply length and the entries
|
||||
// length both join the watch that keeps the stream pinned at the
|
||||
// bottom.
|
||||
watch(
|
||||
() => [props.items.length, props.live?.reply.length, liveThinkingLength(), props.live?.entries.length],
|
||||
() => [props.items.length, props.live?.reply.length, props.live?.entries.length],
|
||||
async () => {
|
||||
if (!pinned.value) return
|
||||
await nextTick()
|
||||
@@ -165,7 +162,7 @@ function submit(): void {
|
||||
// answers 202 at once) — a running turn never blocks the composer,
|
||||
// because a send into one steers it.
|
||||
if (!text || !props.canSend || props.busy) return
|
||||
emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value })
|
||||
emit('send', { text, pastes: pastes.value, images: stagedImages.value })
|
||||
stageGeneration++
|
||||
draft.value = ''
|
||||
pastes.value = []
|
||||
@@ -367,17 +364,36 @@ function storedImageName(image: SentImage): string {
|
||||
type MessageSegment = PastePart | { kind: 'chip'; label: string }
|
||||
|
||||
/** The message's render pieces: literal text and resolved chips, the
|
||||
* chips' one-based ids counted across the message. */
|
||||
function messageSegments(text: string): MessageSegment[] {
|
||||
* chips' one-based ids counted across the message. The chips come
|
||||
* from the row's span record — the plain text sliced at the spans'
|
||||
* byte boundaries — and a row from before spans rode the wire
|
||||
* carries none; that one still scans the mark form in its text. */
|
||||
function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] {
|
||||
if (pastes.length === 0) {
|
||||
const segments: MessageSegment[] = []
|
||||
let chip = 0
|
||||
for (const part of pasteParts(text)) {
|
||||
if (part.kind === 'text') {
|
||||
if (part.text !== '') segments.push(part)
|
||||
} else {
|
||||
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) })
|
||||
}
|
||||
}
|
||||
return segments
|
||||
}
|
||||
const indexOf = byteToIndex(text)
|
||||
const segments: MessageSegment[] = []
|
||||
let chip = 0
|
||||
for (const part of pasteParts(text)) {
|
||||
if (part.kind === 'text') {
|
||||
if (part.text !== '') segments.push(part)
|
||||
} else {
|
||||
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) })
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -453,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
|
||||
</button>
|
||||
</div>
|
||||
<div class="reply plain">
|
||||
<template v-for="(segment, index) in messageSegments(item.text)" :key="index">
|
||||
<template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
|
||||
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
|
||||
<template v-else>{{ segment.text }}</template>
|
||||
</template>
|
||||
@@ -498,7 +514,6 @@ 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)"
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
// A turn's stream-ordered middle: tool rows, pieces of the thinking
|
||||
// trace, the agent's asks, its handovers — each at the position the
|
||||
// stream delivered it, so an ask sits at the tool call that raised it
|
||||
// and thinking sits between the calls it precedes.
|
||||
// The turn's middle, as the web surface shows it: the agent's asks
|
||||
// (consent cards) and its handovers (attachment cards), each at the
|
||||
// position the stream delivered it. Tool calls and the thinking trace
|
||||
// stay off this surface; the reply is what it shows, and these two
|
||||
// cards are the only things the reader must act on or can open.
|
||||
import { computed } from 'vue'
|
||||
import type { TurnEntry } from '~/composables/useTranscript'
|
||||
import type { ConsentAnswer } from '~/composables/useClaw'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
entries: TurnEntry[]
|
||||
/** A live turn's thinking blocks start expanded; finished ones collapse. */
|
||||
openThinking?: boolean
|
||||
}>()
|
||||
|
||||
/** Cards only: a turn's tool rows and thinking blocks never render. */
|
||||
const cards = computed(() =>
|
||||
props.entries.filter((entry) => entry.kind === 'consent' || entry.kind === 'attachment'),
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
consentAnswer: [id: string, answer: ConsentAnswer]
|
||||
consentDeny: [id: string]
|
||||
@@ -20,21 +25,16 @@ const emit = defineEmits<{
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="entries.length > 0" class="entries">
|
||||
<template v-for="(entry, index) in entries" :key="index">
|
||||
<TurnToolRow v-if="entry.kind === 'tool'" :row="entry.row" />
|
||||
<details v-else-if="entry.kind === 'thinking'" class="thinking" :open="openThinking">
|
||||
<summary>thinking</summary>
|
||||
<pre>{{ entry.text }}</pre>
|
||||
</details>
|
||||
<div v-if="cards.length > 0" class="entries">
|
||||
<template v-for="(entry, index) in cards" :key="index">
|
||||
<TurnConsentCard
|
||||
v-else-if="entry.kind === 'consent'"
|
||||
v-if="entry.kind === 'consent'"
|
||||
:consent="entry.consent"
|
||||
@answer="(id, answer) => emit('consentAnswer', id, answer)"
|
||||
@deny="(id) => emit('consentDeny', id)"
|
||||
/>
|
||||
<TurnAttachmentCard
|
||||
v-else
|
||||
v-else-if="entry.kind === 'attachment'"
|
||||
:attachment="entry.attachment"
|
||||
@download="(id, name) => emit('downloadAttachment', id, name)"
|
||||
/>
|
||||
@@ -49,27 +49,4 @@ const emit = defineEmits<{
|
||||
gap: 4px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.thinking {
|
||||
color: var(--text3);
|
||||
}
|
||||
|
||||
.thinking summary {
|
||||
cursor: pointer;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.thinking pre {
|
||||
margin: 6px 0 0;
|
||||
padding: 8px 10px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text3);
|
||||
font-style: italic;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
</style>
|
||||
@@ -1,102 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
// One tool call in a turn: running, completed, or failed — shell lines
|
||||
// for bash (the TUI's tool_row), glyph rows for everything else.
|
||||
import type { ToolRow } from '~/composables/useTranscript'
|
||||
|
||||
defineProps<{ row: ToolRow }>()
|
||||
|
||||
/** Command rows render as shell lines, not glyph rows; run_command is
|
||||
* the bash tool's other name. */
|
||||
function isShellTool(name: string): boolean {
|
||||
return name === 'bash' || name === 'run_command'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="tool-row" :class="{ error: row.isError === true }">
|
||||
<template v-if="isShellTool(row.name)">
|
||||
<span class="shell-mark" aria-hidden="true">$ </span>
|
||||
<span class="shell-command mono">{{ row.command ?? '…' }}</span>
|
||||
<span
|
||||
v-if="typeof row.code === 'number'"
|
||||
class="shell-code mono"
|
||||
:class="row.code === 0 ? 'ok' : 'failed'"
|
||||
>[{{ row.code }}]</span>
|
||||
<span v-else-if="row.isError === true" class="shell-code failed">✗</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="glyph" aria-hidden="true">{{
|
||||
row.isError === null ? '…' : row.isError ? '✗' : '✓'
|
||||
}}</span>
|
||||
<span class="name mono">{{ row.name }}</span>
|
||||
<span v-if="row.summary" class="summary mono">{{ row.summary }}</span>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tool-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
padding: 5px 10px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-left: 3px solid var(--ok);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.tool-row.error {
|
||||
border-left-color: var(--error);
|
||||
}
|
||||
|
||||
.glyph {
|
||||
flex: none;
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.tool-row.error .glyph {
|
||||
color: var(--error);
|
||||
}
|
||||
|
||||
.name {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.summary {
|
||||
color: var(--text3);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* A bash row reads as the shell line it ran: dim $ prefix, the
|
||||
command, and the exit code pushed to the row's right end. */
|
||||
.shell-mark {
|
||||
flex: none;
|
||||
color: var(--text3);
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.shell-command {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.shell-code {
|
||||
flex: none;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.shell-code.ok {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.shell-code.failed {
|
||||
color: var(--error);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,259 @@
|
||||
<script setup lang="ts">
|
||||
// The Sandbox page: where the agent's `bash` runs. The choice saves as
|
||||
// a whole; the token is write-only, so an empty field keeps whatever
|
||||
// the claw already stored. Presentational: data flows in as props,
|
||||
// intent flows up as events.
|
||||
import type { SandboxKind, SandboxSelection, SandboxState } from '~/composables/useClaw'
|
||||
|
||||
const props = defineProps<{
|
||||
state: SandboxState | null
|
||||
saving: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
save: [choice: SandboxSelection]
|
||||
}>()
|
||||
|
||||
const kind = ref<SandboxKind>('local')
|
||||
const url = ref('')
|
||||
const token = ref('')
|
||||
const clearToken = ref(false)
|
||||
|
||||
const dirty = computed(() => {
|
||||
const state = props.state
|
||||
if (!state) return false
|
||||
if (kind.value !== state.kind) return true
|
||||
if (kind.value !== 'http') return false
|
||||
const normalized = url.value.trim().replace(/\/+$/, '')
|
||||
if (normalized !== (state.url ?? '')) return true
|
||||
return token.value.trim() !== '' || clearToken.value
|
||||
})
|
||||
|
||||
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
|
||||
|
||||
const ready = computed(() => kind.value !== 'http' || urlValid.value)
|
||||
|
||||
const urlHint = computed(() =>
|
||||
url.value.trim() && !urlValid.value
|
||||
? 'The URL must start with http:// or https://.'
|
||||
: 'The sandboxd base URL, for example https://box.example:7600.',
|
||||
)
|
||||
|
||||
function sync(): void {
|
||||
const state = props.state
|
||||
if (!state) return
|
||||
kind.value = state.kind
|
||||
url.value = state.url ?? ''
|
||||
token.value = ''
|
||||
clearToken.value = false
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.state,
|
||||
(state) => {
|
||||
if (state) sync()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function discard(): void {
|
||||
sync()
|
||||
}
|
||||
|
||||
function save(): void {
|
||||
if (!dirty.value || props.saving || !ready.value) return
|
||||
const choice: SandboxSelection = { kind: kind.value }
|
||||
if (kind.value === 'http') {
|
||||
choice.url = url.value.trim()
|
||||
if (token.value.trim() !== '') {
|
||||
choice.token = token.value.trim()
|
||||
} else if (clearToken.value) {
|
||||
choice.clear_token = true
|
||||
}
|
||||
}
|
||||
emit('save', choice)
|
||||
}
|
||||
|
||||
// The path the staged choice would use, not the saved one.
|
||||
const workspacePath = computed(() => {
|
||||
const state = props.state
|
||||
if (!state) return ''
|
||||
return kind.value === 'http' ? state.remote_workspace : state.local_workspace
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="Sandbox" subtitle="Where the agent's bash runs.">
|
||||
<template #actions>
|
||||
<button :disabled="!dirty || saving" @click="discard">Discard</button>
|
||||
<button class="primary" :disabled="!dirty || saving || !ready" @click="save">
|
||||
{{ saving ? 'Saving…' : 'Save' }}
|
||||
</button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="scroll">
|
||||
<p v-if="!state" class="muted">loading sandbox…</p>
|
||||
|
||||
<template v-else>
|
||||
<SettingCard title="Execution" meta="applies on the next turn">
|
||||
<label class="option" :class="{ selected: kind === 'local' }">
|
||||
<input v-model="kind" type="radio" value="local" :disabled="saving" />
|
||||
<span class="option-text">
|
||||
<span class="option-title">
|
||||
This machine
|
||||
<span v-if="state.kind === 'local'" class="current">current</span>
|
||||
</span>
|
||||
<span class="option-detail">
|
||||
Commands run as processes on the daemon's host.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label class="option" :class="{ selected: kind === 'http' }">
|
||||
<input v-model="kind" type="radio" value="http" :disabled="saving" />
|
||||
<span class="option-text">
|
||||
<span class="option-title">
|
||||
Remote sandbox
|
||||
<span v-if="state.kind === 'http'" class="current">current</span>
|
||||
</span>
|
||||
<span class="option-detail">
|
||||
Commands run on a host that speaks the sandbox protocol over HTTP.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</SettingCard>
|
||||
|
||||
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
|
||||
<SettingRow
|
||||
title="URL"
|
||||
:description="urlHint"
|
||||
>
|
||||
<input
|
||||
v-model="url"
|
||||
type="text"
|
||||
class="mono"
|
||||
placeholder="https://box.example:7600"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
title="Token"
|
||||
:description="state.token_set
|
||||
? 'A token is stored. Leave this blank to keep it.'
|
||||
: 'The shared secret the daemon checks. Leave it blank when the daemon has none.'"
|
||||
>
|
||||
<input
|
||||
v-model="token"
|
||||
type="password"
|
||||
:placeholder="state.token_set ? 'stored' : 'optional'"
|
||||
autocomplete="off"
|
||||
:disabled="saving || clearToken"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
v-if="state.token_set"
|
||||
title="Stored token"
|
||||
:description="clearToken
|
||||
? 'The stored token is removed when you save.'
|
||||
: 'The token stays in the settings table until you replace or forget it.'"
|
||||
>
|
||||
<button class="ghost" :disabled="saving" @click="clearToken = !clearToken">
|
||||
{{ clearToken ? 'Keep token' : 'Forget token' }}
|
||||
</button>
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
|
||||
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy">
|
||||
On first use the claw sends the local workspace to the sandbox as a tarball.
|
||||
Later edits stay in the sandbox; the claw does not copy them back.
|
||||
</AppCallout>
|
||||
|
||||
<SettingCard title="Workspace">
|
||||
<SettingRow
|
||||
title="Path"
|
||||
description="Where the agent's bash starts under this choice."
|
||||
>
|
||||
<code>{{ workspacePath }}</code>
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.scroll {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0 24px 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
max-width: 860px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--text3);
|
||||
padding: 8px 2px;
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 13px 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.option:hover {
|
||||
background: var(--elevated);
|
||||
}
|
||||
|
||||
.option.selected {
|
||||
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
|
||||
}
|
||||
|
||||
.option input[type='radio'] {
|
||||
flex: none;
|
||||
margin: 3px 0 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.option-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.option-title {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.option-detail {
|
||||
color: var(--text3);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.current {
|
||||
color: var(--accent-text);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@@ -56,9 +56,20 @@ export interface UserImage {
|
||||
media_type: string
|
||||
}
|
||||
|
||||
/** One paste chip a `user_message` carries: the record the session's
|
||||
* `rhema-code` annotation holds — the byte range in the plain text the
|
||||
* chip stands for (UTF-8 offsets; see useTranscript's
|
||||
* `byteToIndex`), plus the payload's line count for the chip's label
|
||||
* (rhema-core `PasteSpan`). */
|
||||
export interface PasteSpan {
|
||||
start: number
|
||||
end: number
|
||||
lines: number
|
||||
}
|
||||
|
||||
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
|
||||
export type TurnEvent =
|
||||
| { type: 'user_message'; text: string; images: UserImage[] }
|
||||
| { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
|
||||
| { type: 'thinking_delta'; text: string }
|
||||
| { type: 'text_delta'; text: string }
|
||||
| { type: 'tool_start'; name: string }
|
||||
@@ -220,6 +231,34 @@ export interface ActiveBackend {
|
||||
active: { provider: string; model: string }
|
||||
}
|
||||
|
||||
/** Where the agent's `bash` runs: this host or a daemon speaking the
|
||||
* sandbox protocol over HTTP. */
|
||||
export type SandboxKind = 'local' | 'http'
|
||||
|
||||
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
|
||||
* the wire; `token_set` says whether one is stored. */
|
||||
export interface SandboxState {
|
||||
kind: SandboxKind
|
||||
url: string | null
|
||||
token_set: boolean
|
||||
/** Where `bash` starts under the current choice. */
|
||||
workspace: string
|
||||
/** The daemon's chat workspace, whatever the choice. */
|
||||
local_workspace: string
|
||||
/** The path a remote sandbox exposes. */
|
||||
remote_workspace: string
|
||||
}
|
||||
|
||||
/** The body `PUT /v1/sandbox` takes. `token` is write-only, and
|
||||
* `clear_token` drops the stored one. An omitted `url` keeps the
|
||||
* current one. */
|
||||
export interface SandboxSelection {
|
||||
kind: SandboxKind
|
||||
url?: string
|
||||
token?: string
|
||||
clear_token?: boolean
|
||||
}
|
||||
|
||||
/** A failed API call: the status plus the claw's `error` string when it sent one. */
|
||||
export class ClawError extends Error {
|
||||
/** HTTP status; 0 when the claw was unreachable at all. */
|
||||
@@ -240,7 +279,9 @@ const INTERACTIVE_PREFIX = 'interactive:'
|
||||
* connection and reconnects: the claw sends a keep-alive comment every
|
||||
* fifteen seconds (hub.rs), so three missed ones means the path is
|
||||
* black-holed — a half-open TCP after a laptop sleep shows the same
|
||||
* 'live' badge a healthy stream does without this check. */
|
||||
* 'live' badge a healthy stream does without this check. The watchdog
|
||||
* is paused while the tab is hidden: browsers throttle timers and can
|
||||
* stall the reader there, and a tab switch is not a dead stream. */
|
||||
const STREAM_SILENCE_TIMEOUT_MS = 45000
|
||||
|
||||
/** Interactive keys are the only ones message ingest accepts (http.rs `messages`). */
|
||||
@@ -368,8 +409,8 @@ export interface ClawApi {
|
||||
* a plain src will not do). Cached per id: attachments are immutable,
|
||||
* so a replayed event never refetches. */
|
||||
attachmentUrl(id: string): Promise<string>
|
||||
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
|
||||
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void>
|
||||
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
|
||||
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
|
||||
/** `GET /v1/providers` — the constructible backends and the active pair. */
|
||||
providers(): Promise<ProvidersState>
|
||||
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
|
||||
@@ -383,6 +424,11 @@ export interface ClawApi {
|
||||
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers
|
||||
* the new providers state. The last backend is refused claw-side. */
|
||||
removeProvider(id: string): Promise<ProvidersState>
|
||||
/** `GET /v1/sandbox`: where the agent's `bash` runs. */
|
||||
sandbox(): Promise<SandboxState>
|
||||
/** `PUT /v1/sandbox`: switch the sandbox, persisted claw-side. The
|
||||
* choice applies on the next turn. */
|
||||
setSandbox(choice: SandboxSelection): Promise<SandboxState>
|
||||
/** `GET /v1/accounts` — the stored accounts, redacted. */
|
||||
accounts(): Promise<ClawAccount[]>
|
||||
/** `POST /v1/accounts` — store an account (the secret is write-only),
|
||||
@@ -498,11 +544,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
})
|
||||
}
|
||||
|
||||
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> {
|
||||
async function sendMessage(
|
||||
key: string,
|
||||
text: string,
|
||||
pastes?: string[],
|
||||
images?: OutboundImage[],
|
||||
): Promise<void> {
|
||||
const body: { text: string; pastes?: string[]; images?: OutboundImage[] } = { text }
|
||||
if (pastes?.length) body.pastes = pastes
|
||||
if (images?.length) body.images = images
|
||||
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
|
||||
body: JSON.stringify(images?.length ? { text, images } : { text }),
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -563,6 +617,18 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
})) as ProvidersState
|
||||
}
|
||||
|
||||
async function sandbox(): Promise<SandboxState> {
|
||||
return (await get('/v1/sandbox', token.value)) as SandboxState
|
||||
}
|
||||
|
||||
async function setSandbox(choice: SandboxSelection): Promise<SandboxState> {
|
||||
return (await send('/v1/sandbox', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
|
||||
body: JSON.stringify(choice),
|
||||
})) as SandboxState
|
||||
}
|
||||
|
||||
async function accounts(): Promise<ClawAccount[]> {
|
||||
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
|
||||
return body.accounts
|
||||
@@ -639,11 +705,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
* notice says so instead of naming an opaque abort error. */
|
||||
let timedOut = false
|
||||
let silence: ReturnType<typeof setTimeout> | null = null
|
||||
const isHidden = (): boolean =>
|
||||
typeof document !== 'undefined' && document.hidden
|
||||
/** Whether the attempt in flight crossed a hidden tab: a drop there
|
||||
* is a backgrounded connection, not a stream the user needs a notice
|
||||
* about. */
|
||||
let hiddenDuringAttempt = isHidden()
|
||||
|
||||
const rearmSilence = (): void => {
|
||||
if (silence !== null) clearTimeout(silence)
|
||||
silence = null
|
||||
if (closed || isHidden()) return
|
||||
silence = setTimeout(() => {
|
||||
if (closed) return
|
||||
if (closed || isHidden()) return
|
||||
timedOut = true
|
||||
current?.abort()
|
||||
}, STREAM_SILENCE_TIMEOUT_MS)
|
||||
@@ -652,6 +726,23 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
if (silence !== null) clearTimeout(silence)
|
||||
silence = null
|
||||
}
|
||||
/** A frame or keep-alive proved this attempt alive: from here on a
|
||||
* drop is real, even if the tab was hidden earlier. */
|
||||
const noteActivity = (): void => {
|
||||
hiddenDuringAttempt = false
|
||||
rearmSilence()
|
||||
}
|
||||
const visibility = (): void => {
|
||||
if (isHidden()) {
|
||||
hiddenDuringAttempt = true
|
||||
stopSilence()
|
||||
return
|
||||
}
|
||||
if (current !== null && !current.signal.aborted) rearmSilence()
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', visibility)
|
||||
}
|
||||
|
||||
const status = (next: StreamStatus) => {
|
||||
if (!closed) handlers.onStatus?.(next)
|
||||
@@ -663,6 +754,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
const controller = new AbortController()
|
||||
current = controller
|
||||
timedOut = false
|
||||
hiddenDuringAttempt = isHidden()
|
||||
rearmSilence()
|
||||
try {
|
||||
const resume = cursor === null ? '' : `?since=${cursor}`
|
||||
@@ -684,7 +776,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
await readFrames(
|
||||
response.body,
|
||||
(data, id) => {
|
||||
rearmSilence()
|
||||
noteActivity()
|
||||
const event = parseTurnEvent(data)
|
||||
if (!event) return
|
||||
const seq = id !== null && /^\d+$/.test(id) ? Number(id) : null
|
||||
@@ -694,7 +786,7 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
(comment) => {
|
||||
// Keep-alives come through here too; each one proves the
|
||||
// path alive.
|
||||
rearmSilence()
|
||||
noteActivity()
|
||||
// The record lost what this mirror holds: drop the cursor
|
||||
// so the next open asks for the tail, and let the consumer
|
||||
// drop its items before the tail that already followed
|
||||
@@ -720,11 +812,16 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
// Backoff caps at 15s: a live stream of a running turn is the
|
||||
// UI's whole job, so retries stay eager but not tight-looped.
|
||||
const backoff = Math.min(15000, 1000 * 2 ** attempt++)
|
||||
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`,
|
||||
)
|
||||
// A connection that crossed a hidden tab reconnects quietly:
|
||||
// the browser held it while the page was in the background,
|
||||
// and the operator did not just lose a live stream.
|
||||
if (!isHidden() && !hiddenDuringAttempt) {
|
||||
handlers.onNotice?.(
|
||||
timedOut
|
||||
? `the event stream went quiet (no keep-alive for ${STREAM_SILENCE_TIMEOUT_MS / 1000}s); reconnecting in ${backoff / 1000}s`
|
||||
: `event stream dropped (${cause instanceof Error ? cause.message : String(cause)}); retrying in ${backoff / 1000}s`,
|
||||
)
|
||||
}
|
||||
status('reconnecting')
|
||||
await new Promise((resolve) => setTimeout(resolve, backoff))
|
||||
} finally {
|
||||
@@ -738,6 +835,9 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
close() {
|
||||
closed = true
|
||||
stopSilence()
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', visibility)
|
||||
}
|
||||
current?.abort()
|
||||
},
|
||||
}
|
||||
@@ -757,6 +857,8 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
models,
|
||||
setCredentials,
|
||||
removeProvider,
|
||||
sandbox,
|
||||
setSandbox,
|
||||
accounts,
|
||||
addAccount,
|
||||
removeAccount,
|
||||
@@ -836,6 +938,24 @@ function parseUserImages(raw: unknown): UserImage[] {
|
||||
return images
|
||||
}
|
||||
|
||||
/** The paste chips a `user_message` carries: rows recorded before
|
||||
* chips rode as spans carry the mark form in the text instead and no
|
||||
* field at all — empty, the render falls back to scanning — and a
|
||||
* span without whole-number bounds or a line count is not one. */
|
||||
function parseUserPastes(raw: unknown): PasteSpan[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const pastes: PasteSpan[] = []
|
||||
for (const entry of raw) {
|
||||
const span = entry as Record<string, unknown>
|
||||
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
|
||||
if (typeof span.lines !== 'number') continue
|
||||
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
|
||||
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
|
||||
pastes.push({ start: span.start, end: span.end, lines: span.lines })
|
||||
}
|
||||
return pastes
|
||||
}
|
||||
|
||||
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
|
||||
function parseTurnEvent(data: string): TurnEvent | null {
|
||||
try {
|
||||
@@ -846,6 +966,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
|
||||
type: 'user_message',
|
||||
text: String(raw.text ?? ''),
|
||||
images: parseUserImages(raw.images),
|
||||
pastes: parseUserPastes(raw.pastes),
|
||||
}
|
||||
case 'thinking_delta':
|
||||
case 'text_delta':
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// mirror when the stream reopens and folds what arrives, never the other
|
||||
// way around.
|
||||
import { ref } from 'vue'
|
||||
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw'
|
||||
import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
|
||||
|
||||
/** One tool call inside a turn: started, then completed by its result. */
|
||||
export interface ToolRow {
|
||||
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
|
||||
|
||||
/** A transcript line: a message the local user sent, or one streamed turn. */
|
||||
export type TranscriptItem =
|
||||
| { kind: 'sent'; id: number; text: string; images: SentImage[] }
|
||||
| { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
|
||||
| { kind: 'turn'; id: number; turn: TurnBlock }
|
||||
| { kind: 'consent'; id: number; consent: ConsentCard }
|
||||
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
|
||||
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
|
||||
return lines.length
|
||||
}
|
||||
|
||||
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
|
||||
* payload's line count (the TUI's chip_label). */
|
||||
export function chipLabel(paste: string, index: number): string {
|
||||
return `▣${index + 1} ${lineCount(paste)}L`
|
||||
/** A chip's label from its line count: `▣1 5L` — the chip's
|
||||
* one-based id and the payload's line count (the TUI's chip_label). */
|
||||
export function chipLinesLabel(lines: number, index: number): string {
|
||||
return `▣${index + 1} ${lines}L`
|
||||
}
|
||||
|
||||
/** Appends each paste as one MARK-payload-MARK embed, in order — the
|
||||
* session's record of the prompt (paste::embed; a web draft holds no
|
||||
* anchors, so every payload lands at the end). */
|
||||
export function embedPastes(draft: string, pastes: string[]): string {
|
||||
return (
|
||||
draft +
|
||||
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
|
||||
)
|
||||
/** A chip's label from its payload (the TUI's chip_label). */
|
||||
export function chipLabel(paste: string, index: number): string {
|
||||
return chipLinesLabel(lineCount(paste), index)
|
||||
}
|
||||
|
||||
/** The modern record the wire carries: each paste a byte span in the
|
||||
* plain text (the `rhema-code` annotation's own shape), one walk over
|
||||
* the composed text mapping every code-point boundary — a span that
|
||||
* splits a code point maps to none, the render skips it. */
|
||||
export function byteToIndex(text: string): (byte: number) => number {
|
||||
const at = new Map<number, number>([[0, 0]])
|
||||
const bytesOf = new TextEncoder()
|
||||
let bytes = 0
|
||||
let units = 0
|
||||
for (const cp of text) {
|
||||
bytes += bytesOf.encode(cp).length
|
||||
units += cp.length
|
||||
at.set(bytes, units)
|
||||
}
|
||||
return (byte) => at.get(byte) ?? -1
|
||||
}
|
||||
|
||||
/** Composes a send the way the fold composes its record: each paste's
|
||||
* normalized payload appends to the draft, its chip's span measured
|
||||
* over the composed plain text. The same form the `user_message`
|
||||
* echo carries, so the optimistic row and the replay render rows of
|
||||
* one shape and the echo dedupes against what this surface sent. */
|
||||
export function composeChips(
|
||||
draft: string,
|
||||
pastes: string[],
|
||||
): { text: string; pastes: PasteSpan[] } {
|
||||
const bytesOf = new TextEncoder()
|
||||
let text = draft
|
||||
const spans: PasteSpan[] = []
|
||||
for (const paste of pastes) {
|
||||
const payload = normalizePaste(paste)
|
||||
const start = bytesOf.encode(text).length
|
||||
text += payload
|
||||
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
|
||||
}
|
||||
return { text, pastes: spans }
|
||||
}
|
||||
|
||||
/** One scanned piece of embedded-form text. */
|
||||
@@ -244,6 +277,7 @@ export function useTranscript() {
|
||||
id: nextId++,
|
||||
text: event.text,
|
||||
images: event.images.map((image) => ({ ...image, url: null, name: null })),
|
||||
pastes: event.pastes,
|
||||
})
|
||||
break
|
||||
}
|
||||
@@ -356,10 +390,10 @@ export function useTranscript() {
|
||||
* Its images render from the staged previews — the claw stores them
|
||||
* and the stream's echo dedupes against this row. Returns the row's
|
||||
* id, so a failed POST can retract it. */
|
||||
function addSent(text: string, images: SentImage[] = []): number {
|
||||
function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
|
||||
const id = nextId++
|
||||
pendingSent.push({ text, images: images.length, itemId: id })
|
||||
items.value.push({ kind: 'sent', id, text, images })
|
||||
items.value.push({ kind: 'sent', id, text, images, pastes })
|
||||
return id
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user