Grok Build - initial
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
# link-arg
|
||||
# https://pyo3.rs/v0.17.1/building_and_distribution.html#macos
|
||||
|
||||
# force-unwind-tables
|
||||
# https://github.com/rust-lang/backtrace-rs/issues/397
|
||||
|
||||
# rustflags are not additive. we have differing flags per arch,
|
||||
# so we must repeat flags in each target section
|
||||
|
||||
[target.x86_64-apple-darwin]
|
||||
rustflags = [
|
||||
"-C",
|
||||
"link-arg=-undefined",
|
||||
"-C",
|
||||
"link-arg=dynamic_lookup",
|
||||
"-C",
|
||||
"force-unwind-tables=yes",
|
||||
"-C",
|
||||
"link-args=-ObjC",
|
||||
]
|
||||
|
||||
[target.aarch64-apple-darwin]
|
||||
rustflags = [
|
||||
"-C",
|
||||
"link-arg=-undefined",
|
||||
"-C",
|
||||
"link-arg=dynamic_lookup",
|
||||
"-C",
|
||||
"force-unwind-tables=yes",
|
||||
"-C",
|
||||
"link-args=-ObjC",
|
||||
]
|
||||
|
||||
[target.x86_64-unknown-linux-gnu]
|
||||
rustflags = ["-C", "force-unwind-tables=yes"]
|
||||
|
||||
[target.aarch64-unknown-linux-gnu]
|
||||
rustflags = ["-C", "target-cpu=neoverse-v2", "-C", "force-unwind-tables=yes"]
|
||||
|
||||
[target.x86_64-unknown-linux-musl]
|
||||
rustflags = [
|
||||
"-C", "force-unwind-tables=yes",
|
||||
# Binary hardening (SECURITY): Full RELRO + non-executable stack
|
||||
# These flags prevent: GOT overwrite attacks, lazy binding exploits, stack shellcode
|
||||
# IMPORTANT: If changing build system (e.g. from cargo to Bazel-only),
|
||||
# ensure equivalent linker hardening is applied to production binaries.
|
||||
"-C", "link-arg=-Wl,-z,relro,-z,now,-z,noexecstack",
|
||||
]
|
||||
|
||||
[target.aarch64-unknown-linux-musl]
|
||||
rustflags = [
|
||||
"-C", "target-cpu=generic",
|
||||
"-C", "force-unwind-tables=yes",
|
||||
# Binary hardening (SECURITY): Full RELRO + non-executable stack
|
||||
# These flags prevent: GOT overwrite attacks, lazy binding exploits, stack shellcode
|
||||
# IMPORTANT: If changing build system (e.g. from cargo to Bazel-only),
|
||||
# ensure equivalent linker hardening is applied to production binaries.
|
||||
"-C", "link-arg=-Wl,-z,relro,-z,now,-z,noexecstack",
|
||||
]
|
||||
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "force-unwind-tables=yes", "-C", "target-feature=+crt-static"]
|
||||
|
||||
[target.aarch64-pc-windows-msvc]
|
||||
rustflags = ["-C", "force-unwind-tables=yes", "-C", "target-feature=+crt-static"]
|
||||
|
||||
|
||||
# jemalloc page size for Apple Silicon (macOS aarch64 uses 16KB pages = 2^14).
|
||||
# This target-prefixed env var is consumed by tikv-jemalloc-sys's build.rs
|
||||
# and only takes effect when TARGET=aarch64-apple-darwin. Other targets
|
||||
# (x86_64, linux) are unaffected — they check their own prefix first and
|
||||
# fall back to the default 4KB page size.
|
||||
# Some aarch64 Linux hosts use 64KB kernel pages = 2^16; set the matching
|
||||
# env vars below for those platforms.
|
||||
# See: https://github.com/tikv/jemallocator/issues/122
|
||||
[env]
|
||||
SYSTEM_DEPS_DAV1D_BUILD_INTERNAL = "auto"
|
||||
AARCH64_APPLE_DARWIN_JEMALLOC_SYS_WITH_LG_PAGE = "14"
|
||||
AARCH64_UNKNOWN_LINUX_GNU_JEMALLOC_SYS_WITH_LG_PAGE = "16"
|
||||
AARCH64_UNKNOWN_LINUX_MUSL_JEMALLOC_SYS_WITH_LG_PAGE = "16"
|
||||
AARCH64_UNKNOWN_LINUX_MUSL_JEMALLOC_SYS_WITH_BACKGROUND_THREADS = "0"
|
||||
@@ -0,0 +1,3 @@
|
||||
/target
|
||||
**/*.rs.bk
|
||||
.DS_Store
|
||||
@@ -0,0 +1,19 @@
|
||||
# Contributing
|
||||
|
||||
This repository does **not** accept external pull requests or unsolicited
|
||||
patches.
|
||||
|
||||
SpaceXAI develops this software internally. The public tree is published for
|
||||
source transparency and local builds under the terms of the Apache License,
|
||||
Version 2.0 (see [`LICENSE`](LICENSE)).
|
||||
|
||||
## Security reports
|
||||
|
||||
Please report security issues through the process described in
|
||||
[`SECURITY.md`](SECURITY.md). Do not open a public issue for vulnerabilities.
|
||||
|
||||
## Licensing of this source
|
||||
|
||||
By downloading or using this source, you agree that your use is governed by
|
||||
the Apache License, Version 2.0. No contributor license agreement is offered
|
||||
because external contributions are not accepted.
|
||||
Generated
+14768
File diff suppressed because it is too large
Load Diff
+403
@@ -0,0 +1,403 @@
|
||||
# Auto-generated workspace root. Prefer editing per-crate Cargo.toml files.
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"crates/build/xai-proto-build",
|
||||
"crates/codegen/ptyctl",
|
||||
"crates/codegen/ptyctl-cli",
|
||||
"crates/codegen/xai-acp-lib",
|
||||
"crates/codegen/xai-agent-lifecycle",
|
||||
"crates/codegen/xai-chat-state",
|
||||
"crates/codegen/xai-codebase-graph",
|
||||
"crates/codegen/xai-crash-handler",
|
||||
"crates/codegen/xai-fast-worktree",
|
||||
"crates/codegen/xai-file-utils",
|
||||
"crates/codegen/xai-fsnotify",
|
||||
"crates/codegen/xai-gix-status",
|
||||
"crates/codegen/xai-grok-agent",
|
||||
"crates/codegen/xai-grok-announcements",
|
||||
"crates/codegen/xai-grok-auth",
|
||||
"crates/codegen/xai-grok-config",
|
||||
"crates/codegen/xai-grok-config-types",
|
||||
"crates/codegen/xai-grok-env",
|
||||
"crates/codegen/xai-grok-hooks",
|
||||
"crates/codegen/xai-grok-http",
|
||||
"crates/codegen/xai-grok-markdown",
|
||||
"crates/codegen/xai-grok-markdown-core",
|
||||
"crates/codegen/xai-grok-mcp",
|
||||
"crates/codegen/xai-grok-memory",
|
||||
"crates/codegen/xai-grok-mermaid",
|
||||
"crates/codegen/xai-grok-models",
|
||||
"crates/codegen/xai-grok-pager",
|
||||
"crates/codegen/xai-grok-pager-bin",
|
||||
"crates/codegen/xai-grok-pager-minimal",
|
||||
"crates/codegen/xai-grok-pager-pty-harness",
|
||||
"crates/codegen/xai-grok-pager-render",
|
||||
"crates/codegen/xai-grok-paths",
|
||||
"crates/codegen/xai-grok-plugin-marketplace",
|
||||
"crates/codegen/xai-grok-sampler",
|
||||
"crates/codegen/xai-grok-sampling-types",
|
||||
"crates/codegen/xai-grok-sandbox",
|
||||
"crates/codegen/xai-grok-secrets",
|
||||
"crates/codegen/xai-grok-shared",
|
||||
"crates/codegen/xai-grok-shell",
|
||||
"crates/codegen/xai-grok-shell-base",
|
||||
"crates/codegen/xai-grok-shell-session-support",
|
||||
"crates/codegen/xai-grok-subagent-resolution",
|
||||
"crates/codegen/xai-grok-telemetry",
|
||||
"crates/codegen/xai-grok-test-support",
|
||||
"crates/codegen/xai-grok-tools",
|
||||
"crates/codegen/xai-grok-tools-api",
|
||||
"crates/codegen/xai-grok-update",
|
||||
"crates/codegen/xai-grok-version",
|
||||
"crates/codegen/xai-grok-voice",
|
||||
"crates/codegen/xai-grok-workspace",
|
||||
"crates/codegen/xai-grok-workspace-client",
|
||||
"crates/codegen/xai-grok-workspace-types",
|
||||
"crates/codegen/xai-hooks-plugins-types",
|
||||
"crates/codegen/xai-hunk-tracker",
|
||||
"crates/codegen/xai-mixpanel",
|
||||
"crates/codegen/xai-prompt-queue",
|
||||
"crates/codegen/xai-ratatui-inline",
|
||||
"crates/codegen/xai-ratatui-textarea",
|
||||
"crates/codegen/xai-sqlite-journal",
|
||||
"crates/codegen/xai-system-power",
|
||||
"crates/codegen/xai-token-estimation",
|
||||
"crates/codegen/xai-tracing-macros",
|
||||
"crates/codegen/xai-tty-utils",
|
||||
"crates/common/xai-circuit-breaker",
|
||||
"crates/common/xai-computer-hub-core",
|
||||
"crates/common/xai-computer-hub-mcp-adapter",
|
||||
"crates/common/xai-computer-hub-sdk",
|
||||
"crates/common/xai-grok-compaction",
|
||||
"crates/common/xai-interjection-core",
|
||||
"crates/common/xai-test-utils",
|
||||
"crates/common/xai-tool-protocol",
|
||||
"crates/common/xai-tool-runtime",
|
||||
"crates/common/xai-tool-types",
|
||||
"crates/common/xai-tracing",
|
||||
"prod/mc/cli-chat-proxy-types",
|
||||
"third_party/dagre_rust",
|
||||
"third_party/graphlib_rust",
|
||||
"third_party/mermaid-to-svg",
|
||||
"third_party/ordered_hashmap",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
agent-client-protocol = { version = "0.10.4", features = ["unstable"] }
|
||||
alacritty_terminal = "0.26.0"
|
||||
ansi-to-tui = "7.0.0"
|
||||
ansi-width = "0.1"
|
||||
anstyle = "1.0"
|
||||
anstyle-lossy = "1.1.4"
|
||||
anstyle-parse = "0.2"
|
||||
anstyle-syntect = "1.0.4"
|
||||
anyhow = { version = "1", features = ["backtrace"] }
|
||||
arboard = "3.6"
|
||||
arc-swap = "1.7"
|
||||
assert_matches = "1.5.0"
|
||||
async-compression = { version = "0.4.17", default-features = false, features = ["gzip", "zstd", "tokio"] }
|
||||
async-lsp = { version = "0.2.3", features = ["tokio", "tracing"] }
|
||||
async-openai = { version = "0.33.0", features = ["responses"] }
|
||||
async-stream = "0.3"
|
||||
async-trait = "0.1"
|
||||
axum = { version = "0.8", features = ["macros", "ws"] }
|
||||
backon = { version = "1.6" }
|
||||
backtrace = "0.3"
|
||||
base64 = "0.22"
|
||||
blake3 = "1"
|
||||
bytes = { version = "1", features = ["serde"] }
|
||||
camino = "1.1.10"
|
||||
chrono = "0.4"
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = { version = "4" }
|
||||
colored_json = "5"
|
||||
core-foundation = "0.10"
|
||||
crc32fast = "1.4"
|
||||
criterion = "0.6"
|
||||
crossbeam = "0.8"
|
||||
crossterm = "0.28"
|
||||
cryptify = "3.2"
|
||||
dashmap = "6"
|
||||
derive_more = { version = "2", features = ["add", "add_assign", "debug", "deref", "deref_mut", "display", "from", "from_str", "into", "into_iterator", "try_into"] }
|
||||
dhat = "0.3"
|
||||
dirs = "5.0"
|
||||
documented = "0.9"
|
||||
dunce = "1"
|
||||
educe = "0.6.0"
|
||||
enum_delegate = "0.2"
|
||||
env_logger = "0.11"
|
||||
eventsource-stream = "0.2"
|
||||
fastrace = { version = "0.7" }
|
||||
fastrace-opentelemetry = { version = "0.18" }
|
||||
fastrace-reqwest = { version = "0.2" }
|
||||
fastrace-tonic = { version = "0.1" }
|
||||
fastrand = "2"
|
||||
filetime = "0.2.25"
|
||||
flate2 = { version = "1", default-features = false, features = ["zlib-rs"] }
|
||||
fontdb = "0.23"
|
||||
fs2 = "0.4"
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
fuzzy-matcher = "0.3.7"
|
||||
gcloud-storage = { version = "1.3.0", default-features = false, features = ["auth", "jwt-aws-lc-rs", "external-account"] }
|
||||
gethostname = "1"
|
||||
gix = { version = "0.83", default-features = false, features = ["sha1"] }
|
||||
glob = "0.3"
|
||||
globset = "0.4"
|
||||
htmd = "0.5.4"
|
||||
html-escape = "0.2"
|
||||
http = "1"
|
||||
http-body-util = "0.1"
|
||||
humantime-serde = "1"
|
||||
ignore = "0.4"
|
||||
image = { version = "0.25.9", default-features = false }
|
||||
indexmap = { version = "2", features = ["serde"] }
|
||||
indicatif = "0.18"
|
||||
infer = "0.19.0"
|
||||
insta = "1"
|
||||
itertools = "0.14"
|
||||
jsonschema = "0.30.0"
|
||||
libc = "0.2"
|
||||
linkify = "0.10"
|
||||
lipsum = "0.9"
|
||||
log = { version = "0.4", features = ["kv", "kv_unstable"] }
|
||||
md5 = "0.8"
|
||||
mermaid-to-svg = { path = "third_party/mermaid-to-svg" }
|
||||
minijinja = "2.9"
|
||||
mockito = "1"
|
||||
moka = "0.12"
|
||||
nix = { version = "0.30", features = ["poll", "process", "signal", "sched", "term", "mount", "fs", "ioctl", "mman", "reboot", "user"] }
|
||||
notify = "8"
|
||||
notify-debouncer-mini = "0.6"
|
||||
nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "5b74652" }
|
||||
num_cpus = "1"
|
||||
oauth2 = "5"
|
||||
obfstr = "0.4"
|
||||
once_cell = "1"
|
||||
opentelemetry = "0.32"
|
||||
opentelemetry-http = { version = "0.32", features = ["reqwest-blocking"] }
|
||||
opentelemetry-otlp = { version = "0.32", features = ["grpc-tonic", "reqwest-blocking-client", "tls-roots"] }
|
||||
opentelemetry-proto = { version = "0.32", features = ["gen-tonic"] }
|
||||
opentelemetry_sdk = { version = "0.32.1", features = ["spec_unstable_metrics_views"] }
|
||||
parking_lot = "0.12.4"
|
||||
pbjson-build = "0.9"
|
||||
pdf_oxide = { version = "0.3.43", features = ["rendering"] }
|
||||
petgraph = { version = "0.6.5", default-features = false, features = ["serde-1", "stable_graph"] }
|
||||
portable-pty = "0.9"
|
||||
pprof = "0.15"
|
||||
pretty_assertions = "1"
|
||||
prometheus = { version = "0.14", features = ["process"] }
|
||||
prost = "0.14"
|
||||
prost-build = "0.14"
|
||||
pulldown-cmark = "0.13"
|
||||
quick-xml = "0.38"
|
||||
rand = "0.9"
|
||||
ratatui = { version = "0.29" }
|
||||
ratatui-core = "0.1"
|
||||
rayon = "1"
|
||||
reflink-copy = "0.1"
|
||||
regex = "1"
|
||||
reqwest = { version = "0.12", features = ["rustls-tls", "stream", "json", "multipart", "http2", "blocking", "socks"], default-features = false }
|
||||
reqwest-middleware = { version = "0.4.1", features = ["json", "multipart"] }
|
||||
resvg = { version = "0.47", default-features = false, features = ["text"] }
|
||||
ring = "0.17"
|
||||
rsa = "0.9"
|
||||
runfiles = "0.1"
|
||||
rustc-hash = "2"
|
||||
schemars = "1"
|
||||
scraper = "0.23"
|
||||
semver = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_path_to_error = "0.1"
|
||||
serde_yaml = "0.9"
|
||||
serial_test = "3"
|
||||
sha2 = { version = "0.10", features = ["force-soft"] }
|
||||
shlex = "1"
|
||||
signal-hook = "0.3"
|
||||
similar = "2.7"
|
||||
siphasher = "1"
|
||||
smallvec = "1"
|
||||
strip-ansi-escapes = "0.2.1"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
supports-color = "3.0"
|
||||
syntect = "5.3"
|
||||
tar = "0.4"
|
||||
tempfile = "3"
|
||||
terminput = "0.3"
|
||||
termwiz = { version = "0.23", default-features = false }
|
||||
textwrap = "0.16"
|
||||
thiserror = "2"
|
||||
tikv-jemalloc-ctl = "0.6"
|
||||
tikv-jemalloc-sys = "0.6"
|
||||
tikv-jemallocator = { version = "0.6", features = ["profiling", "unprefixed_malloc_on_supported_platforms"] }
|
||||
time = "0.3"
|
||||
tiny-skia = "0.12"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-retry = "0.3"
|
||||
tokio-stream = "0.1"
|
||||
tokio-tungstenite = "0.27"
|
||||
tokio-util = { version = "0.7", features = ["rt"] }
|
||||
toml = "0.9"
|
||||
toml_edit = "0.22"
|
||||
tonic = { version = "0.14", features = ["tls-aws-lc", "gzip", "deflate", "zstd"] }
|
||||
tonic-prost = "0.14"
|
||||
tonic-prost-build = "0.14"
|
||||
tower = "0.5"
|
||||
tower-http = "0.6"
|
||||
tracing = "0.1"
|
||||
tracing-opentelemetry = "0.33"
|
||||
tracing-subscriber = { version = "0.3.23", default-features = false, features = ["env-filter", "smallvec", "tracing-log", "std", "ansi"] }
|
||||
ts-rs = "12.0"
|
||||
tui-scrollbar = "0.2"
|
||||
two-face = { version = "0.4", default-features = false, features = ["syntect-fancy"] }
|
||||
unicode-segmentation = "1.12.0"
|
||||
unicode-width = "0.2"
|
||||
url = "2"
|
||||
urlencoding = "2"
|
||||
uuid = { version = "1", features = ["serde", "v4", "v5"] }
|
||||
vte = "0.15.0"
|
||||
wait-timeout = "0.2"
|
||||
walkdir = "2"
|
||||
webbrowser = { version = "1.0.4" }
|
||||
which = "8"
|
||||
whoami = "1.4"
|
||||
windows = { version = "0.61", features = ["Win32_Security", "Win32_Security_Authorization", "Win32_Foundation", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_Console", "Win32_System_Pipes"] }
|
||||
wiremock = "0.6"
|
||||
wl-clipboard-rs = "0.9"
|
||||
xai-acp-lib = { path = "crates/codegen/xai-acp-lib" }
|
||||
xai-agent-lifecycle = { path = "crates/codegen/xai-agent-lifecycle" }
|
||||
xai-circuit-breaker = { path = "crates/common/xai-circuit-breaker" }
|
||||
xai-computer-hub-core = { path = "crates/common/xai-computer-hub-core" }
|
||||
xai-computer-hub-sdk = { path = "crates/common/xai-computer-hub-sdk" }
|
||||
xai-gix-status = { path = "crates/codegen/xai-gix-status" }
|
||||
xai-grok-agent = { path = "crates/codegen/xai-grok-agent" }
|
||||
xai-grok-announcements = { path = "crates/codegen/xai-grok-announcements" }
|
||||
xai-grok-auth = { path = "crates/codegen/xai-grok-auth" }
|
||||
xai-grok-config = { path = "crates/codegen/xai-grok-config" }
|
||||
xai-grok-config-types = { path = "crates/codegen/xai-grok-config-types" }
|
||||
xai-grok-env = { path = "crates/codegen/xai-grok-env" }
|
||||
xai-grok-http = { path = "crates/codegen/xai-grok-http" }
|
||||
xai-grok-markdown = { path = "crates/codegen/xai-grok-markdown" }
|
||||
xai-grok-markdown-core = { path = "crates/codegen/xai-grok-markdown-core" }
|
||||
xai-grok-mcp = { path = "crates/codegen/xai-grok-mcp" }
|
||||
xai-grok-memory = { path = "crates/codegen/xai-grok-memory" }
|
||||
xai-grok-mermaid = { path = "crates/codegen/xai-grok-mermaid" }
|
||||
xai-grok-models = { path = "crates/codegen/xai-grok-models" }
|
||||
xai-grok-sampler = { path = "crates/codegen/xai-grok-sampler" }
|
||||
xai-grok-secrets = { path = "crates/codegen/xai-grok-secrets" }
|
||||
xai-grok-shared = { path = "crates/codegen/xai-grok-shared" }
|
||||
xai-grok-shell = { path = "crates/codegen/xai-grok-shell" }
|
||||
xai-grok-shell-base = { path = "crates/codegen/xai-grok-shell-base" }
|
||||
xai-grok-shell-session-support = { path = "crates/codegen/xai-grok-shell-session-support" }
|
||||
xai-grok-telemetry = { path = "crates/codegen/xai-grok-telemetry" }
|
||||
xai-grok-test-support = { path = "crates/codegen/xai-grok-test-support" }
|
||||
xai-grok-tools = { path = "crates/codegen/xai-grok-tools" }
|
||||
xai-grok-tools-api = { path = "crates/codegen/xai-grok-tools-api" }
|
||||
xai-grok-version = { path = "crates/codegen/xai-grok-version" }
|
||||
xai-grok-workspace = { path = "crates/codegen/xai-grok-workspace" }
|
||||
xai-grok-workspace-types = { path = "crates/codegen/xai-grok-workspace-types" }
|
||||
xai-hooks-plugins-types = { path = "crates/codegen/xai-hooks-plugins-types" }
|
||||
xai-interjection-core = { path = "crates/common/xai-interjection-core" }
|
||||
xai-mixpanel = { path = "crates/codegen/xai-mixpanel" }
|
||||
xai-prompt-queue = { path = "crates/codegen/xai-prompt-queue" }
|
||||
xai-proto-build = { path = "crates/build/xai-proto-build" }
|
||||
xai-ratatui-inline = { path = "crates/codegen/xai-ratatui-inline" }
|
||||
xai-ratatui-textarea = { path = "crates/codegen/xai-ratatui-textarea" }
|
||||
xai-sqlite-journal = { path = "crates/codegen/xai-sqlite-journal" }
|
||||
xai-system-power = { path = "crates/codegen/xai-system-power" }
|
||||
xai-test-utils = { path = "crates/common/xai-test-utils" }
|
||||
xai-token-estimation = { path = "crates/codegen/xai-token-estimation" }
|
||||
xai-tool-protocol = { path = "crates/common/xai-tool-protocol" }
|
||||
xai-tool-runtime = { path = "crates/common/xai-tool-runtime" }
|
||||
xai-tool-types = { path = "crates/common/xai-tool-types" }
|
||||
xai-tracing = { path = "crates/common/xai-tracing" }
|
||||
xai-tty-utils = { path = "crates/codegen/xai-tty-utils" }
|
||||
zbus = { version = "5" }
|
||||
zstd = "0.13"
|
||||
|
||||
[profile.release]
|
||||
incremental = true
|
||||
panic = "abort"
|
||||
|
||||
# Hardened release profile for shipping to end users (alpha + stable).
|
||||
# Use `cargo build --profile release-dist` for distribution builds.
|
||||
# Not used by default `--release` to avoid slowing down local dev builds (~2.2x).
|
||||
#
|
||||
# Hardening: thin LTO for cross-crate optimization with reasonable link times,
|
||||
# codegen-units=1 maximizes optimization (whole-program analysis, no CGU boundaries).
|
||||
# debug=1 emits line-tables DWARF; strip=false keeps symbols so CI can extract
|
||||
# .debug sidecars (Linux) or .dSYM bundles (macOS) before stripping post-build.
|
||||
# Linker flags (RELRO, NX stack) are set per-target in .cargo/config.toml.
|
||||
[profile.release-dist]
|
||||
inherits = "release"
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
strip = false
|
||||
debug = 1
|
||||
split-debuginfo = "off"
|
||||
|
||||
# Production profile for latency-sensitive x-product services (VF, home-mixer).
|
||||
# Thin LTO gives ~90% of full LTO benefit at significantly faster link time.
|
||||
# Keeps symbols + line tables for prod debuggability (perf, flamegraph, stack traces).
|
||||
[profile.x-prod]
|
||||
inherits = "release"
|
||||
lto = "thin"
|
||||
strip = false
|
||||
codegen-units = 1
|
||||
debug = "line-tables-only"
|
||||
panic = "unwind"
|
||||
|
||||
# Desktop release profile. Functionally identical to release-dist — kept as a
|
||||
# named alias so the desktop workflow can reference it without coupling to the
|
||||
# CLI pipeline's profile name. Alpha and stable share a single release-dist
|
||||
# profile so that stable promotion can pointer-swap the alpha binary without
|
||||
# rebuilding.
|
||||
[profile.release-dist-jemalloc]
|
||||
inherits = "release-dist"
|
||||
# All settings now match the parent — this is an intentional alias.
|
||||
|
||||
|
||||
[profile.dev]
|
||||
panic = "abort"
|
||||
split-debuginfo = "unpacked"
|
||||
codegen-units = 128
|
||||
debug = "line-tables-only"
|
||||
opt-level = 0
|
||||
lto = false
|
||||
incremental = true
|
||||
|
||||
[profile.bench]
|
||||
debug = true
|
||||
|
||||
[workspace.lints.clippy]
|
||||
# prost 0.14 renders proto doc-comment bullet lists in a way that trips this
|
||||
# lint on generated code. Kept in sync with bazel/lint/linters.bzl.
|
||||
doc_lazy_continuation = "allow"
|
||||
doc_overindented_list_items = "allow"
|
||||
needless_lifetimes = "allow"
|
||||
single_range_in_vec_init = "allow"
|
||||
too_many_arguments = "allow"
|
||||
|
||||
# Allow uninlined_format_args lint to prevent main from breaking after merges
|
||||
# When older branches (created before this lint was added to CI) get merged,
|
||||
# they pass their own CI because their CI config doesn't include this lint check.
|
||||
# However, once merged to main, the code violates main's lint rules, causing:
|
||||
# 1. Main's CI to fail
|
||||
# 2. All new branches based off main to fail CI
|
||||
# 3. Developers having to fix lint violations from other people's merged code
|
||||
# Without a merge-queue that runs main's CI checks on the PR branch,
|
||||
# these violations slip through and break the build for everyone.
|
||||
# TODO: -> "deny" once/if merge queue enabled
|
||||
uninlined_format_args = "allow"
|
||||
|
||||
# The `fastrace::trace(properties = { … })` proc-macro expands `"{param}"`
|
||||
# into `format!("{}", param)`, which clippy flags as useless_format.
|
||||
# Suppressed until the upstream crate fixes its codegen (fixed in 0.7.16+).
|
||||
useless_format = "allow"
|
||||
@@ -0,0 +1,204 @@
|
||||
Copyright 2023-2026 SpaceXAI
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,140 @@
|
||||
<div align="center">
|
||||
|
||||
<h1>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://media.x.ai/v1/website/spacexai-symbol-white-transparent-0c31957f.png">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://media.x.ai/v1/website/spacexai-symbol-black-transparent-6435cf42.png">
|
||||
<img alt="SpaceXAI logo" src="https://media.x.ai/v1/website/spacexai-symbol-black-transparent-6435cf42.png" width="96">
|
||||
</picture>
|
||||
<br>
|
||||
Grok Build (<code>grok</code>)
|
||||
</h1>
|
||||
|
||||
**Grok Build** is SpaceXAI's terminal-based AI coding agent. It runs as a
|
||||
full-screen TUI that understands your codebase, edits files, executes shell
|
||||
commands, searches the web, and manages long-running tasks — interactively,
|
||||
headlessly for scripting/CI, or embedded in editors via the Agent Client
|
||||
Protocol (ACP).
|
||||
|
||||
[Installing the released binary](#installing-the-released-binary) ·
|
||||
[Building from source](#building-from-source) ·
|
||||
[Documentation](#documentation) ·
|
||||
[Repository layout](#repository-layout) ·
|
||||
[Development](#development) ·
|
||||
[Contributing](#contributing) ·
|
||||
[License](#license)
|
||||
|
||||

|
||||
|
||||
**Learn more about Grok Build at [x.ai/cli](https://x.ai/cli)**
|
||||
|
||||
This repository contains the Rust source for the `grok` CLI/TUI and its agent
|
||||
runtime. It is synced periodically from the SpaceXAI monorepo.
|
||||
|
||||
A small `SOURCE_REV` file at the root records the full monorepo commit SHA
|
||||
for the version of the code present in this tree.
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Installing the released binary
|
||||
|
||||
Prebuilt binaries are published for macOS, Linux, and Windows:
|
||||
|
||||
```sh
|
||||
curl -fsSL https://x.ai/cli/install.sh | bash # macOS / Linux / Git Bash
|
||||
irm https://x.ai/cli/install.ps1 | iex # Windows PowerShell
|
||||
grok --version
|
||||
```
|
||||
|
||||
See the [changelog](https://x.ai/build/changelog) for the latest fixes,
|
||||
features, and improvements in each release.
|
||||
|
||||
## Building from source
|
||||
|
||||
Requirements:
|
||||
|
||||
- **Rust** — the toolchain is pinned by [`rust-toolchain.toml`](rust-toolchain.toml);
|
||||
`rustup` installs it automatically on first build.
|
||||
- **[DotSlash](https://dotslash-cli.com)** — required so hermetic tools under
|
||||
[`bin/`](bin/) (notably [`bin/protoc`](bin/protoc)) can download and run.
|
||||
Install it and ensure `dotslash` is on your `PATH` **before** building:
|
||||
|
||||
```sh
|
||||
cargo install dotslash
|
||||
# or: prebuilt packages — https://dotslash-cli.com/docs/installation/
|
||||
/usr/bin/env dotslash --help # sanity check
|
||||
```
|
||||
|
||||
- **protoc** — proto codegen resolves [`bin/protoc`](bin/protoc) via DotSlash,
|
||||
or falls back to a `protoc` on `PATH` / `$PROTOC`.
|
||||
- macOS and Linux are supported build hosts; Windows builds are best-effort
|
||||
and not currently tested from this tree.
|
||||
|
||||
```sh
|
||||
cargo run -p xai-grok-pager-bin # build + launch the TUI
|
||||
cargo build -p xai-grok-pager-bin --release # release binary: target/release/xai-grok-pager
|
||||
cargo check -p xai-grok-pager-bin # fast validation
|
||||
```
|
||||
|
||||
The binary artifact is named `xai-grok-pager`; official installs ship it as
|
||||
`grok`. On first launch it opens your browser to authenticate — see the
|
||||
[authentication guide](crates/codegen/xai-grok-pager/docs/user-guide/02-authentication.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
Full online documentation is available at
|
||||
[docs.x.ai/build/overview](https://docs.x.ai/build/overview).
|
||||
|
||||
The user guide ships with the pager crate:
|
||||
[`crates/codegen/xai-grok-pager/docs/user-guide/`](crates/codegen/xai-grok-pager/docs/user-guide/)
|
||||
— getting started, keyboard shortcuts, slash commands, configuration, theming,
|
||||
MCP servers, skills, plugins, hooks, headless mode, sandboxing, and more.
|
||||
|
||||
## Repository layout
|
||||
|
||||
| Path | Contents |
|
||||
|------|----------|
|
||||
| `crates/codegen/xai-grok-pager-bin` | Composition-root package; builds the `xai-grok-pager` binary |
|
||||
| `crates/codegen/xai-grok-pager` | The TUI: scrollback, prompt, modals, rendering |
|
||||
| `crates/codegen/xai-grok-shell` | Agent runtime + leader/stdio/headless entry points |
|
||||
| `crates/codegen/xai-grok-tools` | Tool implementations (terminal, file edit, search, ...) |
|
||||
| `crates/codegen/xai-grok-workspace` | Host filesystem, VCS, execution, checkpoints |
|
||||
| `crates/codegen/...` | The rest of the CLI crate closure (config, MCP, markdown, sandbox, ...) |
|
||||
| `crates/common/`, `crates/build/`, `prod/mc/` | Small shared leaf crates pulled in by the closure |
|
||||
| `third_party/` | Vendored upstream source (Mermaid diagram stack) — see below |
|
||||
|
||||
> [!IMPORTANT]
|
||||
> The root `Cargo.toml` (workspace members, dependency versions, lints,
|
||||
> profiles) is **generated** — treat it as read-only. Prefer editing per-crate
|
||||
> `Cargo.toml` files.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
cargo check -p <crate> # always target specific crates; full-workspace builds are slow
|
||||
cargo test -p xai-grok-config # per-crate tests
|
||||
cargo clippy -p <crate> # lint config: clippy.toml at the repo root
|
||||
cargo fmt --all # rustfmt.toml at the repo root
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
> [!NOTE]
|
||||
> External contributions are not accepted. See [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
## License
|
||||
|
||||
First-party code in this repository is licensed under the **Apache License,
|
||||
Version 2.0** — see [`LICENSE`](LICENSE).
|
||||
|
||||
Third-party and vendored code remains under its original licenses. See:
|
||||
|
||||
- [`THIRD-PARTY-NOTICES`](THIRD-PARTY-NOTICES) — crates.io / git dependencies,
|
||||
bundled UI themes, and **in-tree source ports** (including openai/codex and
|
||||
sst/opencode tool implementations)
|
||||
- [`crates/codegen/xai-grok-tools/THIRD_PARTY_NOTICES.md`](crates/codegen/xai-grok-tools/THIRD_PARTY_NOTICES.md)
|
||||
— crate-local notice for the codex and opencode ports (license texts +
|
||||
Apache §4(b) change notice)
|
||||
- [`third_party/NOTICE`](third_party/NOTICE) — vendored Mermaid-stack index
|
||||
@@ -0,0 +1,7 @@
|
||||
# Security Policy
|
||||
|
||||
Please report security vulnerabilities via our HackerOne program:
|
||||
|
||||
https://hackerone.com/x
|
||||
|
||||
Do not open public GitHub issues for security reports.
|
||||
@@ -0,0 +1 @@
|
||||
c5c4ce03436b4bb2cec43d3feaa27dee0109bf37
|
||||
+18898
File diff suppressed because it is too large
Load Diff
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env dotslash
|
||||
|
||||
{
|
||||
"name": "protoc",
|
||||
"platforms": {
|
||||
"macos-aarch64": {
|
||||
"arg0": "underlying-executable",
|
||||
"size": 2290929,
|
||||
"hash": "sha256",
|
||||
"digest": "2b8a3403cd097f95f3ba656e14b76c732b6b26d7f183330b11e36ef2bc028765",
|
||||
"format": "zip",
|
||||
"path": "bin/protoc",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/protocolbuffers/protobuf/releases/download/v29.3/protoc-29.3-osx-aarch_64.zip"
|
||||
}
|
||||
]
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"arg0": "underlying-executable",
|
||||
"size": 3288836,
|
||||
"hash": "sha256",
|
||||
"digest": "3e866620c5be27664f3d2fa2d656b5f3e09b5152b42f1bedbf427b333e90021a",
|
||||
"format": "zip",
|
||||
"path": "bin/protoc",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/protocolbuffers/protobuf/releases/download/v29.3/protoc-29.3-linux-x86_64.zip"
|
||||
}
|
||||
]
|
||||
},
|
||||
"linux-aarch64": {
|
||||
"arg0": "underlying-executable",
|
||||
"size": 3256816,
|
||||
"hash": "sha256",
|
||||
"digest": "6427349140e01f06e049e707a58709a4f221ae73ab9a0425bc4a00c8d0e1ab32",
|
||||
"format": "zip",
|
||||
"path": "bin/protoc",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/protocolbuffers/protobuf/releases/download/v29.3/protoc-29.3-linux-aarch_64.zip"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# Clippy config for crates/codegen/**.
|
||||
#
|
||||
# NOTE: clippy uses the NEAREST clippy.toml (no merging), so this file must
|
||||
# duplicate any settings from the repo-root //clippy.toml.
|
||||
|
||||
# TODO: remove after https://github.com/hyperium/tonic/issues/2253 fixed.
|
||||
large-error-threshold = 256
|
||||
|
||||
# Ban raw canonicalize: on Windows, std/tokio canonicalize return verbatim
|
||||
# `\\?\C:\...` paths that break external tools (git rejects them as clone
|
||||
# destinations), leak into model prompt context, and poison path-equality
|
||||
# keys. Use `dunce::canonicalize` (identical to std on Unix/macOS; strips the
|
||||
# verbatim prefix on Windows when safely representable). For async contexts
|
||||
# in xai-grok-tools, use the blessed helpers in `crate::util::fs`.
|
||||
#
|
||||
# Caveat: dunce keeps the verbatim form for paths it cannot safely simplify
|
||||
# (notably > 260 chars or reserved device names), so prefix checks between two
|
||||
# independently canonicalized paths can mismatch on Windows for very long
|
||||
# paths (containment checks then fail closed).
|
||||
#
|
||||
# Enforcement boundary: this ban is applied by the per-crate cargo clippy
|
||||
# presubmits only — the Bazel lint aspect pins the repo-root //:clippy.toml,
|
||||
# so Bazel-only crates (currently xai-coding-env) need manual vigilance.
|
||||
disallowed-methods = [
|
||||
{ path = "std::fs::canonicalize", reason = "returns \\\\?\\ verbatim paths on Windows; use dunce::canonicalize" },
|
||||
{ path = "std::path::Path::canonicalize", reason = "returns \\\\?\\ verbatim paths on Windows; use dunce::canonicalize" },
|
||||
{ path = "tokio::fs::canonicalize", reason = "returns \\\\?\\ verbatim paths on Windows; use xai_grok_tools::util::fs helpers or spawn_blocking + dunce::canonicalize" },
|
||||
]
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
description = "Build protobuf"
|
||||
edition.workspace = true
|
||||
name = "xai-proto-build"
|
||||
version = "0.0.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
pbjson-build = { workspace = true }
|
||||
prost-build = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tonic-prost-build = { workspace = true }
|
||||
@@ -0,0 +1,93 @@
|
||||
use anyhow::{Context, bail};
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn check_protoc_good(protoc: &Path) -> anyhow::Result<()> {
|
||||
let output = Command::new(protoc)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.context("Failed to execute protoc")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
bail!(
|
||||
"protoc --version failed, likely dotslash is missing; \
|
||||
try `cargo install dotslash`; stdout: {stdout:?}, stderr: {stderr:?}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_github_actions() -> bool {
|
||||
env::var_os("GITHUB_ACTIONS").is_some()
|
||||
}
|
||||
|
||||
/// Find `protoc` command.
|
||||
///
|
||||
/// Search order:
|
||||
/// 1. `$PROTOC` environment variable (set by Bazel `build_script_env` or user override)
|
||||
/// 2. `bin/protoc` walking up parent directories (dotslash wrapper for local dev)
|
||||
/// 3. `protoc` on `$PATH` (system install or other tooling)
|
||||
///
|
||||
/// When `bin/protoc` exists but fails to execute (e.g. the dotslash wrapper running
|
||||
/// in Bazel remote execution where `dotslash` is not installed), the error is not fatal —
|
||||
/// we fall through to the PATH-based lookup instead.
|
||||
///
|
||||
/// Returns `Ok(None)` if not found and not in a strict environment (GitHub Actions).
|
||||
pub fn find_protoc() -> anyhow::Result<Option<PathBuf>> {
|
||||
// 1. Check the PROTOC env var first. This is the standard override used by prost-build
|
||||
// and is set by Bazel cargo_build_script build_script_env to point at a hermetic
|
||||
// protoc binary instead of the dotslash wrapper.
|
||||
if let Ok(protoc_env) = env::var("PROTOC") {
|
||||
let protoc = PathBuf::from(&protoc_env);
|
||||
if protoc.try_exists()? {
|
||||
check_protoc_good(&protoc)?;
|
||||
return Ok(Some(protoc));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Walk up directories looking for bin/protoc (dotslash wrapper).
|
||||
let cwd = env::current_dir()?;
|
||||
let mut dir = cwd.clone();
|
||||
let mut dir_rel = PathBuf::new();
|
||||
loop {
|
||||
// Return relative path to make build more deterministic.
|
||||
let protoc = dir_rel.join("bin/protoc");
|
||||
if protoc.try_exists()? {
|
||||
match check_protoc_good(&protoc) {
|
||||
Ok(()) => return Ok(Some(protoc)),
|
||||
Err(e) => {
|
||||
// bin/protoc exists but can't execute — likely the dotslash wrapper
|
||||
// in an environment without dotslash (e.g. Bazel remote execution).
|
||||
// Fall through to PATH-based lookup below.
|
||||
eprintln!(
|
||||
"bin/protoc found at `{}` but failed to execute: {e:#}; \
|
||||
trying protoc from PATH as fallback",
|
||||
protoc.display()
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !dir.pop() {
|
||||
break;
|
||||
}
|
||||
dir_rel.push("..");
|
||||
}
|
||||
|
||||
// 3. Try protoc from PATH (system install or other tooling).
|
||||
if check_protoc_good(Path::new("protoc")).is_ok() {
|
||||
return Ok(Some(PathBuf::from("protoc")));
|
||||
}
|
||||
|
||||
// 4. Not found anywhere.
|
||||
if is_github_actions() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"`protoc` not found (checked $PROTOC env, bin/protoc, and PATH)"
|
||||
));
|
||||
}
|
||||
eprintln!("`protoc` not found; likely it is missing in docker image");
|
||||
Ok(None)
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
pub mod find_protoc;
|
||||
|
||||
use anyhow::Context;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::{fs, iter};
|
||||
|
||||
/// Find the protoc well-known types include directory.
|
||||
///
|
||||
/// When PROTOC is set (e.g., in Bazel), the include directory is typically
|
||||
/// at `../include` relative to the `bin/protoc` binary. For example:
|
||||
/// - PROTOC = `/path/to/external/protoc_linux_x86_64/bin/protoc`
|
||||
/// - Include = `/path/to/external/protoc_linux_x86_64/include`
|
||||
///
|
||||
/// This is needed because Bazel places the protoc binary and include files
|
||||
/// in separate locations within the sandbox, and protoc doesn't automatically
|
||||
/// find them without an explicit -I flag.
|
||||
fn find_protoc_include_dir(protoc: Option<&Path>) -> Option<PathBuf> {
|
||||
let protoc = protoc?;
|
||||
|
||||
// protoc is typically at .../bin/protoc, so include is at .../include
|
||||
let parent = protoc.parent()?; // .../bin
|
||||
let grandparent = parent.parent()?; // .../
|
||||
let include_dir = grandparent.join("include");
|
||||
|
||||
if include_dir.is_dir() {
|
||||
Some(include_dir)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub struct XaiProtoBuilder {
|
||||
builder: tonic_prost_build::Builder,
|
||||
file_descriptor_set_path: Option<PathBuf>,
|
||||
gen_pbjson: bool,
|
||||
pbjson_ignore_unknown_fields: bool,
|
||||
pbjson_preserve_proto_field_names: bool,
|
||||
}
|
||||
|
||||
impl XaiProtoBuilder {
|
||||
fn map_builder(
|
||||
self,
|
||||
f: impl FnOnce(tonic_prost_build::Builder) -> tonic_prost_build::Builder,
|
||||
) -> Self {
|
||||
Self {
|
||||
builder: f(self.builder),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bytes<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Self {
|
||||
self.map_builder(|b| paths.into_iter().fold(b, |b, path| b.bytes(path)))
|
||||
}
|
||||
|
||||
pub fn extern_path(self, proto_path: impl AsRef<str>, rust_path: impl AsRef<str>) -> Self {
|
||||
self.map_builder(|b| b.extern_path(proto_path, rust_path))
|
||||
}
|
||||
|
||||
pub fn file_descriptor_set_path(mut self, path: impl AsRef<Path>) -> Self {
|
||||
self.file_descriptor_set_path = Some(path.as_ref().to_path_buf());
|
||||
self.map_builder(|b| b.file_descriptor_set_path(path))
|
||||
}
|
||||
|
||||
pub fn gen_pbjson(mut self) -> Self {
|
||||
self.gen_pbjson = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pbjson_ignore_unknown_fields(mut self) -> Self {
|
||||
self.pbjson_ignore_unknown_fields = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Serialize JSON using the original proto field names (snake_case) instead
|
||||
/// of the proto3-JSON default (camelCase). Deserialization still accepts
|
||||
/// both casings, so this is backward-compatible with already-stored
|
||||
/// camelCase documents.
|
||||
pub fn pbjson_preserve_proto_field_names(mut self) -> Self {
|
||||
self.pbjson_preserve_proto_field_names = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn generate_default_stubs(self, enable: bool) -> Self {
|
||||
self.map_builder(|b| b.generate_default_stubs(enable))
|
||||
}
|
||||
|
||||
pub fn type_attribute(self, path: impl AsRef<str>, attr: impl AsRef<str>) -> Self {
|
||||
self.map_builder(|b| b.type_attribute(path, attr))
|
||||
}
|
||||
|
||||
pub fn field_attribute(self, path: impl AsRef<str>, attr: impl AsRef<str>) -> Self {
|
||||
self.map_builder(|b| b.field_attribute(path, attr))
|
||||
}
|
||||
|
||||
// tonic-build generation of `rerun-if-changed` is lazy and incorrect.
|
||||
// - everything is invalidated when anything inside include directories is changed
|
||||
// - also they compute paths incorrectly: assuming paths are relative to current directory
|
||||
// rather than
|
||||
fn emit_rerun_if_changed<'a>(
|
||||
protoc: Option<&Path>,
|
||||
protoc_include_dir: Option<&Path>,
|
||||
protos: impl IntoIterator<Item = &'a Path>,
|
||||
includes: impl IntoIterator<Item = &'a Path>,
|
||||
) -> anyhow::Result<()> {
|
||||
let includes = Vec::from_iter(includes);
|
||||
|
||||
if let Some(protoc) = protoc {
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
protoc.to_str().context("protoc path not UTF-8")?
|
||||
);
|
||||
}
|
||||
|
||||
// Can only process one input file when using --dependency_out=FILE.
|
||||
for proto in protos {
|
||||
let mut command = Command::new(protoc.unwrap_or(Path::new("protoc")));
|
||||
command
|
||||
.arg("--dependency_out=/dev/stdout")
|
||||
.arg("--descriptor_set_out=/dev/null");
|
||||
|
||||
// Add protoc's well-known types include directory first (if found).
|
||||
// This is needed for Bazel sandboxed builds where protoc and its
|
||||
// include files are in different locations.
|
||||
if let Some(include_dir) = protoc_include_dir {
|
||||
command.arg(format!(
|
||||
"-I{}",
|
||||
include_dir.to_str().context("include path not UTF-8")?
|
||||
));
|
||||
}
|
||||
|
||||
for include in &includes {
|
||||
command.arg(format!("-I{}", include.to_str().context("path not UTF-8")?));
|
||||
}
|
||||
|
||||
command.arg(proto);
|
||||
|
||||
command.stdin(Stdio::null());
|
||||
command.stderr(Stdio::inherit());
|
||||
|
||||
let output = command.output().context("protoc command failed")?;
|
||||
if !output.status.success() {
|
||||
return Err(anyhow::anyhow!("protoc command failed"));
|
||||
}
|
||||
|
||||
let output =
|
||||
String::from_utf8(output.stdout).context("protoc command output not UTF-8")?;
|
||||
|
||||
let mut lines = output.lines();
|
||||
let first_line = lines.next().context("protoc command output is empty")?;
|
||||
let prefix = "/dev/null:";
|
||||
let rem = first_line.strip_prefix(prefix).with_context(|| {
|
||||
format!("protoc command output must start with /dev/null: {output:?}")
|
||||
})?;
|
||||
for line in iter::once(rem).chain(lines) {
|
||||
let line = line.trim();
|
||||
let line = line.strip_suffix("\\").unwrap_or(line);
|
||||
// Depending on absolute paths like
|
||||
// /Users/user/homebrew/Cellar/protobuf/29.1/include/google/protobuf/timestamp.proto
|
||||
// is valid, but we want to have output more deterministic.
|
||||
if line.contains("/include/google/protobuf/") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !fs::exists(line)? {
|
||||
return Err(anyhow::anyhow!("dependency file not found: {line}"));
|
||||
}
|
||||
|
||||
println!("cargo:rerun-if-changed={line}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn compile_protos(
|
||||
self,
|
||||
protos: &[impl AsRef<Path>],
|
||||
includes: &[impl AsRef<Path>],
|
||||
) -> anyhow::Result<()> {
|
||||
for proto in protos {
|
||||
let proto = proto.as_ref();
|
||||
if proto.is_absolute() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Absolute paths are not allowed: {}",
|
||||
proto.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let XaiProtoBuilder {
|
||||
builder,
|
||||
gen_pbjson,
|
||||
file_descriptor_set_path,
|
||||
pbjson_ignore_unknown_fields,
|
||||
pbjson_preserve_proto_field_names,
|
||||
} = self;
|
||||
let mut config = prost_build::Config::new();
|
||||
config.enable_type_names();
|
||||
|
||||
let protoc = find_protoc::find_protoc()?;
|
||||
|
||||
// Use fixed version of `protoc` binary.
|
||||
if let Some(protoc) = &protoc {
|
||||
config.protoc_executable(protoc);
|
||||
}
|
||||
|
||||
// Find the protoc's well-known types include directory.
|
||||
// This is needed for Bazel sandboxed builds where protoc and its
|
||||
// include files are placed in different sandbox locations.
|
||||
let protoc_include_dir = find_protoc_include_dir(protoc.as_deref());
|
||||
|
||||
let mut builder = builder.emit_rerun_if_changed(false);
|
||||
Self::emit_rerun_if_changed(
|
||||
protoc.as_deref(),
|
||||
protoc_include_dir.as_deref(),
|
||||
protos.iter().map(|p| p.as_ref()),
|
||||
includes.iter().map(|i| i.as_ref()),
|
||||
)?;
|
||||
|
||||
let tempfile;
|
||||
|
||||
let file_descriptor_set_path: Option<PathBuf> =
|
||||
if let Some(file_descriptor_set_path) = file_descriptor_set_path {
|
||||
Some(file_descriptor_set_path)
|
||||
} else if gen_pbjson {
|
||||
tempfile = tempfile::TempDir::new()?;
|
||||
let file_descriptor_set_path = tempfile.path().join("xai-proto-build.pbbin");
|
||||
builder = builder.file_descriptor_set_path(&file_descriptor_set_path);
|
||||
Some(file_descriptor_set_path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Build the full includes list, prepending the protoc include directory
|
||||
// if found (for well-known types like google/protobuf/timestamp.proto).
|
||||
let all_includes: Vec<&Path> = protoc_include_dir
|
||||
.as_deref()
|
||||
.into_iter()
|
||||
.chain(includes.iter().map(|i| i.as_ref()))
|
||||
.collect();
|
||||
|
||||
let protos: Vec<&Path> = protos.iter().map(|p| p.as_ref()).collect();
|
||||
|
||||
builder
|
||||
.compile_with_config(config, &protos, &all_includes)
|
||||
.context("tonic_build failed")?;
|
||||
|
||||
if gen_pbjson {
|
||||
let file_descriptor_set_path =
|
||||
file_descriptor_set_path.context("fds must be set at this moment")?;
|
||||
let descriptor_set = fs::read(&file_descriptor_set_path).with_context(|| {
|
||||
format!(
|
||||
"Failed to read file descriptor set {}",
|
||||
file_descriptor_set_path.display()
|
||||
)
|
||||
})?;
|
||||
let mut builder = pbjson_build::Builder::new();
|
||||
builder
|
||||
.register_descriptors(&descriptor_set)
|
||||
.context("Failed to register descriptors in pbjson_build")?;
|
||||
if pbjson_ignore_unknown_fields {
|
||||
builder.ignore_unknown_fields();
|
||||
}
|
||||
if pbjson_preserve_proto_field_names {
|
||||
builder.preserve_proto_field_names();
|
||||
}
|
||||
builder
|
||||
.build(&["."])
|
||||
.context("Failed to build descriptor set")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configure() -> XaiProtoBuilder {
|
||||
let builder = tonic_prost_build::configure()
|
||||
.compile_well_known_types(true)
|
||||
.extern_path(".google.protobuf", "::pbjson_types")
|
||||
.extern_path(".google.protobuf.Empty", "()")
|
||||
.protoc_arg("--experimental_allow_proto3_optional");
|
||||
XaiProtoBuilder {
|
||||
builder,
|
||||
gen_pbjson: false,
|
||||
pbjson_ignore_unknown_fields: false,
|
||||
pbjson_preserve_proto_field_names: false,
|
||||
file_descriptor_set_path: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
name = "ptyctl-cli"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
description = "CLI for ptyctl headless PTY controller"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "ptyctl"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
ptyctl = { path = "../ptyctl" }
|
||||
axum = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
reqwest = { workspace = true, features = ["json"] }
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
dirs = { workspace = true }
|
||||
@@ -0,0 +1,227 @@
|
||||
//! CLI argument definitions using clap derive.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "ptyctl")]
|
||||
#[command(about = "Run commands in PTY and control them via HTTP")]
|
||||
#[command(version)]
|
||||
#[command(arg_required_else_help = true)]
|
||||
pub struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum Commands {
|
||||
/// Spawn a command in a PTY and start an HTTP control server
|
||||
#[command(arg_required_else_help = true)]
|
||||
Run {
|
||||
/// Command to run (use -- before command)
|
||||
#[arg(required = true, trailing_var_arg = true)]
|
||||
command: Vec<String>,
|
||||
|
||||
/// Terminal width in columns
|
||||
#[arg(short = 'W', long, default_value = "80")]
|
||||
width: u16,
|
||||
|
||||
/// Terminal height in rows
|
||||
#[arg(short = 'H', long, default_value = "24")]
|
||||
height: u16,
|
||||
|
||||
/// Working directory
|
||||
#[arg(short = 'c', long)]
|
||||
cwd: Option<PathBuf>,
|
||||
|
||||
/// Environment variable (KEY=VAL, repeatable)
|
||||
#[arg(short = 'e', long = "env", value_name = "KEY=VAL")]
|
||||
env: Vec<String>,
|
||||
|
||||
/// TCP port to listen on (0 = auto-assign)
|
||||
#[arg(short, long, default_value = "0")]
|
||||
port: u16,
|
||||
|
||||
/// Session name (registers in ~/.local/state/ptyctl/sessions/)
|
||||
#[arg(short, long)]
|
||||
name: Option<String>,
|
||||
|
||||
/// Take over an existing session name (replaces the registration; does not stop the old server)
|
||||
#[arg(long)]
|
||||
force: bool,
|
||||
|
||||
/// Shutdown after N seconds
|
||||
#[arg(short, long, value_name = "SECS")]
|
||||
timeout: Option<u64>,
|
||||
|
||||
/// Keep server running after process exits
|
||||
#[arg(short, long)]
|
||||
linger: bool,
|
||||
|
||||
/// Suppress output (just print port number)
|
||||
#[arg(short, long)]
|
||||
quiet: bool,
|
||||
},
|
||||
|
||||
/// Send keystrokes to a running session
|
||||
#[command(arg_required_else_help = true)]
|
||||
Send {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
|
||||
/// Keys to send (vim notation)
|
||||
keys: String,
|
||||
|
||||
/// Append Enter (<CR>) after keys
|
||||
#[arg(short = 'e', long)]
|
||||
enter: bool,
|
||||
},
|
||||
|
||||
/// Query terminal screen content
|
||||
#[command(arg_required_else_help = true)]
|
||||
Screen {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
|
||||
/// Row range, 1-indexed (e.g. "1:5")
|
||||
#[arg(short, long)]
|
||||
rows: Option<String>,
|
||||
|
||||
/// Column range, 1-indexed
|
||||
#[arg(short = 'C', long)]
|
||||
cols: Option<String>,
|
||||
|
||||
/// Output as JSON
|
||||
#[arg(short, long, conflicts_with_all = ["ansi", "styled", "html"])]
|
||||
json: bool,
|
||||
|
||||
/// Show cursor position with this character
|
||||
#[arg(short = 'c', long)]
|
||||
cursor: Option<char>,
|
||||
|
||||
/// Include ANSI escape codes
|
||||
#[arg(short, long, conflicts_with_all = ["json", "styled", "html"])]
|
||||
ansi: bool,
|
||||
|
||||
/// Output as styled JSON (LLM-friendly)
|
||||
#[arg(short = 's', long, conflicts_with_all = ["json", "ansi", "html"])]
|
||||
styled: bool,
|
||||
|
||||
/// Output as HTML
|
||||
#[arg(long, conflicts_with_all = ["json", "ansi", "styled"])]
|
||||
html: bool,
|
||||
|
||||
/// Include trailing empty lines
|
||||
#[arg(long)]
|
||||
full: bool,
|
||||
|
||||
/// Show line numbers
|
||||
#[arg(short = 'l', long)]
|
||||
line_numbers: bool,
|
||||
},
|
||||
|
||||
/// Query process status
|
||||
#[command(arg_required_else_help = true)]
|
||||
Status {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
},
|
||||
|
||||
/// Stop a running session
|
||||
#[command(arg_required_else_help = true)]
|
||||
Stop {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
},
|
||||
|
||||
/// Resize terminal dimensions
|
||||
#[command(arg_required_else_help = true)]
|
||||
Resize {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
|
||||
/// New size as COLSxROWS (e.g. "120x40")
|
||||
size: String,
|
||||
},
|
||||
|
||||
/// Query cursor position
|
||||
#[command(arg_required_else_help = true)]
|
||||
Cursor {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
},
|
||||
|
||||
/// Wait for a screen condition (event-driven, no polling).
|
||||
/// Exit codes: 0 matched, 1 timeout (failure JSON on stdout), 2 usage/connection error
|
||||
#[command(arg_required_else_help = true)]
|
||||
#[command(group(clap::ArgGroup::new("condition").required(true)))]
|
||||
Wait {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
|
||||
/// Wait until this text appears on screen
|
||||
#[arg(long, group = "condition")]
|
||||
text: Option<String>,
|
||||
|
||||
/// Wait until this regex matches the screen text
|
||||
#[arg(long, group = "condition")]
|
||||
regex: Option<String>,
|
||||
|
||||
/// Wait until this text is absent from the screen
|
||||
#[arg(long, group = "condition")]
|
||||
gone: Option<String>,
|
||||
|
||||
/// Wait until the screen has been unchanged for this many milliseconds
|
||||
#[arg(long, value_name = "MS", group = "condition")]
|
||||
stable_ms: Option<u64>,
|
||||
|
||||
/// Timeout in seconds (server caps at 120)
|
||||
#[arg(short, long, default_value = "10")]
|
||||
timeout: u64,
|
||||
},
|
||||
|
||||
/// List registered sessions
|
||||
List {
|
||||
/// Output as JSON
|
||||
#[arg(short, long)]
|
||||
json: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// Target session — exactly one of host, port, or name must be provided.
|
||||
#[derive(clap::Args)]
|
||||
#[group(required = true, multiple = false)]
|
||||
pub struct Target {
|
||||
/// Remote host address (e.g. 127.0.0.1:8080)
|
||||
#[arg(short = 'H', long)]
|
||||
pub host: Option<String>,
|
||||
|
||||
/// Local server port
|
||||
#[arg(short, long)]
|
||||
pub port: Option<u16>,
|
||||
|
||||
/// Session name (from registry)
|
||||
#[arg(short, long)]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// Resolve target to a base URL.
|
||||
pub fn to_url(&self) -> anyhow::Result<String> {
|
||||
if let Some(ref h) = self.host {
|
||||
if h.starts_with("http") {
|
||||
return Ok(h.clone());
|
||||
}
|
||||
return Ok(format!("http://{h}"));
|
||||
}
|
||||
if let Some(p) = self.port {
|
||||
return Ok(format!("http://127.0.0.1:{p}"));
|
||||
}
|
||||
if let Some(ref n) = self.name {
|
||||
let info = crate::registry::lookup_session(n)?;
|
||||
return Ok(format!("http://127.0.0.1:{}", info.port));
|
||||
}
|
||||
anyhow::bail!("no target specified")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Client commands — send/screen/status/cursor/resize/stop via HTTP.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use reqwest::Client;
|
||||
|
||||
/// Send keystrokes to a session.
|
||||
pub async fn send(url: &str, keys: &str, enter: bool) -> Result<()> {
|
||||
let mut keys = keys.to_string();
|
||||
if enter {
|
||||
keys.push_str("<CR>");
|
||||
}
|
||||
|
||||
let client = Client::new();
|
||||
let resp = client
|
||||
.post(format!("{url}/control/send"))
|
||||
.json(&serde_json::json!({"keys": keys}))
|
||||
.send()
|
||||
.await
|
||||
.context("failed to send keys")?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("send failed: {body}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Query screen content.
|
||||
pub async fn screen(
|
||||
url: &str,
|
||||
rows: Option<&str>,
|
||||
cols: Option<&str>,
|
||||
cursor: Option<char>,
|
||||
format: &str,
|
||||
full: bool,
|
||||
line_numbers: bool,
|
||||
) -> Result<()> {
|
||||
let client = Client::new();
|
||||
let mut req = client.get(format!("{url}/query/screen"));
|
||||
|
||||
if let Some(r) = rows {
|
||||
req = req.query(&[("rows", r)]);
|
||||
}
|
||||
if let Some(c) = cols {
|
||||
req = req.query(&[("cols", c)]);
|
||||
}
|
||||
if let Some(ch) = cursor {
|
||||
req = req.query(&[("cursor", &ch.to_string())]);
|
||||
}
|
||||
req = req.query(&[("format", format)]);
|
||||
if full {
|
||||
req = req.query(&[("full", "true")]);
|
||||
}
|
||||
|
||||
let resp = req.send().await.context("failed to query screen")?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("screen query failed: {body}");
|
||||
}
|
||||
|
||||
let body = resp.text().await?;
|
||||
|
||||
if format == "html" || format == "styled" {
|
||||
println!("{body}");
|
||||
} else {
|
||||
// Parse as JSON and print lines.
|
||||
let output: serde_json::Value = serde_json::from_str(&body)?;
|
||||
if let Some(lines) = output.get("lines").and_then(|l| l.as_array()) {
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let text = line.as_str().unwrap_or("");
|
||||
if line_numbers {
|
||||
println!("{:4} {text}", i + 1);
|
||||
} else {
|
||||
println!("{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Query cursor position.
|
||||
pub async fn cursor(url: &str) -> Result<()> {
|
||||
let client = Client::new();
|
||||
let resp = client
|
||||
.get(format!("{url}/query/cursor"))
|
||||
.send()
|
||||
.await
|
||||
.context("failed to query cursor")?;
|
||||
let body = resp.text().await?;
|
||||
println!("{body}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Query session status.
|
||||
pub async fn status(url: &str) -> Result<()> {
|
||||
let client = Client::new();
|
||||
let resp = client
|
||||
.get(format!("{url}/query/status"))
|
||||
.send()
|
||||
.await
|
||||
.context("failed to query status")?;
|
||||
let body = resp.text().await?;
|
||||
println!("{body}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resize terminal.
|
||||
pub async fn resize(url: &str, size: &str) -> Result<()> {
|
||||
let (cols, rows) = size
|
||||
.split_once('x')
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid size format, expected COLSxROWS (e.g. 120x40)"))?;
|
||||
let cols: u16 = cols.parse().context("invalid cols")?;
|
||||
let rows: u16 = rows.parse().context("invalid rows")?;
|
||||
|
||||
let client = Client::new();
|
||||
let resp = client
|
||||
.post(format!("{url}/control/resize"))
|
||||
.json(&serde_json::json!({"cols": cols, "rows": rows}))
|
||||
.send()
|
||||
.await
|
||||
.context("failed to resize")?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("resize failed: {body}");
|
||||
}
|
||||
println!("Resized to {cols}x{rows}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Long-poll the wait endpoint; prints the outcome JSON and returns whether it matched.
|
||||
pub async fn wait(
|
||||
url: &str,
|
||||
text: Option<&str>,
|
||||
regex: Option<&str>,
|
||||
gone: Option<&str>,
|
||||
stable_ms: Option<u64>,
|
||||
timeout_secs: u64,
|
||||
) -> Result<bool> {
|
||||
// The HTTP timeout outlasts the wait so the server, not the client, decides the outcome.
|
||||
let client = Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(
|
||||
timeout_secs.saturating_add(5),
|
||||
))
|
||||
.build()
|
||||
.context("failed to build HTTP client")?;
|
||||
|
||||
let mut req = client
|
||||
.get(format!("{url}/wait"))
|
||||
.query(&[("timeout_ms", timeout_secs.saturating_mul(1000).to_string())]);
|
||||
if let Some(t) = text {
|
||||
req = req.query(&[("text", t)]);
|
||||
}
|
||||
if let Some(r) = regex {
|
||||
req = req.query(&[("regex", r)]);
|
||||
}
|
||||
if let Some(g) = gone {
|
||||
req = req.query(&[("gone", g)]);
|
||||
}
|
||||
if let Some(ms) = stable_ms {
|
||||
req = req.query(&[("stable_ms", ms.to_string())]);
|
||||
}
|
||||
|
||||
let resp = req.send().await.context("failed to call wait")?;
|
||||
if !resp.status().is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("wait failed: {body}");
|
||||
}
|
||||
|
||||
let outcome: serde_json::Value = resp.json().await.context("invalid wait response")?;
|
||||
println!("{}", serde_json::to_string_pretty(&outcome)?);
|
||||
Ok(outcome
|
||||
.get("matched")
|
||||
.and_then(|m| m.as_bool())
|
||||
.unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Stop a session.
|
||||
pub async fn stop(url: &str) -> Result<()> {
|
||||
let client = Client::new();
|
||||
let resp = client
|
||||
.post(format!("{url}/control/stop"))
|
||||
.send()
|
||||
.await
|
||||
.context("failed to stop session")?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("stop failed: {body}");
|
||||
}
|
||||
println!("Session stopped");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod client;
|
||||
pub mod run;
|
||||
@@ -0,0 +1,119 @@
|
||||
//! `ptyctl run` — spawn a PTY session and start the HTTP server.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use ptyctl::pty::PtyConfig;
|
||||
use ptyctl::server;
|
||||
use ptyctl::session::{PtySession, SessionConfig};
|
||||
|
||||
use crate::registry;
|
||||
|
||||
/// Run the `ptyctl run` command.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn run(
|
||||
command: Vec<String>,
|
||||
width: u16,
|
||||
height: u16,
|
||||
cwd: Option<PathBuf>,
|
||||
env_vars: Vec<String>,
|
||||
port: u16,
|
||||
name: Option<String>,
|
||||
force: bool,
|
||||
timeout: Option<u64>,
|
||||
linger: bool,
|
||||
quiet: bool,
|
||||
) -> Result<()> {
|
||||
// Refuse to take over a name whose server is still reachable unless --force; stale entries are replaced.
|
||||
if let Some(ref session_name) = name
|
||||
&& !force
|
||||
&& let Ok(existing) = registry::lookup_session(session_name)
|
||||
&& registry::server_alive(existing.port).await
|
||||
{
|
||||
bail!(
|
||||
"session '{session_name}' is already running on port {} (use --force to replace it)",
|
||||
existing.port
|
||||
);
|
||||
}
|
||||
|
||||
// Parse env vars.
|
||||
let mut env = HashMap::new();
|
||||
for var in &env_vars {
|
||||
if let Some((k, v)) = var.split_once('=') {
|
||||
env.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let cwd_str = cwd
|
||||
.as_ref()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_else(|| ".".into());
|
||||
|
||||
let config = SessionConfig {
|
||||
pty: PtyConfig {
|
||||
command: command.clone(),
|
||||
cols: width,
|
||||
rows: height,
|
||||
cwd,
|
||||
env,
|
||||
},
|
||||
timeout,
|
||||
linger,
|
||||
};
|
||||
|
||||
// Start the session.
|
||||
let session = PtySession::start(config).await?;
|
||||
let pid = session.status_basic().1;
|
||||
|
||||
// Build the HTTP server.
|
||||
let router = server::build_router(session);
|
||||
|
||||
// Bind to the requested port.
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
let listener = TcpListener::bind(addr)
|
||||
.await
|
||||
.context("failed to bind TCP listener")?;
|
||||
let actual_addr = listener.local_addr()?;
|
||||
let actual_port = actual_addr.port();
|
||||
|
||||
// Register named session.
|
||||
if let Some(ref session_name) = name {
|
||||
let info = registry::SessionInfo {
|
||||
port: actual_port,
|
||||
pid,
|
||||
command: command.clone(),
|
||||
cwd: cwd_str,
|
||||
started_at: chrono::Utc::now().to_rfc3339(),
|
||||
};
|
||||
registry::register_session(session_name, &info)?;
|
||||
}
|
||||
|
||||
if !quiet {
|
||||
eprintln!("Command: {}", command.join(" "));
|
||||
if let Some(p) = pid {
|
||||
eprintln!("PID: {p}");
|
||||
}
|
||||
eprintln!("Server listening on port: {actual_port}");
|
||||
} else {
|
||||
println!("{actual_port}");
|
||||
}
|
||||
|
||||
// Serve until shutdown.
|
||||
let shutdown_result = axum::serve(listener, router)
|
||||
.await
|
||||
.context("HTTP server error");
|
||||
|
||||
// Clean up only a registration that still points at this server; a --force takeover may have replaced it.
|
||||
if let Some(ref session_name) = name
|
||||
&& let Ok(info) = registry::lookup_session(session_name)
|
||||
&& info.port == actual_port
|
||||
{
|
||||
let _ = registry::unregister_session(session_name);
|
||||
}
|
||||
|
||||
shutdown_result
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! ptyctl CLI — headless PTY controller.
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
mod cli;
|
||||
mod commands;
|
||||
mod registry;
|
||||
|
||||
use cli::{Cli, Commands};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
env_logger::init();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
match cli.command {
|
||||
Commands::Run {
|
||||
command,
|
||||
width,
|
||||
height,
|
||||
cwd,
|
||||
env,
|
||||
port,
|
||||
name,
|
||||
force,
|
||||
timeout,
|
||||
linger,
|
||||
quiet,
|
||||
} => {
|
||||
commands::run::run(
|
||||
command, width, height, cwd, env, port, name, force, timeout, linger, quiet,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Commands::Send {
|
||||
target,
|
||||
keys,
|
||||
enter,
|
||||
} => {
|
||||
let url = target.to_url()?;
|
||||
commands::client::send(&url, &keys, enter).await?;
|
||||
}
|
||||
Commands::Screen {
|
||||
target,
|
||||
rows,
|
||||
cols,
|
||||
json: _,
|
||||
cursor,
|
||||
ansi: _,
|
||||
styled,
|
||||
html,
|
||||
full,
|
||||
line_numbers,
|
||||
} => {
|
||||
let url = target.to_url()?;
|
||||
let format = if styled {
|
||||
"styled"
|
||||
} else if html {
|
||||
"html"
|
||||
} else {
|
||||
"text"
|
||||
};
|
||||
commands::client::screen(
|
||||
&url,
|
||||
rows.as_deref(),
|
||||
cols.as_deref(),
|
||||
cursor,
|
||||
format,
|
||||
full,
|
||||
line_numbers,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Commands::Status { target } => {
|
||||
let url = target.to_url()?;
|
||||
commands::client::status(&url).await?;
|
||||
}
|
||||
Commands::Stop { target } => {
|
||||
let url = target.to_url()?;
|
||||
commands::client::stop(&url).await?;
|
||||
}
|
||||
Commands::Resize { target, size } => {
|
||||
let url = target.to_url()?;
|
||||
commands::client::resize(&url, &size).await?;
|
||||
}
|
||||
Commands::Cursor { target } => {
|
||||
let url = target.to_url()?;
|
||||
commands::client::cursor(&url).await?;
|
||||
}
|
||||
Commands::Wait {
|
||||
target,
|
||||
text,
|
||||
regex,
|
||||
gone,
|
||||
stable_ms,
|
||||
timeout,
|
||||
} => {
|
||||
// Exit code contract: 0 matched, 1 timeout, 2 usage/connection errors.
|
||||
let exit = |code: i32| -> ! { std::process::exit(code) };
|
||||
let url = match target.to_url() {
|
||||
Ok(url) => url,
|
||||
Err(e) => {
|
||||
eprintln!("Error: {e:#}");
|
||||
exit(2);
|
||||
}
|
||||
};
|
||||
match commands::client::wait(
|
||||
&url,
|
||||
text.as_deref(),
|
||||
regex.as_deref(),
|
||||
gone.as_deref(),
|
||||
stable_ms,
|
||||
timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => {}
|
||||
Ok(false) => exit(1),
|
||||
Err(e) => {
|
||||
eprintln!("Error: {e:#}");
|
||||
exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
Commands::List { json } => {
|
||||
let sessions = registry::list_sessions()?;
|
||||
if json {
|
||||
let mut items = Vec::new();
|
||||
for (name, info) in &sessions {
|
||||
items.push(serde_json::json!({
|
||||
"name": name,
|
||||
"port": info.port,
|
||||
"pid": info.pid,
|
||||
"command": info.command,
|
||||
"started_at": info.started_at,
|
||||
// "server_alive", not "alive": /query/status's "alive" means child-alive, which diverges under --linger.
|
||||
"server_alive": registry::server_alive(info.port).await,
|
||||
}));
|
||||
}
|
||||
println!("{}", serde_json::to_string_pretty(&items)?);
|
||||
} else if sessions.is_empty() {
|
||||
println!("No active sessions");
|
||||
} else {
|
||||
println!(
|
||||
"{:<16} {:<8} {:<8} {:<8} COMMAND",
|
||||
"NAME", "PORT", "PID", "SERVER"
|
||||
);
|
||||
println!("{}", "-".repeat(60));
|
||||
for (name, info) in &sessions {
|
||||
let pid = info
|
||||
.pid
|
||||
.map(|p| p.to_string())
|
||||
.unwrap_or_else(|| "?".into());
|
||||
let server = if registry::server_alive(info.port).await {
|
||||
"live"
|
||||
} else {
|
||||
"dead"
|
||||
};
|
||||
println!(
|
||||
"{:<16} {:<8} {:<8} {:<8} {}",
|
||||
name,
|
||||
info.port,
|
||||
pid,
|
||||
server,
|
||||
info.command.join(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Named session registry stored at ~/.local/state/ptyctl/sessions/.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Information about a registered session.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SessionInfo {
|
||||
pub port: u16,
|
||||
pub pid: Option<u32>,
|
||||
pub command: Vec<String>,
|
||||
pub cwd: String,
|
||||
pub started_at: String,
|
||||
}
|
||||
|
||||
/// Get the session registry directory.
|
||||
fn registry_dir() -> Result<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PTYCTL_SESSION_DIR") {
|
||||
return Ok(PathBuf::from(dir));
|
||||
}
|
||||
let state_dir = dirs::state_dir()
|
||||
.or_else(dirs::data_local_dir)
|
||||
.context("cannot determine state directory")?;
|
||||
Ok(state_dir.join("ptyctl").join("sessions"))
|
||||
}
|
||||
|
||||
/// Register a named session.
|
||||
pub fn register_session(name: &str, info: &SessionInfo) -> Result<()> {
|
||||
let dir = registry_dir()?;
|
||||
fs::create_dir_all(&dir).context("failed to create session registry directory")?;
|
||||
|
||||
let path = dir.join(format!("{name}.json"));
|
||||
let json = serde_json::to_string_pretty(info)?;
|
||||
|
||||
// Atomic write: write to temp file, then rename.
|
||||
let tmp = dir.join(format!(".{name}.json.tmp"));
|
||||
fs::write(&tmp, &json).context("failed to write session file")?;
|
||||
fs::rename(&tmp, &path).context("failed to rename session file")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Look up a named session.
|
||||
pub fn lookup_session(name: &str) -> Result<SessionInfo> {
|
||||
let dir = registry_dir()?;
|
||||
let path = dir.join(format!("{name}.json"));
|
||||
|
||||
if !path.exists() {
|
||||
bail!("session '{name}' not found");
|
||||
}
|
||||
|
||||
let json = fs::read_to_string(&path).context("failed to read session file")?;
|
||||
let info: SessionInfo = serde_json::from_str(&json).context("failed to parse session file")?;
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Remove a named session.
|
||||
pub fn unregister_session(name: &str) -> Result<()> {
|
||||
let dir = registry_dir()?;
|
||||
let path = dir.join(format!("{name}.json"));
|
||||
if path.exists() {
|
||||
fs::remove_file(&path).context("failed to remove session file")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check whether a registered session's ptyctl server is reachable.
|
||||
///
|
||||
/// Probes `GET /query/status` and requires a 200 with the ptyctl status body
|
||||
/// shape — a bare TCP connect (or bare 200) would misread an unrelated
|
||||
/// process on a recycled port as live. Not PID-based because the recorded
|
||||
/// PID is the child, which may exit while a `--linger` server is still up.
|
||||
pub async fn server_alive(port: u16) -> bool {
|
||||
let Ok(client) = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_millis(500))
|
||||
.build()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
match client
|
||||
.get(format!("http://127.0.0.1:{port}/query/status"))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
// Require the status body shape, not just a 200, so wildcard-200 servers read dead.
|
||||
Ok(resp) if resp.status() == reqwest::StatusCode::OK => resp
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.is_ok_and(|v| v.get("size").is_some()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// List all registered sessions.
|
||||
pub fn list_sessions() -> Result<Vec<(String, SessionInfo)>> {
|
||||
let dir = registry_dir()?;
|
||||
if !dir.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut sessions = Vec::new();
|
||||
for entry in fs::read_dir(&dir).context("failed to read session directory")? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) == Some("json") {
|
||||
let name = path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if name.starts_with('.') {
|
||||
continue; // skip temp files
|
||||
}
|
||||
if let Ok(json) = fs::read_to_string(&path)
|
||||
&& let Ok(info) = serde_json::from_str::<SessionInfo>(&json)
|
||||
{
|
||||
sessions.push((name, info));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(sessions)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
name = "ptyctl"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
description = "Headless PTY controller built on alacritty_terminal"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
alacritty_terminal = { workspace = true }
|
||||
portable-pty = { workspace = true }
|
||||
terminput = { workspace = true }
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
axum = { workspace = true, features = ["ws"] }
|
||||
futures-util = { workspace = true }
|
||||
tower-http = { workspace = true, features = ["cors"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
log = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["full", "test-util"] }
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Vim-style key notation parser.
|
||||
//!
|
||||
//! Converts strings like `"hello<CR>"`, `"<C-c>"`, `"<Esc>:wq<CR>"` into
|
||||
//! raw terminal byte sequences using the `terminput` crate.
|
||||
|
||||
use std::io;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use terminput::{Encoding, Event, KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
/// Parse a vim-notation key string into raw terminal bytes.
|
||||
///
|
||||
/// # Examples
|
||||
/// - `"hello"` -> literal bytes for h, e, l, l, o
|
||||
/// - `"<CR>"` or `"<Enter>"` -> `\r`
|
||||
/// - `"<C-c>"` -> Ctrl+C (0x03)
|
||||
/// - `"<Esc>:wq<CR>"` -> ESC, :, w, q, CR
|
||||
/// - `"<Up><Up><CR>"` -> up arrow, up arrow, CR
|
||||
pub fn parse_keys(input: &str) -> Result<Vec<u8>> {
|
||||
let events = parse_to_events(input)?;
|
||||
let mut bytes = Vec::new();
|
||||
let mut buf = [0u8; 64];
|
||||
|
||||
for event in events {
|
||||
let ev = Event::Key(event);
|
||||
match ev.encode(&mut buf, Encoding::Xterm) {
|
||||
Ok(n) => bytes.extend_from_slice(&buf[..n]),
|
||||
Err(e) if e.kind() == io::ErrorKind::Unsupported => {
|
||||
// Some keys may not be encodable; skip them.
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Parse vim notation into a sequence of `KeyEvent`s.
|
||||
fn parse_to_events(input: &str) -> Result<Vec<KeyEvent>> {
|
||||
let mut events = Vec::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
|
||||
while let Some(&ch) = chars.peek() {
|
||||
if ch == '<' {
|
||||
// Try to parse a special key notation.
|
||||
let start_pos: String = chars.clone().collect();
|
||||
if let Some(end) = start_pos.find('>') {
|
||||
let notation = &start_pos[1..end]; // between < and >
|
||||
// Consume chars including the >.
|
||||
for _ in 0..=end {
|
||||
chars.next();
|
||||
}
|
||||
let event = parse_special(notation)?;
|
||||
events.push(event);
|
||||
} else {
|
||||
// No closing '>', treat '<' as literal.
|
||||
chars.next();
|
||||
events.push(key(KeyCode::Char('<'), KeyModifiers::NONE));
|
||||
}
|
||||
} else {
|
||||
chars.next();
|
||||
events.push(key(KeyCode::Char(ch), KeyModifiers::NONE));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
/// Helper to build a KeyEvent with modifiers.
|
||||
fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
|
||||
let mut ev = KeyEvent::new(code);
|
||||
ev.modifiers = modifiers;
|
||||
ev
|
||||
}
|
||||
|
||||
/// Parse the content between `<` and `>` as a special key.
|
||||
fn parse_special(notation: &str) -> Result<KeyEvent> {
|
||||
let lower = notation.to_lowercase();
|
||||
|
||||
// Parse modifiers: C-, M-/A-, S- (in any order).
|
||||
let mut modifiers = KeyModifiers::NONE;
|
||||
let mut remaining = lower.as_str();
|
||||
|
||||
loop {
|
||||
if let Some(rest) = remaining.strip_prefix("c-") {
|
||||
modifiers |= KeyModifiers::CTRL;
|
||||
remaining = rest;
|
||||
} else if let Some(rest) = remaining
|
||||
.strip_prefix("m-")
|
||||
.or(remaining.strip_prefix("a-"))
|
||||
{
|
||||
modifiers |= KeyModifiers::ALT;
|
||||
remaining = rest;
|
||||
} else if let Some(rest) = remaining.strip_prefix("s-") {
|
||||
modifiers |= KeyModifiers::SHIFT;
|
||||
remaining = rest;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let code = match remaining {
|
||||
"cr" | "enter" | "return" => KeyCode::Enter,
|
||||
"esc" | "escape" => KeyCode::Esc,
|
||||
"bs" | "backspace" => KeyCode::Backspace,
|
||||
"tab" => KeyCode::Tab,
|
||||
"space" | "spc" => KeyCode::Char(' '),
|
||||
"up" => KeyCode::Up,
|
||||
"down" => KeyCode::Down,
|
||||
"left" => KeyCode::Left,
|
||||
"right" => KeyCode::Right,
|
||||
"home" => KeyCode::Home,
|
||||
"end" => KeyCode::End,
|
||||
"pageup" | "pgup" => KeyCode::PageUp,
|
||||
"pagedown" | "pgdn" => KeyCode::PageDown,
|
||||
"insert" | "ins" => KeyCode::Insert,
|
||||
"delete" | "del" => KeyCode::Delete,
|
||||
"f1" => KeyCode::F(1),
|
||||
"f2" => KeyCode::F(2),
|
||||
"f3" => KeyCode::F(3),
|
||||
"f4" => KeyCode::F(4),
|
||||
"f5" => KeyCode::F(5),
|
||||
"f6" => KeyCode::F(6),
|
||||
"f7" => KeyCode::F(7),
|
||||
"f8" => KeyCode::F(8),
|
||||
"f9" => KeyCode::F(9),
|
||||
"f10" => KeyCode::F(10),
|
||||
"f11" => KeyCode::F(11),
|
||||
"f12" => KeyCode::F(12),
|
||||
"lt" => KeyCode::Char('<'),
|
||||
"gt" => KeyCode::Char('>'),
|
||||
"bar" => KeyCode::Char('|'),
|
||||
"bslash" => KeyCode::Char('\\'),
|
||||
s if s.len() == 1 => {
|
||||
let c = s.chars().next().unwrap();
|
||||
// For Shift+letter with no other modifiers, uppercase it (vim behavior).
|
||||
if modifiers == KeyModifiers::SHIFT && c.is_ascii_alphabetic() {
|
||||
modifiers = KeyModifiers::NONE;
|
||||
KeyCode::Char(c.to_ascii_uppercase())
|
||||
} else {
|
||||
KeyCode::Char(c)
|
||||
}
|
||||
}
|
||||
_ => bail!("unknown key notation: <{notation}>"),
|
||||
};
|
||||
|
||||
Ok(key(code, modifiers))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_literal_text() {
|
||||
let bytes = parse_keys("hello").unwrap();
|
||||
assert_eq!(bytes, b"hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enter() {
|
||||
let bytes = parse_keys("<CR>").unwrap();
|
||||
assert_eq!(bytes, b"\r");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_escape() {
|
||||
let bytes = parse_keys("<Esc>").unwrap();
|
||||
assert_eq!(bytes, b"\x1b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ctrl_c() {
|
||||
let bytes = parse_keys("<C-c>").unwrap();
|
||||
assert_eq!(bytes, b"\x03");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mixed() {
|
||||
let bytes = parse_keys("hello<CR>").unwrap();
|
||||
assert_eq!(&bytes[..5], b"hello");
|
||||
assert_eq!(bytes[5], b'\r');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_case_insensitive() {
|
||||
let a = parse_keys("<cr>").unwrap();
|
||||
let b = parse_keys("<CR>").unwrap();
|
||||
let c = parse_keys("<Cr>").unwrap();
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(b, c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! ptyctl — Headless PTY controller built on alacritty_terminal.
|
||||
//!
|
||||
//! Provides programmatic control of terminal sessions: spawn processes
|
||||
//! in a PTY, send keystrokes, read screen content as text/styled/HTML,
|
||||
//! and expose it all via HTTP REST API.
|
||||
|
||||
pub mod keys;
|
||||
pub mod pty;
|
||||
pub mod server;
|
||||
pub mod session;
|
||||
pub mod styled;
|
||||
pub mod term;
|
||||
pub mod wait;
|
||||
@@ -0,0 +1,155 @@
|
||||
//! PTY wrapper using `portable-pty` for cross-platform pseudoterminal support.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
|
||||
/// Configuration for spawning a PTY session.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PtyConfig {
|
||||
/// Command and arguments to run.
|
||||
pub command: Vec<String>,
|
||||
/// Terminal width in columns.
|
||||
pub cols: u16,
|
||||
/// Terminal height in rows.
|
||||
pub rows: u16,
|
||||
/// Working directory.
|
||||
pub cwd: Option<PathBuf>,
|
||||
/// Additional environment variables.
|
||||
pub env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Handle to a running PTY session.
|
||||
pub struct PtyHandle {
|
||||
master: Box<dyn MasterPty + Send>,
|
||||
child: Box<dyn portable_pty::Child + Send>,
|
||||
reader: Box<dyn Read + Send>,
|
||||
writer: Box<dyn Write + Send>,
|
||||
}
|
||||
|
||||
/// Resize-capable master half of a dismantled [`PtyHandle`].
|
||||
///
|
||||
/// portable-pty's unix master is not `Sync` (interior `RefCell`), so it sits
|
||||
/// behind a mutex that is only held for the synchronous resize ioctl.
|
||||
pub struct PtyMaster {
|
||||
master: std::sync::Mutex<Box<dyn MasterPty + Send>>,
|
||||
}
|
||||
|
||||
impl PtyMaster {
|
||||
/// Resize the PTY (TIOCSWINSZ; the kernel delivers SIGWINCH to the child).
|
||||
pub fn resize(&self, cols: u16, rows: u16) -> Result<()> {
|
||||
self.master
|
||||
.lock()
|
||||
.unwrap()
|
||||
.resize(PtySize {
|
||||
rows,
|
||||
cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
})
|
||||
.context("failed to resize PTY")
|
||||
}
|
||||
}
|
||||
|
||||
/// Child-process half of a dismantled [`PtyHandle`].
|
||||
pub struct PtyChild {
|
||||
child: Box<dyn portable_pty::Child + Send>,
|
||||
}
|
||||
|
||||
impl PtyChild {
|
||||
/// Check if the child process is still alive.
|
||||
pub fn is_alive(&mut self) -> bool {
|
||||
self.child.try_wait().ok().flatten().is_none()
|
||||
}
|
||||
|
||||
/// Get the child process ID.
|
||||
pub fn pid(&self) -> Option<u32> {
|
||||
self.child.process_id()
|
||||
}
|
||||
|
||||
/// Wait for the child to exit and return the exit code.
|
||||
pub fn wait(&mut self) -> Result<u32> {
|
||||
let status = self.child.wait().context("failed to wait for child")?;
|
||||
Ok(status.exit_code())
|
||||
}
|
||||
|
||||
/// Kill the child process.
|
||||
pub fn kill(&mut self) -> Result<()> {
|
||||
self.child.kill().context("failed to kill child process")
|
||||
}
|
||||
}
|
||||
|
||||
impl PtyHandle {
|
||||
/// Spawn a new process in a PTY.
|
||||
pub fn spawn(config: &PtyConfig) -> Result<Self> {
|
||||
let pty_system = native_pty_system();
|
||||
|
||||
let pty_size = PtySize {
|
||||
rows: config.rows,
|
||||
cols: config.cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
};
|
||||
|
||||
let pair = pty_system.openpty(pty_size).context("failed to open PTY")?;
|
||||
|
||||
let mut cmd = CommandBuilder::new(&config.command[0]);
|
||||
if config.command.len() > 1 {
|
||||
cmd.args(&config.command[1..]);
|
||||
}
|
||||
if let Some(ref cwd) = config.cwd {
|
||||
cmd.cwd(cwd);
|
||||
}
|
||||
for (key, value) in &config.env {
|
||||
cmd.env(key, value);
|
||||
}
|
||||
// Set TERM for proper terminal detection.
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
|
||||
let child = pair
|
||||
.slave
|
||||
.spawn_command(cmd)
|
||||
.context("failed to spawn command in PTY")?;
|
||||
|
||||
let reader = pair
|
||||
.master
|
||||
.try_clone_reader()
|
||||
.context("failed to clone PTY reader")?;
|
||||
|
||||
let writer = pair
|
||||
.master
|
||||
.take_writer()
|
||||
.context("failed to take PTY writer")?;
|
||||
|
||||
Ok(Self {
|
||||
master: pair.master,
|
||||
child,
|
||||
reader,
|
||||
writer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Dismantle into the master half (kept for resize), the child half
|
||||
/// (moved into a waiter task), and the reader/writer streams.
|
||||
pub fn into_parts(
|
||||
self,
|
||||
) -> (
|
||||
PtyMaster,
|
||||
PtyChild,
|
||||
Box<dyn Read + Send>,
|
||||
Box<dyn Write + Send>,
|
||||
) {
|
||||
(
|
||||
PtyMaster {
|
||||
master: std::sync::Mutex::new(self.master),
|
||||
},
|
||||
PtyChild { child: self.child },
|
||||
self.reader,
|
||||
self.writer,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
//! HTTP + WebSocket server exposing PTY session control.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Json, Response};
|
||||
use axum::routing::{get, post};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::sync::Mutex;
|
||||
use tower_http::cors::CorsLayer;
|
||||
|
||||
use crate::session::{PtySession, WaitCondition, WaitOutcome};
|
||||
use crate::term::ScreenOpts;
|
||||
|
||||
/// Shared application state.
|
||||
type AppState = Arc<Mutex<PtySession>>;
|
||||
|
||||
/// Query parameters for screen endpoint.
|
||||
#[derive(Debug, serde::Deserialize, Default)]
|
||||
pub struct ScreenParams {
|
||||
/// Row range, 1-indexed (e.g. "1:5", "5:", ":10", "5").
|
||||
pub rows: Option<String>,
|
||||
/// Column range, 1-indexed.
|
||||
pub cols: Option<String>,
|
||||
/// Character to show at cursor position.
|
||||
pub cursor: Option<char>,
|
||||
/// Output format: "text" (default), "styled", "html".
|
||||
pub format: Option<String>,
|
||||
/// Include trailing empty lines.
|
||||
pub full: Option<bool>,
|
||||
}
|
||||
|
||||
/// Request body for send endpoint.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SendRequest {
|
||||
pub keys: String,
|
||||
}
|
||||
|
||||
/// Request body for resize endpoint.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct ResizeRequest {
|
||||
pub cols: u16,
|
||||
pub rows: u16,
|
||||
}
|
||||
|
||||
/// Query parameters for scrollback endpoint.
|
||||
#[derive(Debug, serde::Deserialize, Default)]
|
||||
pub struct ScrollbackParams {
|
||||
/// Number of scrollback lines to return (default: 100).
|
||||
pub lines: Option<usize>,
|
||||
}
|
||||
|
||||
/// Default wait timeout in milliseconds.
|
||||
const WAIT_DEFAULT_TIMEOUT_MS: u64 = 10_000;
|
||||
/// Maximum wait timeout in milliseconds.
|
||||
const WAIT_MAX_TIMEOUT_MS: u64 = 120_000;
|
||||
|
||||
/// Query parameters for wait endpoint — exactly one condition must be set.
|
||||
#[derive(Debug, serde::Deserialize, Default)]
|
||||
pub struct WaitParams {
|
||||
/// Wait until this text appears on screen.
|
||||
pub text: Option<String>,
|
||||
/// Wait until this regex matches the screen text.
|
||||
pub regex: Option<String>,
|
||||
/// Wait until this text is absent from the screen.
|
||||
pub gone: Option<String>,
|
||||
/// Wait until the grid has been unchanged for this many milliseconds.
|
||||
pub stable_ms: Option<u64>,
|
||||
/// Timeout in milliseconds (default 10000, capped at 120000).
|
||||
pub timeout_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// Incoming WebSocket message from client.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
enum WsClientMessage {
|
||||
/// Send raw input text to the PTY.
|
||||
#[serde(rename = "input")]
|
||||
Input { data: String },
|
||||
/// Send vim-notation keys to the PTY.
|
||||
#[serde(rename = "keys")]
|
||||
Keys { keys: String },
|
||||
/// Resize the terminal.
|
||||
#[serde(rename = "resize")]
|
||||
Resize { cols: u16, rows: u16 },
|
||||
}
|
||||
|
||||
/// Build the axum router.
|
||||
pub fn build_router(session: PtySession) -> Router {
|
||||
let state: AppState = Arc::new(Mutex::new(session));
|
||||
|
||||
Router::new()
|
||||
.route("/query/screen", get(handle_screen))
|
||||
.route("/query/cursor", get(handle_cursor))
|
||||
.route("/query/status", get(handle_status))
|
||||
.route("/query/scrollback", get(handle_scrollback))
|
||||
// Top-level on purpose: wait is a synchronization primitive, neither a /query read nor a /control mutation.
|
||||
.route("/wait", get(handle_wait))
|
||||
.route("/control/send", post(handle_send))
|
||||
.route("/control/resize", post(handle_resize))
|
||||
.route("/control/stop", post(handle_stop))
|
||||
.route("/ws", get(handle_ws_upgrade))
|
||||
.layer(CorsLayer::very_permissive())
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Parse a range string like "1:5", "5:", ":10", "5" into a Range<usize>.
|
||||
fn parse_range(s: &str) -> Option<std::ops::Range<usize>> {
|
||||
if let Some((a, b)) = s.split_once(':') {
|
||||
let start = if a.is_empty() {
|
||||
1
|
||||
} else {
|
||||
a.parse::<usize>().ok()?
|
||||
};
|
||||
let end = if b.is_empty() {
|
||||
usize::MAX
|
||||
} else {
|
||||
b.parse::<usize>().ok()?
|
||||
};
|
||||
Some(start..end)
|
||||
} else {
|
||||
let n = s.parse::<usize>().ok()?;
|
||||
Some(n..n + 1)
|
||||
}
|
||||
}
|
||||
|
||||
fn build_screen_opts(params: &ScreenParams) -> ScreenOpts {
|
||||
ScreenOpts {
|
||||
rows: params.rows.as_deref().and_then(parse_range),
|
||||
cols: params.cols.as_deref().and_then(parse_range),
|
||||
cursor_char: params.cursor,
|
||||
include_empty: params.full.unwrap_or(false),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_screen(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<ScreenParams>,
|
||||
) -> Response {
|
||||
let session = state.lock().await;
|
||||
let opts = build_screen_opts(¶ms);
|
||||
|
||||
let format = params.format.as_deref().unwrap_or("text");
|
||||
match format {
|
||||
"styled" => {
|
||||
let styled = session.screen_styled(&opts).await;
|
||||
Json(styled).into_response()
|
||||
}
|
||||
"html" => {
|
||||
let html = session.screen_html(&opts).await;
|
||||
([(axum::http::header::CONTENT_TYPE, "text/html")], html).into_response()
|
||||
}
|
||||
_ => {
|
||||
let output = session.screen(&opts).await;
|
||||
Json(output).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_cursor(State(state): State<AppState>) -> Json<serde_json::Value> {
|
||||
let session = state.lock().await;
|
||||
let cursor = session.cursor().await;
|
||||
Json(serde_json::json!({
|
||||
"row": cursor.row,
|
||||
"col": cursor.col,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn handle_status(State(state): State<AppState>) -> Json<serde_json::Value> {
|
||||
let session = state.lock().await;
|
||||
let status = session.status().await;
|
||||
Json(serde_json::json!({
|
||||
"alive": status.alive,
|
||||
"pid": status.pid,
|
||||
"exit_code": status.exit_code,
|
||||
"size": [status.size.0, status.size.1],
|
||||
"modes": status.modes,
|
||||
"scrollback_lines": status.scrollback_lines,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn handle_send(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<SendRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let session = state.lock().await;
|
||||
match session.send_keys(&req.keys).await {
|
||||
Ok(()) => Ok(Json(serde_json::json!({"ok": true}))),
|
||||
Err(e) => Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_resize(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<ResizeRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let session = state.lock().await;
|
||||
match session.resize(req.cols, req.rows).await {
|
||||
Ok(()) => Ok(Json(serde_json::json!({"ok": true}))),
|
||||
Err(e) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": e.to_string()})),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Long-poll until a screen condition is met or the timeout elapses.
|
||||
///
|
||||
/// Timeout is a normal outcome (200 with `matched: false` + diagnostics),
|
||||
/// not an error — `--gone`/`--stable_ms` waits time out routinely.
|
||||
async fn handle_wait(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<WaitParams>,
|
||||
) -> Result<Json<WaitOutcome>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let mut conditions = Vec::new();
|
||||
if let Some(text) = params.text {
|
||||
conditions.push(WaitCondition::Text(text));
|
||||
}
|
||||
if let Some(pattern) = params.regex {
|
||||
conditions.push(WaitCondition::Regex(pattern));
|
||||
}
|
||||
if let Some(text) = params.gone {
|
||||
conditions.push(WaitCondition::Gone(text));
|
||||
}
|
||||
if let Some(ms) = params.stable_ms {
|
||||
conditions.push(WaitCondition::StableMs(ms));
|
||||
}
|
||||
let (Some(condition), true) = (conditions.pop(), conditions.is_empty()) else {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "exactly one of text, regex, gone, stable_ms is required"
|
||||
})),
|
||||
));
|
||||
};
|
||||
let timeout_ms = params
|
||||
.timeout_ms
|
||||
.unwrap_or(WAIT_DEFAULT_TIMEOUT_MS)
|
||||
.min(WAIT_MAX_TIMEOUT_MS);
|
||||
|
||||
// Clone the wait handles and drop the session guard, or send/screen would block for the whole wait.
|
||||
let handle = state.lock().await.wait_handle();
|
||||
match handle
|
||||
.wait_for(condition, std::time::Duration::from_millis(timeout_ms))
|
||||
.await
|
||||
{
|
||||
Ok(outcome) => Ok(Json(outcome)),
|
||||
// Alternate format keeps the regex parse detail from the error chain.
|
||||
Err(e) => Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({"error": format!("{e:#}")})),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_stop(State(state): State<AppState>) -> Json<serde_json::Value> {
|
||||
let mut session = state.lock().await;
|
||||
let _ = session.stop().await;
|
||||
Json(serde_json::json!({"ok": true}))
|
||||
}
|
||||
|
||||
// -- Scrollback --
|
||||
|
||||
async fn handle_scrollback(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<ScrollbackParams>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let session = state.lock().await;
|
||||
let count = params.lines.unwrap_or(100);
|
||||
let lines = session.scrollback(count).await;
|
||||
Json(serde_json::json!({
|
||||
"count": lines.len(),
|
||||
"lines": lines,
|
||||
}))
|
||||
}
|
||||
|
||||
// -- WebSocket streaming --
|
||||
|
||||
/// Upgrade an HTTP request to a WebSocket connection.
|
||||
async fn handle_ws_upgrade(
|
||||
State(state): State<AppState>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> impl IntoResponse {
|
||||
ws.on_upgrade(move |socket| handle_ws_connection(socket, state))
|
||||
}
|
||||
|
||||
/// Handle a single WebSocket connection.
|
||||
///
|
||||
/// Protocol:
|
||||
///
|
||||
/// **Server -> Client:**
|
||||
/// - Binary frames: raw PTY output bytes (high-throughput streaming)
|
||||
/// - Text frames: JSON `{"type":"closed","exit_code":N}` on process exit
|
||||
///
|
||||
/// **Client -> Server:**
|
||||
/// - Binary frames: raw bytes written to PTY stdin
|
||||
/// - Text frames: JSON with `type` field:
|
||||
/// - `{"type":"input","data":"text"}` — send text to PTY
|
||||
/// - `{"type":"keys","keys":"<C-c>"}` — vim-notation keystrokes
|
||||
/// - `{"type":"resize","cols":120,"rows":40}` — resize terminal
|
||||
async fn handle_ws_connection(socket: WebSocket, state: AppState) {
|
||||
let (mut ws_tx, mut ws_rx) = socket.split();
|
||||
|
||||
// Subscribe to the PTY output broadcast channel.
|
||||
let session = state.lock().await;
|
||||
let mut output_rx = session.subscribe();
|
||||
drop(session);
|
||||
|
||||
// Task: forward PTY output -> WebSocket (binary frames).
|
||||
let state_output = state.clone();
|
||||
let mut send_task = tokio::spawn(async move {
|
||||
loop {
|
||||
match output_rx.recv().await {
|
||||
Ok(bytes) => {
|
||||
if ws_tx.send(Message::Binary(bytes.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
|
||||
// Client is too slow; send a warning and continue.
|
||||
let msg = serde_json::json!({
|
||||
"type": "warning",
|
||||
"message": format!("dropped {n} output chunks (slow consumer)"),
|
||||
});
|
||||
let _ = ws_tx.send(Message::Text(msg.to_string().into())).await;
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
|
||||
// PTY output channel closed — process likely exited.
|
||||
let session = state_output.lock().await;
|
||||
let status = session.status().await;
|
||||
let msg = serde_json::json!({
|
||||
"type": "closed",
|
||||
"exit_code": status.exit_code,
|
||||
});
|
||||
let _ = ws_tx.send(Message::Text(msg.to_string().into())).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Task: receive WebSocket messages -> PTY input / control.
|
||||
let state_input = state.clone();
|
||||
let mut recv_task = tokio::spawn(async move {
|
||||
while let Some(Ok(msg)) = ws_rx.next().await {
|
||||
match msg {
|
||||
Message::Binary(bytes) => {
|
||||
// Raw binary input -> PTY.
|
||||
let session = state_input.lock().await;
|
||||
let _ = session.send_bytes(&bytes).await;
|
||||
}
|
||||
Message::Text(text) => {
|
||||
// JSON-structured command.
|
||||
if let Ok(cmd) = serde_json::from_str::<WsClientMessage>(&text) {
|
||||
let session = state_input.lock().await;
|
||||
match cmd {
|
||||
WsClientMessage::Input { data } => {
|
||||
let _ = session.send_bytes(data.as_bytes()).await;
|
||||
}
|
||||
WsClientMessage::Keys { keys: notation } => {
|
||||
let _ = session.send_keys(¬ation).await;
|
||||
}
|
||||
WsClientMessage::Resize { cols, rows } => {
|
||||
let _ = session.resize(cols, rows).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::Close(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for either task to finish, then abort the other.
|
||||
tokio::select! {
|
||||
_ = &mut send_task => recv_task.abort(),
|
||||
_ = &mut recv_task => send_task.abort(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use crate::session::tests::start_session;
|
||||
|
||||
/// Send one raw HTTP/1.1 request and read the full response (Connection: close).
|
||||
async fn http(port: u16, request: &str) -> String {
|
||||
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
|
||||
.await
|
||||
.expect("connect failed");
|
||||
stream
|
||||
.write_all(request.as_bytes())
|
||||
.await
|
||||
.expect("write failed");
|
||||
let mut response = Vec::new();
|
||||
stream
|
||||
.read_to_end(&mut response)
|
||||
.await
|
||||
.expect("read failed");
|
||||
String::from_utf8_lossy(&response).into_owned()
|
||||
}
|
||||
|
||||
fn get(path: &str) -> String {
|
||||
format!("GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
|
||||
}
|
||||
|
||||
fn post_json(path: &str, body: &str) -> String {
|
||||
format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
/// A long-poll /wait must not hold the session mutex: the send and screen
|
||||
/// requests served mid-wait are exactly what make the wait complete.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_does_not_block_other_endpoints() {
|
||||
let session = start_session(vec!["/bin/sh".into()]).await;
|
||||
let router = super::build_router(session);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, router).await;
|
||||
});
|
||||
|
||||
let start = Instant::now();
|
||||
// Long-poll for text that only appears if /control/send gets through mid-wait.
|
||||
let wait_task = tokio::spawn(async move {
|
||||
http(port, &get("/wait?text=WAIT_DONE_77&timeout_ms=30000")).await
|
||||
});
|
||||
|
||||
// /query/screen must answer while the wait is in flight (deadline-polled).
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let resp = http(port, &get("/query/screen")).await;
|
||||
if resp.starts_with("HTTP/1.1 200") {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"screen not served during wait: {resp}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
|
||||
let resp = http(
|
||||
port,
|
||||
&post_json("/control/send", r#"{"keys":"echo WAIT_DONE_77<CR>"}"#),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
resp.starts_with("HTTP/1.1 200"),
|
||||
"send not served during wait: {resp}"
|
||||
);
|
||||
|
||||
let wait_resp = wait_task.await.unwrap();
|
||||
assert!(wait_resp.starts_with("HTTP/1.1 200"), "{wait_resp}");
|
||||
assert!(wait_resp.contains(r#""matched":true"#), "{wait_resp}");
|
||||
// A deadlocked handler could only return at its 30s timeout.
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_secs(10),
|
||||
"wait took {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
|
||||
// Zero or multiple conditions are usage errors.
|
||||
let resp = http(port, &get("/wait")).await;
|
||||
assert!(resp.starts_with("HTTP/1.1 400"), "{resp}");
|
||||
let resp = http(port, &get("/wait?text=a&gone=b")).await;
|
||||
assert!(resp.starts_with("HTTP/1.1 400"), "{resp}");
|
||||
|
||||
// Bounded shutdown so the shell doesn't outlive the test.
|
||||
let resp = http(port, &post_json("/control/send", r#"{"keys":"exit<CR>"}"#)).await;
|
||||
assert!(resp.starts_with("HTTP/1.1 200"), "{resp}");
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let resp = http(port, &get("/query/status")).await;
|
||||
if resp.contains(r#""alive":false"#) {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "shell did not exit: {resp}");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
//! Core PTY session — ties PTY + Terminal + I/O channels together.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::io::Read;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::sync::{Mutex, broadcast, mpsc, watch};
|
||||
|
||||
use crate::keys;
|
||||
use crate::pty::{PtyConfig, PtyHandle, PtyMaster};
|
||||
use crate::styled::StyledLine;
|
||||
use crate::term::{
|
||||
CursorPosition, ScreenOpts, ScreenOutput, ScrollbackLine, SessionListener, Terminal,
|
||||
TerminalModes,
|
||||
};
|
||||
// Re-exported so existing `session::Wait*` paths keep working after the wait-module extraction.
|
||||
use crate::wait::{RAW_TAIL_CAP, push_raw_tail};
|
||||
pub use crate::wait::{WaitCondition, WaitDiagnostics, WaitHandle, WaitOutcome};
|
||||
|
||||
/// Configuration for starting a session.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SessionConfig {
|
||||
pub pty: PtyConfig,
|
||||
/// Auto-shutdown timeout in seconds (None = no timeout).
|
||||
pub timeout: Option<u64>,
|
||||
/// Keep server running after child exits.
|
||||
pub linger: bool,
|
||||
}
|
||||
|
||||
/// Status of a PTY session.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct SessionStatus {
|
||||
pub alive: bool,
|
||||
pub pid: Option<u32>,
|
||||
pub exit_code: Option<u32>,
|
||||
pub size: (u16, u16),
|
||||
pub modes: TerminalModes,
|
||||
pub scrollback_lines: usize,
|
||||
}
|
||||
|
||||
/// A running PTY session.
|
||||
pub struct PtySession {
|
||||
terminal: Arc<Mutex<Terminal>>,
|
||||
/// Master half of the PTY, kept here so resize reaches the real PTY.
|
||||
master: PtyMaster,
|
||||
pty_write_tx: mpsc::UnboundedSender<Vec<u8>>,
|
||||
alive: Arc<AtomicBool>,
|
||||
exit_code: Arc<std::sync::Mutex<Option<u32>>>,
|
||||
pid: Option<u32>,
|
||||
/// Grid generation counter, bumped by the feeder after each `term.feed()`.
|
||||
generation_rx: watch::Receiver<u64>,
|
||||
/// Weak so the feeder's exit still drops the sender, signalling "ended" to waiters;
|
||||
/// lets `resize` bump the generation too (a resize changes the grid without output).
|
||||
generation_tx: Weak<watch::Sender<u64>>,
|
||||
/// Last [`RAW_TAIL_CAP`] bytes of raw PTY output for wait-timeout diagnostics.
|
||||
raw_tail: Arc<std::sync::Mutex<VecDeque<u8>>>,
|
||||
_shutdown_tx: Option<mpsc::Sender<()>>,
|
||||
/// Broadcast channel for real-time PTY output streaming (WebSocket).
|
||||
output_tx: broadcast::Sender<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl PtySession {
|
||||
/// Start a new PTY session.
|
||||
pub async fn start(config: SessionConfig) -> Result<Self> {
|
||||
let cols = config.pty.cols;
|
||||
let rows = config.pty.rows;
|
||||
|
||||
// Spawn the PTY process; keep the master half for resize, only the child half moves into the waiter task.
|
||||
let pty = PtyHandle::spawn(&config.pty).context("failed to spawn PTY")?;
|
||||
let (master, mut child, mut reader, mut writer) = pty.into_parts();
|
||||
let pid = child.pid();
|
||||
|
||||
// Channel for terminal-generated PtyWrite responses.
|
||||
let (pty_response_tx, mut pty_response_rx) = mpsc::unbounded_channel::<Vec<u8>>();
|
||||
|
||||
// Channel for user-initiated writes (send_keys, send_bytes).
|
||||
let (pty_write_tx, mut pty_write_rx) = mpsc::unbounded_channel::<Vec<u8>>();
|
||||
|
||||
// Channel for PTY reader -> terminal feeder.
|
||||
let (pty_read_tx, mut pty_read_rx) = mpsc::unbounded_channel::<Vec<u8>>();
|
||||
|
||||
// Broadcast channel for WebSocket streaming (capacity: 256 chunks).
|
||||
let (output_tx, _) = broadcast::channel::<Vec<u8>>(256);
|
||||
|
||||
// Grid-generation watch for event-driven waits (watch over Notify: check-then-wait is lost-wakeup-free).
|
||||
// The feeder holds the only strong Arc so its exit still drops the sender ("ended" signal).
|
||||
let (generation_tx, generation_rx) = watch::channel::<u64>(0);
|
||||
let generation_tx = Arc::new(generation_tx);
|
||||
let generation_tx_weak = Arc::downgrade(&generation_tx);
|
||||
let raw_tail: Arc<std::sync::Mutex<VecDeque<u8>>> =
|
||||
Arc::new(std::sync::Mutex::new(VecDeque::with_capacity(RAW_TAIL_CAP)));
|
||||
|
||||
// Shutdown signal.
|
||||
let (shutdown_tx, _shutdown_rx) = mpsc::channel::<()>(1);
|
||||
|
||||
// Create the terminal.
|
||||
let listener = SessionListener::new(pty_response_tx);
|
||||
let terminal = Arc::new(Mutex::new(Terminal::new(cols, rows, listener)));
|
||||
let alive = Arc::new(AtomicBool::new(true));
|
||||
let exit_code: Arc<std::sync::Mutex<Option<u32>>> = Arc::new(std::sync::Mutex::new(None));
|
||||
|
||||
// --- PTY Reader Thread (blocking) ---
|
||||
let alive_reader = alive.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("pty-reader".into())
|
||||
.spawn(move || {
|
||||
let mut buf = [0u8; 65536];
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
if pty_read_tx.send(buf[..n].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if e.kind() != std::io::ErrorKind::WouldBlock {
|
||||
log::debug!("PTY read error: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
alive_reader.store(false, Ordering::SeqCst);
|
||||
})
|
||||
.context("failed to spawn PTY reader thread")?;
|
||||
|
||||
// --- PTY Writer Task (async) ---
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(bytes) = pty_write_rx.recv() => {
|
||||
if let Err(e) = std::io::Write::write_all(&mut writer, &bytes) {
|
||||
log::debug!("PTY write error: {e}");
|
||||
break;
|
||||
}
|
||||
let _ = std::io::Write::flush(&mut writer);
|
||||
}
|
||||
Some(bytes) = pty_response_rx.recv() => {
|
||||
if let Err(e) = std::io::Write::write_all(&mut writer, &bytes) {
|
||||
log::debug!("PTY response write error: {e}");
|
||||
break;
|
||||
}
|
||||
let _ = std::io::Write::flush(&mut writer);
|
||||
}
|
||||
else => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// --- Terminal Feeder Task (async) ---
|
||||
let terminal_feeder = terminal.clone();
|
||||
let output_tx_feeder = output_tx.clone();
|
||||
let raw_tail_feeder = raw_tail.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(bytes) = pty_read_rx.recv().await {
|
||||
// Broadcast raw PTY output to all WebSocket subscribers.
|
||||
// Ignore errors (no active subscribers is fine).
|
||||
let _ = output_tx_feeder.send(bytes.clone());
|
||||
|
||||
push_raw_tail(&raw_tail_feeder, &bytes);
|
||||
|
||||
{
|
||||
let mut term = terminal_feeder.lock().await;
|
||||
term.feed(&bytes);
|
||||
}
|
||||
// Bump only after term.feed(): a waiter woken by the broadcast above would read a stale grid.
|
||||
generation_tx.send_modify(|g| *g += 1);
|
||||
}
|
||||
});
|
||||
|
||||
// --- Child Process Waiter ---
|
||||
let alive_waiter = alive.clone();
|
||||
let exit_code_waiter = exit_code.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
if !alive_waiter.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
if !child.is_alive() {
|
||||
if let Ok(code) = child.wait() {
|
||||
*exit_code_waiter.lock().unwrap() = Some(code);
|
||||
}
|
||||
alive_waiter.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
terminal,
|
||||
master,
|
||||
pty_write_tx,
|
||||
alive,
|
||||
exit_code,
|
||||
pid,
|
||||
generation_rx,
|
||||
generation_tx: generation_tx_weak,
|
||||
raw_tail,
|
||||
_shutdown_tx: Some(shutdown_tx),
|
||||
output_tx,
|
||||
})
|
||||
}
|
||||
|
||||
/// Send keystrokes using vim notation (e.g. `"<C-c>"`, `"hello<CR>"`).
|
||||
pub async fn send_keys(&self, notation: &str) -> Result<()> {
|
||||
let bytes = keys::parse_keys(notation)?;
|
||||
self.send_bytes(&bytes).await
|
||||
}
|
||||
|
||||
/// Send raw bytes to the PTY.
|
||||
pub async fn send_bytes(&self, bytes: &[u8]) -> Result<()> {
|
||||
self.pty_write_tx
|
||||
.send(bytes.to_vec())
|
||||
.map_err(|_| anyhow::anyhow!("PTY write channel closed"))
|
||||
}
|
||||
|
||||
/// Read screen content as plain text.
|
||||
pub async fn screen(&self, opts: &ScreenOpts) -> ScreenOutput {
|
||||
let term = self.terminal.lock().await;
|
||||
term.screen_content(opts)
|
||||
}
|
||||
|
||||
/// Read screen content with style information.
|
||||
pub async fn screen_styled(&self, opts: &ScreenOpts) -> Vec<StyledLine> {
|
||||
let term = self.terminal.lock().await;
|
||||
term.screen_styled(opts)
|
||||
}
|
||||
|
||||
/// Read screen content as HTML.
|
||||
pub async fn screen_html(&self, opts: &ScreenOpts) -> String {
|
||||
let term = self.terminal.lock().await;
|
||||
term.screen_html(opts)
|
||||
}
|
||||
|
||||
/// Get cursor position (1-indexed).
|
||||
pub async fn cursor(&self) -> CursorPosition {
|
||||
let term = self.terminal.lock().await;
|
||||
term.cursor_position()
|
||||
}
|
||||
|
||||
/// Get session status (basic info, no terminal lock needed).
|
||||
pub fn status_basic(&self) -> (bool, Option<u32>, Option<u32>) {
|
||||
(
|
||||
self.alive.load(Ordering::SeqCst),
|
||||
self.pid,
|
||||
*self.exit_code.lock().unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Get full session status including terminal modes.
|
||||
pub async fn status(&self) -> SessionStatus {
|
||||
let (alive, pid, exit_code) = self.status_basic();
|
||||
let term = self.terminal.lock().await;
|
||||
// Size comes from the grid under the same lock resize holds, so it can never be torn.
|
||||
let size = term.size();
|
||||
SessionStatus {
|
||||
alive,
|
||||
pid,
|
||||
exit_code,
|
||||
size: (size.cols as u16, size.rows as u16),
|
||||
modes: term.terminal_modes(),
|
||||
scrollback_lines: term.scrollback_count(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resize the real PTY and the terminal grid.
|
||||
pub async fn resize(&self, cols: u16, rows: u16) -> Result<()> {
|
||||
let mut term = self.terminal.lock().await;
|
||||
// PTY first (fail-fast); the held terminal lock keeps the SIGWINCH redraw out of a stale grid.
|
||||
self.master.resize(cols, rows)?;
|
||||
term.resize(cols, rows);
|
||||
// Bump after the grid resize (matching the feeder's post-feed ordering): reflow/clipping
|
||||
// changes screen text, so in-flight waits must re-check — and StableMs must restart.
|
||||
if let Some(generation_tx) = self.generation_tx.upgrade() {
|
||||
generation_tx.send_modify(|g| *g += 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if the child process is still alive.
|
||||
pub fn is_alive(&self) -> bool {
|
||||
self.alive.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Subscribe to real-time PTY output for WebSocket streaming.
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<Vec<u8>> {
|
||||
self.output_tx.subscribe()
|
||||
}
|
||||
|
||||
/// Read scrollback history lines.
|
||||
pub async fn scrollback(&self, count: usize) -> Vec<ScrollbackLine> {
|
||||
let term = self.terminal.lock().await;
|
||||
term.scrollback_lines(count)
|
||||
}
|
||||
|
||||
/// Clone the handles needed to wait without holding any outer session lock.
|
||||
pub fn wait_handle(&self) -> WaitHandle {
|
||||
WaitHandle {
|
||||
terminal: self.terminal.clone(),
|
||||
generation_rx: self.generation_rx.clone(),
|
||||
raw_tail: self.raw_tail.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until `condition` is met or `timeout` elapses.
|
||||
pub async fn wait_for(
|
||||
&self,
|
||||
condition: WaitCondition,
|
||||
timeout: Duration,
|
||||
) -> Result<WaitOutcome> {
|
||||
self.wait_handle().wait_for(condition, timeout).await
|
||||
}
|
||||
|
||||
/// Stop the session.
|
||||
pub async fn stop(&mut self) -> Result<()> {
|
||||
if let Some(tx) = self._shutdown_tx.take() {
|
||||
let _ = tx.send(()).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Start a session running `command` at 80x24.
|
||||
pub(crate) async fn start_session(command: Vec<String>) -> PtySession {
|
||||
PtySession::start(SessionConfig {
|
||||
pty: PtyConfig {
|
||||
command,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: None,
|
||||
env: HashMap::new(),
|
||||
},
|
||||
timeout: None,
|
||||
linger: false,
|
||||
})
|
||||
.await
|
||||
.expect("failed to start session")
|
||||
}
|
||||
|
||||
/// Send `keys` then wait (bounded) for the child to exit, so the shell and
|
||||
/// reader thread don't outlive the test.
|
||||
pub(crate) async fn shutdown(session: &PtySession, keys: &str) {
|
||||
session.send_keys(keys).await.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while session.is_alive() {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"child did not exit after {keys:?}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll the screen until `pred` matches, panicking with the last screen on timeout.
|
||||
async fn wait_for_screen(session: &PtySession, pred: impl Fn(&str) -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let screen = session.screen(&ScreenOpts::default()).await;
|
||||
let text = screen.lines.join("\n");
|
||||
if pred(&text) {
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for screen; last screen:\n{text}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The child must observe a resize on its own TTY (TIOCSWINSZ), not just the emulator grid.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn resize_reaches_child_process() {
|
||||
let session = start_session(vec!["/bin/sh".into()]).await;
|
||||
|
||||
// `stty size` prints "rows cols" as reported by the child's TTY.
|
||||
session.send_keys("stty size<CR>").await.unwrap();
|
||||
wait_for_screen(&session, |s| s.contains("24 80")).await;
|
||||
|
||||
session.resize(120, 40).await.unwrap();
|
||||
let screen = session.screen(&ScreenOpts::default()).await;
|
||||
assert_eq!((screen.size.cols, screen.size.rows), (120, 40));
|
||||
|
||||
session.send_keys("stty size<CR>").await.unwrap();
|
||||
wait_for_screen(&session, |s| s.contains("40 120")).await;
|
||||
|
||||
shutdown(&session, "exit<CR>").await;
|
||||
}
|
||||
|
||||
/// resize() must bump the wait generation: a resize reflows/clips the grid without
|
||||
/// any PTY output, so in-flight waits would otherwise sleep through the change.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn resize_bumps_wait_generation() {
|
||||
// A child that never writes: the resize is the only possible generation bump.
|
||||
let session = start_session(vec!["/bin/sleep".into(), "30".into()]).await;
|
||||
|
||||
let mut generation_rx = session.wait_handle().generation_rx;
|
||||
let before = *generation_rx.borrow_and_update();
|
||||
|
||||
session.resize(120, 40).await.unwrap();
|
||||
|
||||
// The bump happens inside resize(), so it is visible as soon as resize returns.
|
||||
assert!(
|
||||
*generation_rx.borrow() > before,
|
||||
"resize did not bump the wait generation (still {before})"
|
||||
);
|
||||
|
||||
shutdown(&session, "<C-c>").await;
|
||||
}
|
||||
|
||||
/// wait_for(Text) returns as soon as delayed output lands, not at the timeout.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_text_matches_delayed_output() {
|
||||
let session = start_session(vec![
|
||||
"/bin/sh".into(),
|
||||
"-c".into(),
|
||||
"sleep 0.3; echo READY; sleep 30".into(),
|
||||
])
|
||||
.await;
|
||||
|
||||
let outcome = session
|
||||
.wait_for(WaitCondition::Text("READY".into()), Duration::from_secs(10))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(outcome.matched, "expected match: {outcome:?}");
|
||||
assert!(outcome.diagnostics.is_none());
|
||||
// Event-driven completion: far below the 10s timeout despite the delayed echo.
|
||||
assert!(
|
||||
outcome.elapsed_ms < 5000,
|
||||
"elapsed_ms = {}",
|
||||
outcome.elapsed_ms
|
||||
);
|
||||
|
||||
// Interrupt the trailing `sleep 30` so the child exits.
|
||||
shutdown(&session, "<C-c>").await;
|
||||
}
|
||||
|
||||
/// A wait for absent text times out at the deadline and carries the diagnostic snapshot.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_timeout_carries_diagnostics() {
|
||||
let session = start_session(vec!["/bin/sh".into()]).await;
|
||||
session
|
||||
.send_keys("echo hello-from-the-shell<CR>")
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for_screen(&session, |s| s.contains("hello-from-the-shell")).await;
|
||||
|
||||
let outcome = session
|
||||
.wait_for(
|
||||
WaitCondition::Text("NEVER_APPEARS_123".into()),
|
||||
Duration::from_millis(1000),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!outcome.matched);
|
||||
// Timed out at the deadline (with scheduler tolerance), neither early nor far late.
|
||||
assert!(
|
||||
(950..4000).contains(&outcome.elapsed_ms),
|
||||
"elapsed_ms = {}",
|
||||
outcome.elapsed_ms
|
||||
);
|
||||
let diag = outcome.diagnostics.expect("timeout must carry diagnostics");
|
||||
assert!(diag.screen.contains("hello-from-the-shell"));
|
||||
assert!(diag.raw_tail.contains("hello-from-the-shell"));
|
||||
assert!(diag.generation > 0);
|
||||
assert!(diag.cursor.row >= 1);
|
||||
assert!(!diag.ended, "deadline timeout must not be flagged as ended");
|
||||
|
||||
// Once the child exits the grid is final: the wait fails fast, flagged `ended`.
|
||||
shutdown(&session, "exit<CR>").await;
|
||||
let outcome = session
|
||||
.wait_for(
|
||||
WaitCondition::Text("NEVER_APPEARS_123".into()),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!outcome.matched);
|
||||
assert!(
|
||||
outcome.elapsed_ms < 5000,
|
||||
"fail-fast took {}ms",
|
||||
outcome.elapsed_ms
|
||||
);
|
||||
assert!(outcome.diagnostics.expect("diagnostics on ended").ended);
|
||||
}
|
||||
|
||||
/// wait_for(Gone) matches once the text is cleared from the screen.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_gone_matches_after_clear() {
|
||||
let session = start_session(vec!["/bin/sh".into()]).await;
|
||||
session.send_keys("echo MARKER_GONE_42<CR>").await.unwrap();
|
||||
let outcome = session
|
||||
.wait_for(
|
||||
WaitCondition::Text("MARKER_GONE_42".into()),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(outcome.matched);
|
||||
|
||||
// Clear the screen and home the cursor; the marker must vanish from the grid.
|
||||
session
|
||||
.send_keys(r"printf '\033[2J\033[H'<CR>")
|
||||
.await
|
||||
.unwrap();
|
||||
let outcome = session
|
||||
.wait_for(
|
||||
WaitCondition::Gone("MARKER_GONE_42".into()),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(outcome.matched, "marker still on screen: {outcome:?}");
|
||||
|
||||
shutdown(&session, "exit<CR>").await;
|
||||
}
|
||||
|
||||
/// wait_for(StableMs) matches once output quiesces, never before the window elapses.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_stable_matches_after_quiesce() {
|
||||
let session = start_session(vec!["/bin/sh".into()]).await;
|
||||
session.send_keys("echo quiesce-now<CR>").await.unwrap();
|
||||
|
||||
let outcome = session
|
||||
.wait_for(WaitCondition::StableMs(400), Duration::from_secs(10))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(outcome.matched, "screen never stabilized: {outcome:?}");
|
||||
// A full uninterrupted window is a lower bound on the elapsed time.
|
||||
assert!(
|
||||
outcome.elapsed_ms >= 400,
|
||||
"elapsed_ms = {}",
|
||||
outcome.elapsed_ms
|
||||
);
|
||||
|
||||
shutdown(&session, "exit<CR>").await;
|
||||
}
|
||||
|
||||
/// wait_for(StableMs) treats a resize as grid activity: the stability window restarts.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_stable_restarts_window_on_resize() {
|
||||
// A child that never writes: the resize is the only grid activity.
|
||||
let session = start_session(vec!["/bin/sleep".into(), "30".into()]).await;
|
||||
|
||||
let wait = tokio::spawn(
|
||||
session
|
||||
.wait_handle()
|
||||
.wait_for(WaitCondition::StableMs(800), Duration::from_secs(10)),
|
||||
);
|
||||
// Land the resize inside the first stability window.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
session.resize(100, 30).await.unwrap();
|
||||
let resized_at = Instant::now();
|
||||
|
||||
let outcome = wait.await.unwrap().unwrap();
|
||||
assert!(outcome.matched, "screen never stabilized: {outcome:?}");
|
||||
// A full window must elapse after the resize; without the restart the wait
|
||||
// matches off the original window, well under 800ms after the resize.
|
||||
assert!(
|
||||
resized_at.elapsed() >= Duration::from_millis(800),
|
||||
"stability window did not restart on resize (completed {:?} after it)",
|
||||
resized_at.elapsed()
|
||||
);
|
||||
|
||||
shutdown(&session, "<C-c>").await;
|
||||
}
|
||||
|
||||
/// wait_for(Regex) matches the screen text; invalid patterns error instead of waiting.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn wait_regex_matches() {
|
||||
let session = start_session(vec!["/bin/sh".into()]).await;
|
||||
session.send_keys("echo exit code 42<CR>").await.unwrap();
|
||||
let outcome = session
|
||||
.wait_for(
|
||||
WaitCondition::Regex(r"exit code \d+".into()),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(outcome.matched);
|
||||
|
||||
assert!(
|
||||
session
|
||||
.wait_for(
|
||||
WaitCondition::Regex("(unclosed".into()),
|
||||
Duration::from_secs(1)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
shutdown(&session, "exit<CR>").await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Styled output formatters — styled JSON and HTML rendering.
|
||||
//!
|
||||
//! Converts the terminal grid into structured representations that preserve
|
||||
//! color and text attribute information for LLM consumption.
|
||||
|
||||
use alacritty_terminal::grid::Row;
|
||||
use alacritty_terminal::index::Column;
|
||||
use alacritty_terminal::term::cell::{Cell, Flags};
|
||||
use alacritty_terminal::vte::ansi::{Color, NamedColor};
|
||||
|
||||
use crate::term::{CursorPosition, ScreenOpts, TerminalSize};
|
||||
|
||||
/// A single styled run of text with uniform attributes.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct StyledRun {
|
||||
pub text: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fg: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bg: Option<String>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub bold: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub italic: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub underline: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub strikeout: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub dim: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub inverse: bool,
|
||||
}
|
||||
|
||||
fn is_false(v: &bool) -> bool {
|
||||
!v
|
||||
}
|
||||
|
||||
/// A single line of styled content.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct StyledLine {
|
||||
pub line: usize,
|
||||
pub runs: Vec<StyledRun>,
|
||||
}
|
||||
|
||||
/// Style attributes for a cell, used for run-length coalescing.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct CellStyle {
|
||||
fg: Option<String>,
|
||||
bg: Option<String>,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
underline: bool,
|
||||
strikeout: bool,
|
||||
dim: bool,
|
||||
inverse: bool,
|
||||
}
|
||||
|
||||
impl CellStyle {
|
||||
fn from_cell(cell: &Cell) -> Self {
|
||||
let flags = cell.flags;
|
||||
Self {
|
||||
fg: color_to_css(&cell.fg),
|
||||
bg: color_to_css(&cell.bg),
|
||||
bold: flags.contains(Flags::BOLD),
|
||||
italic: flags.contains(Flags::ITALIC),
|
||||
underline: flags.intersects(Flags::ALL_UNDERLINES),
|
||||
strikeout: flags.contains(Flags::STRIKEOUT),
|
||||
dim: flags.contains(Flags::DIM),
|
||||
inverse: flags.contains(Flags::INVERSE),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_run(&self, text: String) -> StyledRun {
|
||||
StyledRun {
|
||||
text,
|
||||
fg: self.fg.clone(),
|
||||
bg: self.bg.clone(),
|
||||
bold: self.bold,
|
||||
italic: self.italic,
|
||||
underline: self.underline,
|
||||
strikeout: self.strikeout,
|
||||
dim: self.dim,
|
||||
inverse: self.inverse,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a styled line from a grid row by coalescing consecutive cells
|
||||
/// with identical style into runs.
|
||||
pub fn extract_styled_line(
|
||||
row: &Row<Cell>,
|
||||
col_start: usize,
|
||||
col_end: usize,
|
||||
line_number: usize,
|
||||
cursor: &CursorPosition,
|
||||
opts: &ScreenOpts,
|
||||
) -> StyledLine {
|
||||
let mut runs = Vec::new();
|
||||
let mut current_text = String::new();
|
||||
let mut current_style: Option<CellStyle> = None;
|
||||
|
||||
for col_idx in col_start..col_end {
|
||||
let cell = &row[Column(col_idx)];
|
||||
|
||||
// Skip wide char spacers.
|
||||
if cell
|
||||
.flags
|
||||
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let style = CellStyle::from_cell(cell);
|
||||
|
||||
// Determine the character to emit.
|
||||
let is_cursor = cursor.row == line_number && cursor.col == col_idx + 1;
|
||||
let ch = if is_cursor && opts.cursor_char.is_some() {
|
||||
opts.cursor_char.unwrap()
|
||||
} else {
|
||||
cell.c
|
||||
};
|
||||
|
||||
// If style changed, flush the current run.
|
||||
if let Some(ref cur) = current_style {
|
||||
if *cur != style {
|
||||
if !current_text.is_empty() {
|
||||
runs.push(cur.to_run(std::mem::take(&mut current_text)));
|
||||
}
|
||||
current_style = Some(style);
|
||||
}
|
||||
} else {
|
||||
current_style = Some(style);
|
||||
}
|
||||
|
||||
current_text.push(ch);
|
||||
if let Some(zw) = cell.zerowidth() {
|
||||
for &c in zw {
|
||||
current_text.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush remaining.
|
||||
if !current_text.is_empty()
|
||||
&& let Some(ref style) = current_style
|
||||
{
|
||||
runs.push(style.to_run(current_text));
|
||||
}
|
||||
|
||||
// Trim trailing whitespace-only runs with default style.
|
||||
while runs
|
||||
.last()
|
||||
.is_some_and(|r| r.text.trim().is_empty() && r.fg.is_none() && r.bg.is_none() && !r.bold)
|
||||
{
|
||||
runs.pop();
|
||||
}
|
||||
|
||||
StyledLine {
|
||||
line: line_number,
|
||||
runs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Render styled lines as an HTML document.
|
||||
pub fn render_html(lines: &[StyledLine], _cursor: &CursorPosition, _size: &TerminalSize) -> String {
|
||||
let mut html = String::new();
|
||||
html.push_str("<!DOCTYPE html>\n<html>\n<head>\n");
|
||||
html.push_str("<meta charset=\"utf-8\">\n");
|
||||
html.push_str("<style>\n");
|
||||
html.push_str("body { background: #1e1e1e; margin: 0; padding: 16px; }\n");
|
||||
html.push_str("pre { font-family: 'Menlo', 'Monaco', 'Courier New', monospace; ");
|
||||
html.push_str("font-size: 14px; line-height: 1.4; color: #d4d4d4; margin: 0; }\n");
|
||||
html.push_str(".cursor { background: #d4d4d4; color: #1e1e1e; }\n");
|
||||
html.push_str(".bold { font-weight: bold; }\n");
|
||||
html.push_str(".italic { font-style: italic; }\n");
|
||||
html.push_str(".underline { text-decoration: underline; }\n");
|
||||
html.push_str(".strikeout { text-decoration: line-through; }\n");
|
||||
html.push_str(".dim { opacity: 0.5; }\n");
|
||||
html.push_str("</style>\n</head>\n<body>\n<pre>");
|
||||
|
||||
for styled_line in lines {
|
||||
html.push_str("<div class=\"line\">");
|
||||
for run in &styled_line.runs {
|
||||
let mut classes = Vec::new();
|
||||
let mut styles = Vec::new();
|
||||
|
||||
if run.bold {
|
||||
classes.push("bold");
|
||||
}
|
||||
if run.italic {
|
||||
classes.push("italic");
|
||||
}
|
||||
if run.underline {
|
||||
classes.push("underline");
|
||||
}
|
||||
if run.strikeout {
|
||||
classes.push("strikeout");
|
||||
}
|
||||
if run.dim {
|
||||
classes.push("dim");
|
||||
}
|
||||
|
||||
if let Some(ref fg) = run.fg {
|
||||
styles.push(format!("color:{fg}"));
|
||||
}
|
||||
if let Some(ref bg) = run.bg {
|
||||
styles.push(format!("background:{bg}"));
|
||||
}
|
||||
|
||||
if classes.is_empty() && styles.is_empty() {
|
||||
html.push_str(&html_escape(&run.text));
|
||||
} else {
|
||||
html.push_str("<span");
|
||||
if !classes.is_empty() {
|
||||
html.push_str(&format!(" class=\"{}\"", classes.join(" ")));
|
||||
}
|
||||
if !styles.is_empty() {
|
||||
html.push_str(&format!(" style=\"{}\"", styles.join(";")));
|
||||
}
|
||||
html.push('>');
|
||||
html.push_str(&html_escape(&run.text));
|
||||
html.push_str("</span>");
|
||||
}
|
||||
}
|
||||
html.push_str("</div>\n");
|
||||
}
|
||||
|
||||
html.push_str("</pre>\n</body>\n</html>\n");
|
||||
html
|
||||
}
|
||||
|
||||
/// Convert a terminal `Color` to a CSS color string.
|
||||
fn color_to_css(color: &Color) -> Option<String> {
|
||||
match color {
|
||||
Color::Spec(rgb) => Some(format!("#{:02x}{:02x}{:02x}", rgb.r, rgb.g, rgb.b)),
|
||||
Color::Named(name) => named_color_to_css(name),
|
||||
Color::Indexed(idx) => Some(indexed_color_to_css(*idx)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map named ANSI colors to CSS hex values (standard xterm palette).
|
||||
fn named_color_to_css(name: &NamedColor) -> Option<String> {
|
||||
let hex = match name {
|
||||
NamedColor::Black => "#000000",
|
||||
NamedColor::Red => "#cd0000",
|
||||
NamedColor::Green => "#00cd00",
|
||||
NamedColor::Yellow => "#cdcd00",
|
||||
NamedColor::Blue => "#0000ee",
|
||||
NamedColor::Magenta => "#cd00cd",
|
||||
NamedColor::Cyan => "#00cdcd",
|
||||
NamedColor::White => "#e5e5e5",
|
||||
NamedColor::BrightBlack => "#7f7f7f",
|
||||
NamedColor::BrightRed => "#ff0000",
|
||||
NamedColor::BrightGreen => "#00ff00",
|
||||
NamedColor::BrightYellow => "#ffff00",
|
||||
NamedColor::BrightBlue => "#5c5cff",
|
||||
NamedColor::BrightMagenta => "#ff00ff",
|
||||
NamedColor::BrightCyan => "#00ffff",
|
||||
NamedColor::BrightWhite => "#ffffff",
|
||||
NamedColor::Foreground | NamedColor::Background | NamedColor::Cursor => return None,
|
||||
_ => return None,
|
||||
};
|
||||
Some(hex.to_string())
|
||||
}
|
||||
|
||||
/// Map 256-color palette index to CSS hex.
|
||||
fn indexed_color_to_css(idx: u8) -> String {
|
||||
match idx {
|
||||
0 => "#000000".into(),
|
||||
1 => "#cd0000".into(),
|
||||
2 => "#00cd00".into(),
|
||||
3 => "#cdcd00".into(),
|
||||
4 => "#0000ee".into(),
|
||||
5 => "#cd00cd".into(),
|
||||
6 => "#00cdcd".into(),
|
||||
7 => "#e5e5e5".into(),
|
||||
8 => "#7f7f7f".into(),
|
||||
9 => "#ff0000".into(),
|
||||
10 => "#00ff00".into(),
|
||||
11 => "#ffff00".into(),
|
||||
12 => "#5c5cff".into(),
|
||||
13 => "#ff00ff".into(),
|
||||
14 => "#00ffff".into(),
|
||||
15 => "#ffffff".into(),
|
||||
// 216 color cube (indices 16-231).
|
||||
16..=231 => {
|
||||
let idx = idx - 16;
|
||||
let r = idx / 36;
|
||||
let g = (idx % 36) / 6;
|
||||
let b = idx % 6;
|
||||
let to_rgb = |v: u8| if v == 0 { 0u8 } else { 55 + 40 * v };
|
||||
format!("#{:02x}{:02x}{:02x}", to_rgb(r), to_rgb(g), to_rgb(b))
|
||||
}
|
||||
// Grayscale ramp (indices 232-255).
|
||||
232..=255 => {
|
||||
let v = 8 + 10 * (idx - 232);
|
||||
format!("#{:02x}{:02x}{:02x}", v, v, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape HTML special characters.
|
||||
fn html_escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Wrapper around `alacritty_terminal::Term` for headless terminal emulation.
|
||||
//!
|
||||
//! Provides a simplified interface for feeding PTY output into the terminal
|
||||
//! state machine and reading back screen content as text, styled JSON, or HTML.
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use alacritty_terminal::event::{Event, EventListener};
|
||||
use alacritty_terminal::grid::Dimensions;
|
||||
use alacritty_terminal::index::{Column, Line};
|
||||
use alacritty_terminal::term::cell::Flags;
|
||||
use alacritty_terminal::term::{Config, Term, TermMode};
|
||||
use alacritty_terminal::vte::ansi;
|
||||
|
||||
use crate::styled::{self, StyledLine};
|
||||
|
||||
/// Event listener that captures `PtyWrite` events for forwarding back to PTY.
|
||||
///
|
||||
/// When the terminal emulator needs to respond to device status queries (DSR),
|
||||
/// color queries, etc., it emits `Event::PtyWrite`. These MUST be forwarded
|
||||
/// back to the PTY, otherwise programs like vim/tmux will hang waiting for
|
||||
/// a response.
|
||||
#[derive(Clone)]
|
||||
pub struct SessionListener {
|
||||
pty_write_tx: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl SessionListener {
|
||||
pub fn new(pty_write_tx: tokio::sync::mpsc::UnboundedSender<Vec<u8>>) -> Self {
|
||||
Self { pty_write_tx }
|
||||
}
|
||||
}
|
||||
|
||||
impl EventListener for SessionListener {
|
||||
fn send_event(&self, event: Event) {
|
||||
if let Event::PtyWrite(text) = event {
|
||||
let _ = self.pty_write_tx.send(text.into_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for querying screen content.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ScreenOpts {
|
||||
/// Row range (1-indexed, inclusive). None = all rows.
|
||||
pub rows: Option<Range<usize>>,
|
||||
/// Column range (1-indexed, inclusive). None = all columns.
|
||||
pub cols: Option<Range<usize>>,
|
||||
/// If set, replace the character at cursor position with this char.
|
||||
pub cursor_char: Option<char>,
|
||||
/// Include trailing empty lines (default: trim them).
|
||||
pub include_empty: bool,
|
||||
}
|
||||
|
||||
/// Plain text screen output.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ScreenOutput {
|
||||
pub lines: Vec<String>,
|
||||
pub cursor: CursorPosition,
|
||||
pub size: TerminalSize,
|
||||
}
|
||||
|
||||
/// Cursor position (1-indexed).
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize)]
|
||||
pub struct CursorPosition {
|
||||
pub row: usize,
|
||||
pub col: usize,
|
||||
}
|
||||
|
||||
/// Terminal dimensions.
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize)]
|
||||
pub struct TerminalSize {
|
||||
pub cols: usize,
|
||||
pub rows: usize,
|
||||
}
|
||||
|
||||
/// Active terminal modes — tells callers what the running program has enabled.
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize)]
|
||||
pub struct TerminalModes {
|
||||
/// Alternate screen buffer is active (vim, less, htop, etc.).
|
||||
pub alt_screen: bool,
|
||||
/// Bracketed paste mode — input pasted between ESC[200~ / ESC[201~.
|
||||
pub bracketed_paste: bool,
|
||||
/// Application cursor keys (arrow keys send SS3 instead of CSI).
|
||||
pub app_cursor: bool,
|
||||
/// Application keypad mode.
|
||||
pub app_keypad: bool,
|
||||
/// Line-wrap mode (auto-wrap at right margin).
|
||||
pub line_wrap: bool,
|
||||
/// Origin mode (cursor addressing relative to scroll region).
|
||||
pub origin: bool,
|
||||
/// Cursor is visible.
|
||||
pub show_cursor: bool,
|
||||
/// Insert mode.
|
||||
pub insert: bool,
|
||||
/// LF/NL mode (linefeed also does carriage return).
|
||||
pub linefeed_newline: bool,
|
||||
/// Focus in/out reporting enabled.
|
||||
pub focus_in_out: bool,
|
||||
/// Mouse click reporting enabled.
|
||||
pub mouse_reporting: bool,
|
||||
}
|
||||
|
||||
/// A single line from scrollback history.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ScrollbackLine {
|
||||
/// 1-indexed offset from the bottom of scrollback (1 = most recent).
|
||||
pub offset: usize,
|
||||
/// Text content of the line.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// A simple `Dimensions` impl for creating a `Term`.
|
||||
struct TermDimensions {
|
||||
columns: usize,
|
||||
screen_lines: usize,
|
||||
}
|
||||
|
||||
impl TermDimensions {
|
||||
fn new(columns: usize, screen_lines: usize) -> Self {
|
||||
Self {
|
||||
columns,
|
||||
screen_lines,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dimensions for TermDimensions {
|
||||
fn total_lines(&self) -> usize {
|
||||
self.screen_lines
|
||||
}
|
||||
|
||||
fn screen_lines(&self) -> usize {
|
||||
self.screen_lines
|
||||
}
|
||||
|
||||
fn columns(&self) -> usize {
|
||||
self.columns
|
||||
}
|
||||
}
|
||||
|
||||
/// Headless terminal emulator wrapping `alacritty_terminal`.
|
||||
pub struct Terminal {
|
||||
term: Term<SessionListener>,
|
||||
parser: ansi::Processor,
|
||||
}
|
||||
|
||||
impl Terminal {
|
||||
/// Create a new terminal with the given dimensions.
|
||||
pub fn new(cols: u16, rows: u16, listener: SessionListener) -> Self {
|
||||
let size = TermDimensions::new(cols as usize, rows as usize);
|
||||
let config = Config::default();
|
||||
let term = Term::new(config, &size, listener);
|
||||
let parser = ansi::Processor::new();
|
||||
|
||||
Self { term, parser }
|
||||
}
|
||||
|
||||
/// Feed raw bytes from PTY output into the terminal emulator.
|
||||
pub fn feed(&mut self, bytes: &[u8]) {
|
||||
self.parser.advance(&mut self.term, bytes);
|
||||
}
|
||||
|
||||
/// Get the cursor position (1-indexed).
|
||||
pub fn cursor_position(&self) -> CursorPosition {
|
||||
let point = self.term.grid().cursor.point;
|
||||
CursorPosition {
|
||||
row: point.line.0 as usize + 1,
|
||||
col: point.column.0 + 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get terminal dimensions.
|
||||
pub fn size(&self) -> TerminalSize {
|
||||
TerminalSize {
|
||||
cols: self.term.columns(),
|
||||
rows: self.term.screen_lines(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resize the terminal.
|
||||
pub fn resize(&mut self, cols: u16, rows: u16) {
|
||||
let size = TermDimensions::new(cols as usize, rows as usize);
|
||||
self.term.resize(size);
|
||||
}
|
||||
|
||||
/// Get the active terminal modes.
|
||||
pub fn terminal_modes(&self) -> TerminalModes {
|
||||
let mode = self.term.mode();
|
||||
TerminalModes {
|
||||
alt_screen: mode.contains(TermMode::ALT_SCREEN),
|
||||
bracketed_paste: mode.contains(TermMode::BRACKETED_PASTE),
|
||||
app_cursor: mode.contains(TermMode::APP_CURSOR),
|
||||
app_keypad: mode.contains(TermMode::APP_KEYPAD),
|
||||
line_wrap: mode.contains(TermMode::LINE_WRAP),
|
||||
origin: mode.contains(TermMode::ORIGIN),
|
||||
show_cursor: mode.contains(TermMode::SHOW_CURSOR),
|
||||
insert: mode.contains(TermMode::INSERT),
|
||||
linefeed_newline: mode.contains(TermMode::LINE_FEED_NEW_LINE),
|
||||
focus_in_out: mode.contains(TermMode::FOCUS_IN_OUT),
|
||||
mouse_reporting: mode.intersects(
|
||||
TermMode::MOUSE_REPORT_CLICK | TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of lines in the scrollback buffer.
|
||||
pub fn scrollback_count(&self) -> usize {
|
||||
self.term.grid().history_size()
|
||||
}
|
||||
|
||||
/// Read scrollback lines. `count` limits how many to return (from the
|
||||
/// bottom / most-recent). Returns them in chronological order (oldest first).
|
||||
pub fn scrollback_lines(&self, count: usize) -> Vec<ScrollbackLine> {
|
||||
let grid = self.term.grid();
|
||||
let history = grid.history_size();
|
||||
let n = count.min(history);
|
||||
let num_cols = grid.columns();
|
||||
|
||||
let mut lines = Vec::with_capacity(n);
|
||||
// history lines are at negative indices: Line(-1) is most recent
|
||||
for offset in (1..=n).rev() {
|
||||
let row = &grid[Line(-(offset as i32))];
|
||||
let mut text = String::new();
|
||||
for col_idx in 0..num_cols {
|
||||
let cell = &row[Column(col_idx)];
|
||||
if cell
|
||||
.flags
|
||||
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
text.push(cell.c);
|
||||
if let Some(zw) = cell.zerowidth() {
|
||||
for &c in zw {
|
||||
text.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push(ScrollbackLine {
|
||||
offset,
|
||||
text: text.trim_end().to_string(),
|
||||
});
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Read screen content as plain text lines.
|
||||
pub fn screen_content(&self, opts: &ScreenOpts) -> ScreenOutput {
|
||||
let grid = self.term.grid();
|
||||
let num_lines = grid.screen_lines();
|
||||
let num_cols = grid.columns();
|
||||
let cursor = self.cursor_position();
|
||||
|
||||
let (row_start, row_end) = resolve_range(&opts.rows, num_lines);
|
||||
let (col_start, col_end) = resolve_range(&opts.cols, num_cols);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
|
||||
for line_idx in row_start..row_end {
|
||||
let row = &grid[Line(line_idx as i32)];
|
||||
let mut text = String::new();
|
||||
|
||||
for col_idx in col_start..col_end {
|
||||
let cell = &row[Column(col_idx)];
|
||||
|
||||
// Skip wide char spacers.
|
||||
if cell
|
||||
.flags
|
||||
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace cursor position if requested.
|
||||
let is_cursor = cursor.row == line_idx + 1 && cursor.col == col_idx + 1;
|
||||
if is_cursor && opts.cursor_char.is_some() {
|
||||
text.push(opts.cursor_char.unwrap());
|
||||
} else {
|
||||
text.push(cell.c);
|
||||
if let Some(zw) = cell.zerowidth() {
|
||||
for &c in zw {
|
||||
text.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(text);
|
||||
}
|
||||
|
||||
// Trim trailing empty lines unless include_empty is set.
|
||||
if !opts.include_empty {
|
||||
while lines.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
lines.pop();
|
||||
}
|
||||
}
|
||||
|
||||
// Right-trim each line.
|
||||
for line in &mut lines {
|
||||
let trimmed = line.trim_end().to_string();
|
||||
*line = trimmed;
|
||||
}
|
||||
|
||||
ScreenOutput {
|
||||
lines,
|
||||
cursor,
|
||||
size: self.size(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read screen content with full style information.
|
||||
pub fn screen_styled(&self, opts: &ScreenOpts) -> Vec<StyledLine> {
|
||||
let grid = self.term.grid();
|
||||
let num_lines = grid.screen_lines();
|
||||
let num_cols = grid.columns();
|
||||
let cursor = self.cursor_position();
|
||||
|
||||
let (row_start, row_end) = resolve_range(&opts.rows, num_lines);
|
||||
let (col_start, col_end) = resolve_range(&opts.cols, num_cols);
|
||||
|
||||
let mut result = Vec::new();
|
||||
|
||||
for line_idx in row_start..row_end {
|
||||
let row = &grid[Line(line_idx as i32)];
|
||||
let styled_line =
|
||||
styled::extract_styled_line(row, col_start, col_end, line_idx + 1, &cursor, opts);
|
||||
result.push(styled_line);
|
||||
}
|
||||
|
||||
// Trim trailing empty styled lines unless include_empty is set.
|
||||
if !opts.include_empty {
|
||||
while result.last().is_some_and(|l| l.runs.is_empty()) {
|
||||
result.pop();
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Render screen content as HTML.
|
||||
pub fn screen_html(&self, opts: &ScreenOpts) -> String {
|
||||
let styled = self.screen_styled(opts);
|
||||
styled::render_html(&styled, &self.cursor_position(), &self.size())
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve an optional 1-indexed range to 0-indexed (start, end).
|
||||
fn resolve_range(range: &Option<Range<usize>>, max: usize) -> (usize, usize) {
|
||||
match range {
|
||||
Some(r) => {
|
||||
let start = r.start.saturating_sub(1).min(max);
|
||||
let end = r.end.min(max);
|
||||
(start, end)
|
||||
}
|
||||
None => (0, max),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Event-driven wait/expect primitives over the terminal grid.
|
||||
//!
|
||||
//! Waiters never poll: the session's feeder bumps a generation watch after
|
||||
//! each `term.feed()`, and conditions are re-checked only on bumps.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::sync::{Mutex, watch};
|
||||
|
||||
use crate::term::{CursorPosition, ScreenOpts, Terminal, TerminalModes};
|
||||
|
||||
/// Maximum bytes of recent raw PTY output kept for wait-timeout diagnostics.
|
||||
pub(crate) const RAW_TAIL_CAP: usize = 2048;
|
||||
|
||||
/// A condition `wait_for` blocks on.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum WaitCondition {
|
||||
/// Text appears on screen (substring of the trimmed screen text).
|
||||
Text(String),
|
||||
/// Regex matches the trimmed screen text.
|
||||
Regex(String),
|
||||
/// Text is absent from the screen.
|
||||
Gone(String),
|
||||
/// No grid update for this many milliseconds.
|
||||
StableMs(u64),
|
||||
}
|
||||
|
||||
/// Result of a `wait_for` call.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct WaitOutcome {
|
||||
pub matched: bool,
|
||||
pub elapsed_ms: u64,
|
||||
/// Present only on timeout, so the agent never needs a follow-up call.
|
||||
#[serde(flatten)]
|
||||
pub diagnostics: Option<WaitDiagnostics>,
|
||||
}
|
||||
|
||||
/// Screen snapshot attached to a timed-out wait.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct WaitDiagnostics {
|
||||
/// Trimmed screen text (the exact text the condition was evaluated against).
|
||||
pub screen: String,
|
||||
pub cursor: CursorPosition,
|
||||
pub modes: TerminalModes,
|
||||
/// Last bytes of raw PTY output (lossy UTF-8, at most [`RAW_TAIL_CAP`] bytes).
|
||||
pub raw_tail: String,
|
||||
/// Grid generation at timeout.
|
||||
pub generation: u64,
|
||||
/// True when the session's output ended (child exited) before the deadline,
|
||||
/// so the condition could never have been met.
|
||||
pub ended: bool,
|
||||
}
|
||||
|
||||
/// Handles needed to wait on screen conditions without holding any outer session lock.
|
||||
///
|
||||
/// The HTTP server wraps `PtySession` in a mutex; a long-poll must clone
|
||||
/// this handle and drop the session guard, or it would block send/screen
|
||||
/// for the whole wait.
|
||||
///
|
||||
/// TODO: the next verb needing lock-free session access must instead make
|
||||
/// `stop()` take `&self` and switch the server state to `Arc<PtySession>`,
|
||||
/// deleting this handle — do not clone another field trio.
|
||||
pub struct WaitHandle {
|
||||
pub(crate) terminal: Arc<Mutex<Terminal>>,
|
||||
pub(crate) generation_rx: watch::Receiver<u64>,
|
||||
pub(crate) raw_tail: Arc<std::sync::Mutex<VecDeque<u8>>>,
|
||||
}
|
||||
|
||||
impl WaitHandle {
|
||||
/// Wait until `condition` is met or `timeout` elapses.
|
||||
///
|
||||
/// Event-driven: the grid is re-checked only when the feeder bumps the
|
||||
/// generation. Errors only on an invalid regex pattern.
|
||||
pub async fn wait_for(
|
||||
mut self,
|
||||
condition: WaitCondition,
|
||||
timeout: Duration,
|
||||
) -> Result<WaitOutcome> {
|
||||
let start = Instant::now();
|
||||
let deadline = tokio::time::Instant::now() + timeout;
|
||||
// Compile once so a bad pattern fails fast instead of on every check.
|
||||
let regex = match &condition {
|
||||
WaitCondition::Regex(pattern) => {
|
||||
Some(regex::Regex::new(pattern).context("invalid regex")?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let WaitCondition::StableMs(window_ms) = condition {
|
||||
let window = Duration::from_millis(window_ms);
|
||||
return Ok(self.wait_stable(window, start, deadline).await);
|
||||
}
|
||||
|
||||
loop {
|
||||
// Mark the current generation seen before checking, so a feed racing the check wakes changed().
|
||||
self.generation_rx.borrow_and_update();
|
||||
{
|
||||
let term = self.terminal.lock().await;
|
||||
let text = screen_text(&term);
|
||||
let met = match &condition {
|
||||
WaitCondition::Text(needle) => text.contains(needle),
|
||||
WaitCondition::Gone(needle) => !text.contains(needle),
|
||||
WaitCondition::Regex(_) => regex.as_ref().is_some_and(|re| re.is_match(&text)),
|
||||
WaitCondition::StableMs(_) => unreachable!("handled above"),
|
||||
};
|
||||
if met {
|
||||
return Ok(WaitOutcome {
|
||||
matched: true,
|
||||
elapsed_ms: start.elapsed().as_millis() as u64,
|
||||
diagnostics: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
changed = self.generation_rx.changed() => {
|
||||
if changed.is_err() {
|
||||
// Feeder gone (session over): the grid is final, so fail fast with diagnostics.
|
||||
return Ok(self.timeout_outcome(start, true).await);
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
return Ok(self.timeout_outcome(start, false).await);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until the grid has been unchanged for `window`, bounded by `deadline`.
|
||||
async fn wait_stable(
|
||||
&mut self,
|
||||
window: Duration,
|
||||
start: Instant,
|
||||
deadline: tokio::time::Instant,
|
||||
) -> WaitOutcome {
|
||||
// A dropped sender means no further grid updates: the remaining window always completes.
|
||||
let mut sender_gone = false;
|
||||
loop {
|
||||
self.generation_rx.borrow_and_update();
|
||||
let window_end = tokio::time::Instant::now() + window;
|
||||
tokio::select! {
|
||||
changed = self.generation_rx.changed(), if !sender_gone => {
|
||||
if changed.is_err() {
|
||||
sender_gone = true;
|
||||
}
|
||||
// Activity: restart the stability window unless out of time.
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return self.timeout_outcome(start, sender_gone).await;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep_until(window_end.min(deadline)) => {
|
||||
if window_end <= deadline {
|
||||
return WaitOutcome {
|
||||
matched: true,
|
||||
elapsed_ms: start.elapsed().as_millis() as u64,
|
||||
diagnostics: None,
|
||||
};
|
||||
}
|
||||
return self.timeout_outcome(start, sender_gone).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot the screen state for a timed-out wait.
|
||||
async fn timeout_outcome(&self, start: Instant, ended: bool) -> WaitOutcome {
|
||||
let (screen, cursor, modes) = {
|
||||
let term = self.terminal.lock().await;
|
||||
(
|
||||
screen_text(&term),
|
||||
term.cursor_position(),
|
||||
term.terminal_modes(),
|
||||
)
|
||||
};
|
||||
let raw_tail = {
|
||||
let tail = self.raw_tail.lock().unwrap();
|
||||
String::from_utf8_lossy(&tail.iter().copied().collect::<Vec<u8>>()).into_owned()
|
||||
};
|
||||
WaitOutcome {
|
||||
matched: false,
|
||||
elapsed_ms: start.elapsed().as_millis() as u64,
|
||||
diagnostics: Some(WaitDiagnostics {
|
||||
screen,
|
||||
cursor,
|
||||
modes,
|
||||
raw_tail,
|
||||
generation: *self.generation_rx.borrow(),
|
||||
ended,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trimmed screen text — identical to what agents see via the screen API.
|
||||
fn screen_text(term: &Terminal) -> String {
|
||||
term.screen_content(&ScreenOpts::default()).lines.join("\n")
|
||||
}
|
||||
|
||||
/// Append bytes to the bounded raw-output tail, evicting the oldest bytes.
|
||||
pub(crate) fn push_raw_tail(tail: &std::sync::Mutex<VecDeque<u8>>, bytes: &[u8]) {
|
||||
let mut tail = tail.lock().unwrap();
|
||||
if bytes.len() >= RAW_TAIL_CAP {
|
||||
tail.clear();
|
||||
tail.extend(&bytes[bytes.len() - RAW_TAIL_CAP..]);
|
||||
return;
|
||||
}
|
||||
while tail.len() + bytes.len() > RAW_TAIL_CAP {
|
||||
tail.pop_front();
|
||||
}
|
||||
tail.extend(bytes);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
name = "xai-acp-lib"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
agent-client-protocol = { workspace = true, features = ["unstable"] }
|
||||
async-trait = { workspace = true }
|
||||
derive_more = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
serde.workspace = true
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,103 @@
|
||||
use std::fmt;
|
||||
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::{
|
||||
common::{AcpChannelFailure, AcpResult, acp_channel_failure_error},
|
||||
message::{AcpAgentMessage, AcpArgs, AcpClientMessage, AcpMethod, AcpRequest},
|
||||
};
|
||||
|
||||
/// Receiver/sender pair, either for client/agent or agent/client message types.
|
||||
pub struct AcpChannel<I, O> {
|
||||
pub rx: mpsc::UnboundedReceiver<I>,
|
||||
pub tx: mpsc::UnboundedSender<O>,
|
||||
}
|
||||
|
||||
impl<I: AcpMethod, O: AcpMethod> AcpChannel<I, O> {
|
||||
pub fn new(rx: mpsc::UnboundedReceiver<I>, tx: mpsc::UnboundedSender<O>) -> Self {
|
||||
Self { rx, tx }
|
||||
}
|
||||
}
|
||||
|
||||
/// Client channel: receive client messages from agent, send agent messages to agent.
|
||||
pub type AcpClientChannel = AcpChannel<AcpClientMessage, AcpAgentMessage>;
|
||||
/// Agent channel: receive agent messages from client, send client messages to client.
|
||||
pub type AcpAgentChannel = AcpChannel<AcpAgentMessage, AcpClientMessage>;
|
||||
|
||||
/// Create a linked pair of client/agent channels.
|
||||
pub fn acp_channels() -> (AcpClientChannel, AcpAgentChannel) {
|
||||
let (tx1, rx1) = mpsc::unbounded_channel();
|
||||
let (tx2, rx2) = mpsc::unbounded_channel();
|
||||
(AcpChannel::new(rx1, tx2), AcpChannel::new(rx2, tx1))
|
||||
}
|
||||
|
||||
pub async fn acp_send<R, T>(request: T, tx: &mpsc::UnboundedSender<R>) -> AcpResult<T::Response>
|
||||
where
|
||||
T: AcpRequest,
|
||||
R: From<AcpArgs<T>> + fmt::Debug,
|
||||
{
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let method = request.method_name();
|
||||
let args = AcpArgs {
|
||||
request,
|
||||
response_tx,
|
||||
};
|
||||
|
||||
tx.send(args.into()).map_err(|_| {
|
||||
acp_channel_failure_error(
|
||||
format!("unable to send '{method}' request, channel closed"),
|
||||
AcpChannelFailure::SendFailed,
|
||||
)
|
||||
})?;
|
||||
|
||||
response_rx.await.map_err(|_| {
|
||||
acp_channel_failure_error(
|
||||
format!("unable to receive '{method}' response, channel closed"),
|
||||
AcpChannelFailure::RecvFailed,
|
||||
)
|
||||
})?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod acp_send_failure_tests {
|
||||
use super::acp_send;
|
||||
use crate::common::{AcpChannelFailure, acp_channel_failure};
|
||||
use crate::message::AcpAgentMessage;
|
||||
use agent_client_protocol as acp;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
fn ext_request() -> acp::ExtRequest {
|
||||
acp::ExtRequest::new(
|
||||
"x.ai/test",
|
||||
serde_json::value::to_raw_value(&serde_json::json!({}))
|
||||
.unwrap()
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_failed_when_receiver_dropped_before_send() {
|
||||
let (tx, rx) = mpsc::unbounded_channel::<AcpAgentMessage>();
|
||||
drop(rx); // no peer listening -> enqueue fails
|
||||
let err = acp_send(ext_request(), &tx).await.unwrap_err();
|
||||
assert_eq!(
|
||||
acp_channel_failure(&err),
|
||||
Some(AcpChannelFailure::SendFailed)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recv_failed_when_response_channel_dropped_after_send() {
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<AcpAgentMessage>();
|
||||
let mut send_fut = Box::pin(acp_send(ext_request(), &tx));
|
||||
// First poll enqueues the request, then parks on the response channel.
|
||||
assert!(futures::poll!(send_fut.as_mut()).is_pending());
|
||||
// The peer "receives" the request then drops it (dropping response_tx).
|
||||
drop(rx.try_recv().expect("request should be enqueued"));
|
||||
let err = send_fut.await.unwrap_err();
|
||||
assert_eq!(
|
||||
acp_channel_failure(&err),
|
||||
Some(AcpChannelFailure::RecvFailed)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use agent_client_protocol as acp;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::message::{AcpAgentMessage, AcpClientMessage};
|
||||
|
||||
pub type AcpResult<T> = Result<T, acp::Error>;
|
||||
|
||||
pub type AcpRxo<T> = oneshot::Receiver<AcpResult<T>>;
|
||||
pub type AcpTxo<T> = oneshot::Sender<AcpResult<T>>;
|
||||
|
||||
pub type AcpClientRx = mpsc::UnboundedReceiver<AcpClientMessage>;
|
||||
pub type AcpClientTx = mpsc::UnboundedSender<AcpClientMessage>;
|
||||
|
||||
pub type AcpAgentRx = mpsc::UnboundedReceiver<AcpAgentMessage>;
|
||||
pub type AcpAgentTx = mpsc::UnboundedSender<AcpAgentMessage>;
|
||||
|
||||
pub fn acp_internal_error(message: impl Into<String>) -> acp::Error {
|
||||
acp::Error::new(acp::ErrorCode::InternalError.into(), message)
|
||||
}
|
||||
|
||||
/// The two distinct ways an [`acp_send`](crate::acp_send) round-trip can fail
|
||||
/// when the underlying channel is closed. Both surface as a JSON-RPC
|
||||
/// `INTERNAL_ERROR` (so existing callers and the wire format are unaffected);
|
||||
/// this typed discriminant — carried in the error's `data` — lets callers tell
|
||||
/// them apart WITHOUT substring-matching the human-readable `message`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AcpChannelFailure {
|
||||
/// The request could not be ENQUEUED: the receiver half (the peer's
|
||||
/// connection task) is already gone, so no peer is listening — e.g. a
|
||||
/// headless run with no client wired.
|
||||
SendFailed,
|
||||
/// The request was enqueued but the RESPONSE channel was dropped before a
|
||||
/// reply arrived: a peer received the request, then went away (disconnect /
|
||||
/// process exit) without answering.
|
||||
RecvFailed,
|
||||
}
|
||||
|
||||
impl AcpChannelFailure {
|
||||
/// `data` object key under which [`acp_send`](crate::acp_send) records the
|
||||
/// kind. Namespaced so it can never collide with other `with_data` payloads.
|
||||
const DATA_KEY: &'static str = "xaiAcpChannelFailure";
|
||||
|
||||
const fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::SendFailed => "send_failed",
|
||||
Self::RecvFailed => "recv_failed",
|
||||
}
|
||||
}
|
||||
|
||||
fn from_tag(tag: &str) -> Option<Self> {
|
||||
match tag {
|
||||
"send_failed" => Some(Self::SendFailed),
|
||||
"recv_failed" => Some(Self::RecvFailed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the channel-closed error for [`acp_send`](crate::acp_send), tagging it
|
||||
/// with a typed [`AcpChannelFailure`] discriminant in `data`. The error `code`
|
||||
/// stays `INTERNAL_ERROR`, so this is purely additive for callers that just
|
||||
/// propagate the error.
|
||||
pub(crate) fn acp_channel_failure_error(
|
||||
message: impl Into<String>,
|
||||
kind: AcpChannelFailure,
|
||||
) -> acp::Error {
|
||||
acp_internal_error(message).data(serde_json::json!({ AcpChannelFailure::DATA_KEY: kind.tag() }))
|
||||
}
|
||||
|
||||
/// Recover the [`AcpChannelFailure`] kind from an error, or `None` if the error
|
||||
/// did not originate from [`acp_send`](crate::acp_send)'s channel-closed paths
|
||||
/// (or predates the tag). Consumers use this instead of inspecting `message`.
|
||||
pub fn acp_channel_failure(err: &acp::Error) -> Option<AcpChannelFailure> {
|
||||
err.data
|
||||
.as_ref()
|
||||
.and_then(|data| data.get(AcpChannelFailure::DATA_KEY))
|
||||
.and_then(|value| value.as_str())
|
||||
.and_then(AcpChannelFailure::from_tag)
|
||||
}
|
||||
|
||||
/// Compact single-line JSON for gateway debug traces. Plain (uncolored)
|
||||
/// output: this feeds `tracing::debug!`, which typically lands in log files
|
||||
/// where ANSI colors are noise. Replaces the former `colored_json`-backed
|
||||
/// `color_json` (dropped to shrink the shipped dependency tree).
|
||||
#[doc(hidden)]
|
||||
pub fn compact_json<T: serde::Serialize>(value: &T) -> String {
|
||||
serde_json::to_string(value).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod channel_failure_tests {
|
||||
use super::{
|
||||
AcpChannelFailure, acp, acp_channel_failure, acp_channel_failure_error, acp_internal_error,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn classifier_round_trips_both_kinds() {
|
||||
for kind in [AcpChannelFailure::SendFailed, AcpChannelFailure::RecvFailed] {
|
||||
let err = acp_channel_failure_error("boom", kind);
|
||||
// Code stays INTERNAL_ERROR for backward compatibility.
|
||||
assert_eq!(err.code, acp::ErrorCode::InternalError);
|
||||
assert_eq!(acp_channel_failure(&err), Some(kind));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifier_none_for_untagged_errors() {
|
||||
assert_eq!(acp_channel_failure(&acp_internal_error("plain")), None);
|
||||
// A different `with_data` payload must not be misread as a channel kind.
|
||||
assert_eq!(
|
||||
acp_channel_failure(&acp::Error::invalid_params().data("unknown session id")),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,695 @@
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
|
||||
use agent_client_protocol as acp;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::{
|
||||
AcpMethod, acp_send,
|
||||
common::AcpResult,
|
||||
message::{AcpAgentMessage, AcpArgs, AcpClientMessage, AcpRequest, AcpSide},
|
||||
};
|
||||
|
||||
type SpawnFn = Rc<dyn Fn(Pin<Box<dyn Future<Output = ()>>>)>;
|
||||
/// Callback that creates a `tracing::Span` from `_meta` for distributed tracing.
|
||||
type OnMetaFn = Rc<dyn Fn(&acp::Meta) -> tracing::Span>;
|
||||
|
||||
/// Gateway receiver - allows sending messages to it via a channel and it will
|
||||
/// forward them to an underlying connection.
|
||||
pub struct AcpGatewayReceiver<S: AcpSide, C> {
|
||||
rx: mpsc::UnboundedReceiver<S::OutMessage>,
|
||||
conn: C,
|
||||
tracing: bool,
|
||||
spawn_fn: SpawnFn,
|
||||
on_meta: Option<OnMetaFn>,
|
||||
}
|
||||
|
||||
impl<S: AcpSide, C> AcpGatewayReceiver<S, C> {
|
||||
pub fn new(rx: mpsc::UnboundedReceiver<S::OutMessage>, conn: C) -> Self {
|
||||
Self {
|
||||
rx,
|
||||
conn,
|
||||
tracing: false,
|
||||
spawn_fn: Rc::new(|fut| {
|
||||
tokio::task::spawn_local(fut);
|
||||
}),
|
||||
on_meta: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_tracing(mut self, tracing: bool) -> Self {
|
||||
self.tracing = tracing;
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the spawner used for dispatching incoming messages.
|
||||
///
|
||||
/// By default, `spawn_local` is used (suitable for `LocalSet` runtimes).
|
||||
/// Pass a custom spawner to use a different execution strategy.
|
||||
pub fn with_spawn_fn(
|
||||
mut self,
|
||||
f: impl Fn(Pin<Box<dyn Future<Output = ()>>>) + 'static,
|
||||
) -> Self {
|
||||
self.spawn_fn = Rc::new(f);
|
||||
self
|
||||
}
|
||||
|
||||
/// Hook that builds a `tracing::Span` from `_meta` to `.instrument()` dispatched messages.
|
||||
pub fn with_on_meta(mut self, f: impl Fn(&acp::Meta) -> tracing::Span + 'static) -> Self {
|
||||
self.on_meta = Some(Rc::new(f));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The other side of the gateway. Allows to send messages to a channel so that
|
||||
/// they will be forwarded automatically to a connection (as long as gateway
|
||||
/// receiver side is running in the background).
|
||||
pub struct AcpGatewaySender<S: AcpSide> {
|
||||
tx: mpsc::UnboundedSender<S::OutMessage>,
|
||||
tracing: bool,
|
||||
}
|
||||
|
||||
impl<S: AcpSide> Clone for AcpGatewaySender<S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
tx: self.tx.clone(),
|
||||
tracing: self.tracing,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: AcpSide> AcpGatewaySender<S> {
|
||||
pub fn new(tx: mpsc::UnboundedSender<S::OutMessage>) -> Self {
|
||||
Self { tx, tracing: false }
|
||||
}
|
||||
|
||||
pub fn tx(&self) -> mpsc::UnboundedSender<S::OutMessage> {
|
||||
self.tx.clone()
|
||||
}
|
||||
|
||||
pub fn with_tracing(mut self, tracing: bool) -> Self {
|
||||
self.tracing = tracing;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn acp_gateway<S: AcpSide, C>(conn: C) -> (AcpGatewaySender<S>, AcpGatewayReceiver<S, C>) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let sender = AcpGatewaySender::new(tx);
|
||||
let receiver = AcpGatewayReceiver::new(rx, conn);
|
||||
(sender, receiver)
|
||||
}
|
||||
|
||||
pub type AcpAgentGatewayReceiver = AcpGatewayReceiver<acp::AgentSide, acp::AgentSideConnection>;
|
||||
pub type AcpAgentGatewaySender = AcpGatewaySender<acp::AgentSide>;
|
||||
pub type AcpClientGatewayReceiver = AcpGatewayReceiver<acp::ClientSide, acp::ClientSideConnection>;
|
||||
pub type AcpClientGatewaySender = AcpGatewaySender<acp::ClientSide>;
|
||||
|
||||
fn before_request<T: AcpRequest>(args: &AcpArgs<T>, tracing: bool) -> Option<String> {
|
||||
tracing.then(|| {
|
||||
let method = crate::common::compact_json(&args.method_name());
|
||||
tracing::debug!(
|
||||
"sending {method} request: {}",
|
||||
crate::common::compact_json(&args.request)
|
||||
);
|
||||
method
|
||||
})
|
||||
}
|
||||
|
||||
fn after_request<T: Serialize>(
|
||||
response_tx: oneshot::Sender<AcpResult<T>>,
|
||||
response: AcpResult<T>,
|
||||
method: Option<String>,
|
||||
) -> bool {
|
||||
if let Some(method) = method {
|
||||
match response {
|
||||
Ok(ref response) => {
|
||||
tracing::debug!(
|
||||
"received {method} response: {}",
|
||||
crate::common::compact_json(&response)
|
||||
);
|
||||
}
|
||||
Err(ref err) => {
|
||||
// Log at debug level - errors are handled visually in the TUI status bar
|
||||
tracing::debug!("received {method} error: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
response_tx.send(response).is_ok()
|
||||
}
|
||||
|
||||
macro_rules! handle {
|
||||
($args:expr, $tracing:expr, $conn:expr, $name:ident, $spawn:expr, $on_meta:expr $(,)?) => {{
|
||||
let span = ($on_meta)
|
||||
.as_ref()
|
||||
.zip(($args).request.meta.as_ref())
|
||||
.map(|(f, meta)| f(meta))
|
||||
.unwrap_or_else(tracing::Span::none);
|
||||
($spawn)(Box::pin(
|
||||
async move {
|
||||
let method = before_request(&($args), $tracing);
|
||||
let response = ($conn).$name(($args).request).await;
|
||||
let _ = after_request(($args).response_tx, response, method);
|
||||
}
|
||||
.instrument(span),
|
||||
));
|
||||
}};
|
||||
// Variant for types without `meta` field (ExtRequest, ExtNotification).
|
||||
// $on_meta is accepted (but unused) to disambiguate from the primary pattern.
|
||||
(no_meta, $args:expr, $tracing:expr, $conn:expr, $name:ident, $spawn:expr, $on_meta:expr $(,)?) => {
|
||||
($spawn)(Box::pin(async move {
|
||||
let method = before_request(&($args), $tracing);
|
||||
let response = ($conn).$name(($args).request).await;
|
||||
let _ = after_request(($args).response_tx, response, method);
|
||||
}));
|
||||
};
|
||||
}
|
||||
|
||||
impl<C: acp::Agent + 'static> AcpGatewayReceiver<acp::ClientSide, C> {
|
||||
pub async fn run(mut self) {
|
||||
let conn = Rc::new(self.conn);
|
||||
let spawn = self.spawn_fn.clone();
|
||||
let on_meta = self.on_meta.clone();
|
||||
while let Some(msg) = self.rx.recv().await {
|
||||
let conn = conn.clone();
|
||||
match msg {
|
||||
AcpAgentMessage::Initialize(args) => {
|
||||
handle!(args, self.tracing, conn, initialize, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::Authenticate(args) => {
|
||||
handle!(args, self.tracing, conn, authenticate, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::NewSession(args) => {
|
||||
handle!(args, self.tracing, conn, new_session, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::LoadSession(args) => {
|
||||
handle!(args, self.tracing, conn, load_session, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::SetSessionMode(args) => {
|
||||
handle!(args, self.tracing, conn, set_session_mode, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::Prompt(args) => {
|
||||
handle!(args, self.tracing, conn, prompt, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::Cancel(args) => {
|
||||
handle!(args, self.tracing, conn, cancel, spawn, on_meta);
|
||||
}
|
||||
AcpAgentMessage::ExtMethod(args) => {
|
||||
handle!(
|
||||
no_meta,
|
||||
args,
|
||||
self.tracing,
|
||||
conn,
|
||||
ext_method,
|
||||
spawn,
|
||||
on_meta
|
||||
);
|
||||
}
|
||||
AcpAgentMessage::ExtNotification(args) => {
|
||||
handle!(
|
||||
no_meta,
|
||||
args,
|
||||
self.tracing,
|
||||
conn,
|
||||
ext_notification,
|
||||
spawn,
|
||||
on_meta
|
||||
);
|
||||
}
|
||||
AcpAgentMessage::SetSessionModel(args) => {
|
||||
handle!(args, self.tracing, conn, set_session_model, spawn, on_meta);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.tracing {
|
||||
tracing::trace!("stopping gateway loop: receiver channel is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: acp::Client + 'static> AcpGatewayReceiver<acp::AgentSide, C> {
|
||||
pub async fn run(mut self) {
|
||||
let conn = Rc::new(self.conn);
|
||||
let spawn = self.spawn_fn.clone();
|
||||
let on_meta = self.on_meta.clone();
|
||||
while let Some(msg) = self.rx.recv().await {
|
||||
let conn = conn.clone();
|
||||
match msg {
|
||||
AcpClientMessage::RequestPermission(args) => {
|
||||
handle!(args, self.tracing, conn, request_permission, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::ReadTextFile(args) => {
|
||||
handle!(args, self.tracing, conn, read_text_file, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::WriteTextFile(args) => {
|
||||
handle!(args, self.tracing, conn, write_text_file, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::SessionNotification(args) => {
|
||||
handle!(
|
||||
args,
|
||||
self.tracing,
|
||||
conn,
|
||||
session_notification,
|
||||
spawn,
|
||||
on_meta
|
||||
);
|
||||
}
|
||||
AcpClientMessage::CreateTerminal(args) => {
|
||||
handle!(args, self.tracing, conn, create_terminal, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::TerminalOutput(args) => {
|
||||
handle!(args, self.tracing, conn, terminal_output, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::ReleaseTerminal(args) => {
|
||||
handle!(args, self.tracing, conn, release_terminal, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::WaitForTerminalExit(args) => {
|
||||
handle!(
|
||||
args,
|
||||
self.tracing,
|
||||
conn,
|
||||
wait_for_terminal_exit,
|
||||
spawn,
|
||||
on_meta
|
||||
);
|
||||
}
|
||||
AcpClientMessage::KillTerminalCommand(args) => {
|
||||
handle!(args, self.tracing, conn, kill_terminal, spawn, on_meta);
|
||||
}
|
||||
AcpClientMessage::ExtMethod(args) => {
|
||||
handle!(
|
||||
no_meta,
|
||||
args,
|
||||
self.tracing,
|
||||
conn,
|
||||
ext_method,
|
||||
spawn,
|
||||
on_meta
|
||||
);
|
||||
}
|
||||
AcpClientMessage::ExtNotification(args) => {
|
||||
handle!(
|
||||
no_meta,
|
||||
args,
|
||||
self.tracing,
|
||||
conn,
|
||||
ext_notification,
|
||||
spawn,
|
||||
on_meta
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.tracing {
|
||||
tracing::trace!("stopping gateway loop: receiver channel is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: AcpSide> AcpGatewaySender<S> {
|
||||
/// Shared enqueue for the forward variants; `caller` attributes the
|
||||
/// dropped-receiver log to the right public method.
|
||||
fn enqueue<T>(
|
||||
&self,
|
||||
request: T,
|
||||
caller: &'static str,
|
||||
) -> (bool, oneshot::Receiver<AcpResult<T::Response>>)
|
||||
where
|
||||
T: AcpRequest,
|
||||
S::OutMessage: From<AcpArgs<T>>,
|
||||
{
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let method = request.method_name();
|
||||
let args = AcpArgs {
|
||||
request,
|
||||
response_tx,
|
||||
};
|
||||
let accepted = self.tx.send(args.into()).is_ok();
|
||||
if !accepted {
|
||||
tracing::debug!(method, "{caller}: receiver dropped, notification discarded");
|
||||
}
|
||||
(accepted, response_rx)
|
||||
}
|
||||
|
||||
/// Enqueue a request and return a completion receiver for handler finish.
|
||||
pub fn forward_with_completion<T>(
|
||||
&self,
|
||||
request: T,
|
||||
) -> oneshot::Receiver<AcpResult<T::Response>>
|
||||
where
|
||||
T: AcpRequest,
|
||||
S::OutMessage: From<AcpArgs<T>>,
|
||||
{
|
||||
self.enqueue(request, "forward_with_completion").1
|
||||
}
|
||||
|
||||
/// Enqueue a request without waiting for the response. Returns whether
|
||||
/// the gateway channel accepted it (`false`: receiver gone, message
|
||||
/// discarded) so callers keeping delivery-dependent state can retry.
|
||||
pub fn forward_fire_and_forget<T>(&self, request: T) -> bool
|
||||
where
|
||||
T: AcpRequest,
|
||||
S::OutMessage: From<AcpArgs<T>>,
|
||||
{
|
||||
self.enqueue(request, "forward_fire_and_forget").0
|
||||
}
|
||||
|
||||
/// Send a request and await the response. Returns a `Send` future.
|
||||
///
|
||||
/// Equivalent to the `acp::Client` / `acp::Agent` trait methods but the
|
||||
/// returned future is `Send` because this is an inherent async fn — not
|
||||
/// wrapped by `#[async_trait(?Send)]`.
|
||||
pub async fn send<T>(&self, request: T) -> AcpResult<T::Response>
|
||||
where
|
||||
T: AcpRequest,
|
||||
S::OutMessage: From<AcpArgs<T>>,
|
||||
{
|
||||
self.forward(request).await
|
||||
}
|
||||
|
||||
async fn forward<T>(&self, request: T) -> AcpResult<T::Response>
|
||||
where
|
||||
T: AcpRequest,
|
||||
S::OutMessage: From<AcpArgs<T>>,
|
||||
{
|
||||
if self.tracing {
|
||||
let method = crate::common::compact_json(&request.method_name());
|
||||
tracing::debug!(
|
||||
"received {method} request: {}",
|
||||
crate::common::compact_json(&request)
|
||||
);
|
||||
}
|
||||
acp_send(request, &self.tx).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl acp::Client for AcpGatewaySender<acp::AgentSide> {
|
||||
async fn request_permission(
|
||||
&self,
|
||||
args: acp::RequestPermissionRequest,
|
||||
) -> AcpResult<acp::RequestPermissionResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn write_text_file(
|
||||
&self,
|
||||
args: acp::WriteTextFileRequest,
|
||||
) -> AcpResult<acp::WriteTextFileResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn read_text_file(
|
||||
&self,
|
||||
args: acp::ReadTextFileRequest,
|
||||
) -> AcpResult<acp::ReadTextFileResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn create_terminal(
|
||||
&self,
|
||||
args: acp::CreateTerminalRequest,
|
||||
) -> AcpResult<acp::CreateTerminalResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn terminal_output(
|
||||
&self,
|
||||
args: acp::TerminalOutputRequest,
|
||||
) -> AcpResult<acp::TerminalOutputResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn release_terminal(
|
||||
&self,
|
||||
args: acp::ReleaseTerminalRequest,
|
||||
) -> AcpResult<acp::ReleaseTerminalResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn wait_for_terminal_exit(
|
||||
&self,
|
||||
args: acp::WaitForTerminalExitRequest,
|
||||
) -> AcpResult<acp::WaitForTerminalExitResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn kill_terminal(
|
||||
&self,
|
||||
args: acp::KillTerminalRequest,
|
||||
) -> AcpResult<acp::KillTerminalResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn session_notification(&self, args: acp::SessionNotification) -> AcpResult<()> {
|
||||
// Fire-and-forget: session notifications carry no meaningful response (the
|
||||
// ACK is `()`), so we must not block the caller waiting for the client to
|
||||
// acknowledge. When the agent→relay→client path is degraded (e.g. a Slack
|
||||
// session whose ephemeral WebSocket died mid-turn), the relay write can
|
||||
// stall for minutes (TCP retransmit timeout). Blocking here freezes the
|
||||
// terminal streaming loop — its timeout check never fires, the session
|
||||
// actor can't process new prompts, and the entire session hangs.
|
||||
self.forward_fire_and_forget(args);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ext_method(&self, args: acp::ExtRequest) -> AcpResult<acp::ExtResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn ext_notification(&self, args: acp::ExtNotification) -> AcpResult<()> {
|
||||
// Fire-and-forget for the same reason as `session_notification` above:
|
||||
// the ACK is `()` and blocking risks hanging the caller when the
|
||||
// relay→client path is degraded. Many call sites already bypass this
|
||||
// trait method and call `forward_fire_and_forget` directly.
|
||||
self.forward_fire_and_forget(args);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl acp::Agent for AcpGatewaySender<acp::ClientSide> {
|
||||
async fn initialize(&self, args: acp::InitializeRequest) -> AcpResult<acp::InitializeResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn authenticate(
|
||||
&self,
|
||||
args: acp::AuthenticateRequest,
|
||||
) -> AcpResult<acp::AuthenticateResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn new_session(
|
||||
&self,
|
||||
args: acp::NewSessionRequest,
|
||||
) -> AcpResult<acp::NewSessionResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn load_session(
|
||||
&self,
|
||||
args: acp::LoadSessionRequest,
|
||||
) -> AcpResult<acp::LoadSessionResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn set_session_mode(
|
||||
&self,
|
||||
args: acp::SetSessionModeRequest,
|
||||
) -> AcpResult<acp::SetSessionModeResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn prompt(&self, args: acp::PromptRequest) -> AcpResult<acp::PromptResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn cancel(&self, args: acp::CancelNotification) -> AcpResult<()> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn ext_method(&self, args: acp::ExtRequest) -> AcpResult<acp::ExtResponse> {
|
||||
self.forward(args).await
|
||||
}
|
||||
|
||||
async fn ext_notification(&self, args: acp::ExtNotification) -> AcpResult<()> {
|
||||
self.forward(args).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use agent_client_protocol as acp;
|
||||
|
||||
struct OrderTrackingClient {
|
||||
log: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl acp::Client for OrderTrackingClient {
|
||||
async fn request_permission(
|
||||
&self,
|
||||
_: acp::RequestPermissionRequest,
|
||||
) -> acp::Result<acp::RequestPermissionResponse> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn session_notification(&self, args: acp::SessionNotification) -> acp::Result<()> {
|
||||
if let acp::SessionUpdate::AgentMessageChunk(chunk) = &args.update
|
||||
&& let acp::ContentBlock::Text(text) = &chunk.content
|
||||
{
|
||||
self.log.borrow_mut().push(text.text.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn text_notification(marker: &str) -> acp::SessionNotification {
|
||||
acp::SessionNotification::new(
|
||||
acp::SessionId::new("s"),
|
||||
acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(acp::ContentBlock::Text(
|
||||
acp::TextContent::new(marker),
|
||||
))),
|
||||
)
|
||||
}
|
||||
|
||||
/// Regression: draining completion receivers preserves notification ordering.
|
||||
#[tokio::test]
|
||||
async fn completion_drain_preserves_notification_ordering() {
|
||||
let local = tokio::task::LocalSet::new();
|
||||
local
|
||||
.run_until(async {
|
||||
let log = Rc::new(RefCell::new(Vec::<String>::new()));
|
||||
let (sender, receiver) =
|
||||
acp_gateway::<acp::AgentSide, _>(OrderTrackingClient { log: log.clone() });
|
||||
tokio::task::spawn_local(receiver.run());
|
||||
|
||||
const N: usize = 100;
|
||||
let completions: Vec<_> = (0..N)
|
||||
.map(|i| sender.forward_with_completion(text_notification(&format!("{i}"))))
|
||||
.collect();
|
||||
for rx in completions {
|
||||
let _ = rx.await;
|
||||
}
|
||||
|
||||
log.borrow_mut().push("RESPONSE".into());
|
||||
|
||||
let log = log.borrow();
|
||||
assert_eq!(log.len(), N + 1);
|
||||
assert_eq!(log[N], "RESPONSE");
|
||||
for i in 0..N {
|
||||
assert_eq!(log[i], format!("{i}"));
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Regression: two-phase cutover keeps replay-before-response and avoids
|
||||
/// dropping live updates during drain.
|
||||
#[tokio::test]
|
||||
async fn two_phase_cutover_no_missing_updates() {
|
||||
let local = tokio::task::LocalSet::new();
|
||||
local
|
||||
.run_until(async {
|
||||
let log = Rc::new(RefCell::new(Vec::<String>::new()));
|
||||
let (sender, receiver) =
|
||||
acp_gateway::<acp::AgentSide, _>(OrderTrackingClient { log: log.clone() });
|
||||
tokio::task::spawn_local(receiver.run());
|
||||
|
||||
const DELTA: usize = 50;
|
||||
const LIVE: usize = 20;
|
||||
|
||||
// Phase 1: sync enqueue of replay notifications.
|
||||
let completions: Vec<_> = (0..DELTA)
|
||||
.map(|i| {
|
||||
sender.forward_with_completion(text_notification(&format!("delta-{i}")))
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Gate-open point; then concurrent producer emits live updates.
|
||||
let live_sender = sender.clone();
|
||||
let producer = tokio::task::spawn_local(async move {
|
||||
for i in 0..LIVE {
|
||||
live_sender
|
||||
.forward_fire_and_forget(text_notification(&format!("live-{i}")));
|
||||
// Encourage interleaving with drain.
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
});
|
||||
|
||||
// Drain replay completions while producer runs.
|
||||
for rx in completions {
|
||||
let _ = rx.await;
|
||||
}
|
||||
|
||||
// Mark response boundary.
|
||||
log.borrow_mut().push("RESPONSE".into());
|
||||
|
||||
// Let producer and gateway finish remaining live updates.
|
||||
let _ = producer.await;
|
||||
for _ in 0..LIVE + 5 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
|
||||
let log = log.borrow();
|
||||
let response_idx = log
|
||||
.iter()
|
||||
.position(|s| s == "RESPONSE")
|
||||
.expect("RESPONSE marker must be in the log");
|
||||
|
||||
// (1) Delta notifications are all present and before RESPONSE.
|
||||
for i in 0..DELTA {
|
||||
let tag = format!("delta-{i}");
|
||||
let pos = log
|
||||
.iter()
|
||||
.position(|s| s == &tag)
|
||||
.unwrap_or_else(|| panic!("missing delta notification: {tag}"));
|
||||
assert!(
|
||||
pos < response_idx,
|
||||
"{tag} at index {pos} must precede RESPONSE at index {response_idx}"
|
||||
);
|
||||
}
|
||||
|
||||
// (2) Delta notifications preserve enqueue order.
|
||||
let delta_positions: Vec<usize> = (0..DELTA)
|
||||
.map(|i| log.iter().position(|s| s == &format!("delta-{i}")).unwrap())
|
||||
.collect();
|
||||
for w in delta_positions.windows(2) {
|
||||
assert!(
|
||||
w[0] < w[1],
|
||||
"delta ordering violated: delta at index {} came after delta at index {}",
|
||||
w[0],
|
||||
w[1]
|
||||
);
|
||||
}
|
||||
|
||||
// (3) No live updates are lost.
|
||||
for i in 0..LIVE {
|
||||
let tag = format!("live-{i}");
|
||||
assert!(
|
||||
log.iter().any(|s| s == &tag),
|
||||
"live update lost: {tag} not found in log"
|
||||
);
|
||||
}
|
||||
|
||||
// (4) Live updates do not precede replay delta.
|
||||
let last_delta = *delta_positions.last().unwrap();
|
||||
for i in 0..LIVE {
|
||||
let tag = format!("live-{i}");
|
||||
let pos = log.iter().position(|s| s == &tag).unwrap();
|
||||
assert!(
|
||||
pos > last_delta,
|
||||
"{tag} at index {pos} must come after last delta at index {last_delta}"
|
||||
);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
mod channel;
|
||||
mod common;
|
||||
mod gateway;
|
||||
mod line_reader;
|
||||
mod message;
|
||||
mod normalize;
|
||||
mod stdin_reader;
|
||||
|
||||
pub use self::{
|
||||
channel::{AcpAgentChannel, AcpChannel, AcpClientChannel, acp_channels, acp_send},
|
||||
common::{
|
||||
AcpAgentRx, AcpAgentTx, AcpChannelFailure, AcpClientRx, AcpClientTx, AcpResult, AcpRxo,
|
||||
AcpTxo, acp_channel_failure, acp_internal_error,
|
||||
},
|
||||
gateway::{
|
||||
AcpAgentGatewayReceiver, AcpAgentGatewaySender, AcpClientGatewayReceiver,
|
||||
AcpClientGatewaySender, AcpGatewayReceiver, AcpGatewaySender, acp_gateway,
|
||||
},
|
||||
message::{
|
||||
AcpAgentMessage, AcpAgentMessageBox, AcpAgentMessageGeneric, AcpArgs, AcpArgsBox,
|
||||
AcpClientMessage, AcpClientMessageBox, AcpClientMessageGeneric, AcpMethod, AcpRequest,
|
||||
AcpSide, Boxed, StorageMarker, Unboxed,
|
||||
},
|
||||
};
|
||||
|
||||
pub use self::line_reader::LineBufferedRead;
|
||||
pub use self::stdin_reader::spawn_stdin_line_reader;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::common::compact_json;
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Cancel-safe line-buffered [`AsyncRead`] wrapper.
|
||||
//!
|
||||
//! `agent-client-protocol` v0.6's `handle_io` uses `select_biased!` with
|
||||
//! `BufReader::read_line`. `read_line` is **not** cancel-safe: it internally
|
||||
//! calls `consume()` on partial reads, so dropping the future mid-read loses
|
||||
//! bytes and corrupts the stream.
|
||||
//!
|
||||
//! [`LineBufferedRead`] works around this by pre-reading complete `\n`-delimited
|
||||
//! lines on a dedicated task and serving them through a channel. The `poll_read`
|
||||
//! implementation only returns `Pending` *between* lines (when no buffered data
|
||||
//! remains), so ACP's `BufReader::read_line` always finds `\n` without
|
||||
//! suspending, and can never be cancelled mid-read by `select_biased!`.
|
||||
|
||||
use std::{
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use futures::{
|
||||
AsyncBufRead, AsyncBufReadExt as _, AsyncRead, SinkExt as _, StreamExt as _, channel::mpsc,
|
||||
io::BufReader,
|
||||
};
|
||||
|
||||
/// Maximum size of a single NDJSON line (64 MiB).
|
||||
///
|
||||
/// Prevents unbounded memory growth if a peer sends data without newlines.
|
||||
/// 64 MiB accommodates the largest legitimate ACP messages (e.g. a
|
||||
/// multi-megabyte file read response after JSON string escaping).
|
||||
const MAX_LINE_SIZE: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// An [`AsyncRead`] that only yields complete `\n`-delimited lines.
|
||||
///
|
||||
/// Internally, a background task reads lines from the wrapped reader and sends
|
||||
/// them through a channel. [`poll_read`](AsyncRead::poll_read) serves bytes
|
||||
/// from the current line buffer and only returns `Poll::Pending` when no
|
||||
/// buffered bytes remain (i.e. between lines). This guarantees that a consumer
|
||||
/// calling `BufReader::read_line` on this reader will always complete without
|
||||
/// intermediate `Pending` states, making it safe to use inside `select!`.
|
||||
pub struct LineBufferedRead {
|
||||
/// Buffered bytes from the current line being served.
|
||||
buf: Vec<u8>,
|
||||
/// Read cursor within `buf`.
|
||||
pos: usize,
|
||||
/// Receives complete lines (or an IO error) from the reader task.
|
||||
rx: mpsc::Receiver<io::Result<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl LineBufferedRead {
|
||||
/// Wrap an `AsyncRead` source, spawning the reader task via
|
||||
/// [`tokio::task::spawn_local`].
|
||||
pub fn spawn_local(source: impl AsyncRead + Unpin + 'static) -> Self {
|
||||
Self::new(source, |fut| {
|
||||
tokio::task::spawn_local(fut);
|
||||
})
|
||||
}
|
||||
|
||||
/// Wrap an `AsyncRead` source with cancel-safe line buffering.
|
||||
///
|
||||
/// A background task is spawned (via `spawn`) that reads `\n`-delimited
|
||||
/// lines from `source` and feeds them into the returned reader.
|
||||
pub fn new(
|
||||
source: impl AsyncRead + Unpin + 'static,
|
||||
spawn: impl FnOnce(futures::future::LocalBoxFuture<'static, ()>),
|
||||
) -> Self {
|
||||
let (mut tx, rx) = mpsc::channel(64);
|
||||
|
||||
spawn(Box::pin(async move {
|
||||
let mut reader = BufReader::new(source);
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
match read_line_capped(&mut reader, &mut line).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => {
|
||||
if tx.send(Ok(line.split_off(0))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = tx.send(Err(e)).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
Self {
|
||||
buf: Vec::new(),
|
||||
pos: 0,
|
||||
rx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for LineBufferedRead {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut [u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let this = self.get_mut();
|
||||
|
||||
// Serve remaining bytes from the current line.
|
||||
if this.pos < this.buf.len() {
|
||||
let avail = this.buf.len() - this.pos;
|
||||
let n = avail.min(buf.len());
|
||||
buf[..n].copy_from_slice(&this.buf[this.pos..this.pos + n]);
|
||||
this.pos += n;
|
||||
if this.pos >= this.buf.len() {
|
||||
this.buf.clear();
|
||||
this.pos = 0;
|
||||
}
|
||||
return Poll::Ready(Ok(n));
|
||||
}
|
||||
|
||||
// No buffered data — try to receive the next complete line.
|
||||
match this.rx.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok(line))) => {
|
||||
let n = line.len().min(buf.len());
|
||||
buf[..n].copy_from_slice(&line[..n]);
|
||||
if n < line.len() {
|
||||
// Stash the remainder for subsequent poll_read calls.
|
||||
this.buf = line;
|
||||
this.pos = n;
|
||||
}
|
||||
Poll::Ready(Ok(n))
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => Poll::Ready(Err(e)),
|
||||
Poll::Ready(None) => Poll::Ready(Ok(0)), // EOF
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a single `\n`-delimited line into `buf`, capped at [`MAX_LINE_SIZE`].
|
||||
///
|
||||
/// Unlike `read_line`, this checks the accumulated size after each internal
|
||||
/// buffer fill, so memory usage stays bounded even if the peer never sends
|
||||
/// a newline.
|
||||
async fn read_line_capped(
|
||||
reader: &mut (impl AsyncBufRead + Unpin),
|
||||
buf: &mut Vec<u8>,
|
||||
) -> io::Result<usize> {
|
||||
buf.clear();
|
||||
loop {
|
||||
let (consumed, done) = {
|
||||
let available = reader.fill_buf().await?;
|
||||
if available.is_empty() {
|
||||
return Ok(buf.len()); // EOF
|
||||
}
|
||||
match available.iter().position(|&b| b == b'\n') {
|
||||
Some(pos) => {
|
||||
buf.extend_from_slice(&available[..=pos]);
|
||||
(pos + 1, true)
|
||||
}
|
||||
None => {
|
||||
buf.extend_from_slice(available);
|
||||
(available.len(), false)
|
||||
}
|
||||
}
|
||||
};
|
||||
reader.consume_unpin(consumed);
|
||||
if buf.len() > MAX_LINE_SIZE {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"ACP message exceeds {} byte limit ({} bytes read)",
|
||||
MAX_LINE_SIZE,
|
||||
buf.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
if done {
|
||||
return Ok(buf.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::{AsyncReadExt as _, io::Cursor};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Helper: run a test inside a tokio LocalSet so spawn_local works.
|
||||
fn run<F: Future<Output = ()>>(f: F) {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
tokio::task::LocalSet::new().run_until(f).await;
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line() {
|
||||
run(async {
|
||||
let source = Cursor::new(b"hello world\n");
|
||||
let mut reader = LineBufferedRead::spawn_local(source);
|
||||
let mut buf = Vec::new();
|
||||
reader.read_to_end(&mut buf).await.unwrap();
|
||||
assert_eq!(buf, b"hello world\n");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_lines() {
|
||||
run(async {
|
||||
let source = Cursor::new(b"line1\nline2\nline3\n");
|
||||
let mut reader = LineBufferedRead::spawn_local(source);
|
||||
let mut buf = Vec::new();
|
||||
reader.read_to_end(&mut buf).await.unwrap();
|
||||
assert_eq!(buf, b"line1\nline2\nline3\n");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof_with_partial_line() {
|
||||
run(async {
|
||||
let source = Cursor::new(b"complete\nno trailing newline");
|
||||
let mut reader = LineBufferedRead::spawn_local(source);
|
||||
let mut buf = Vec::new();
|
||||
reader.read_to_end(&mut buf).await.unwrap();
|
||||
assert_eq!(buf, b"complete\nno trailing newline");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_input() {
|
||||
run(async {
|
||||
let source = Cursor::new(b"");
|
||||
let mut reader = LineBufferedRead::spawn_local(source);
|
||||
let mut buf = Vec::new();
|
||||
reader.read_to_end(&mut buf).await.unwrap();
|
||||
assert!(buf.is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_line_within_limit() {
|
||||
run(async {
|
||||
// A line larger than BufReader's 8KB buffer but well under 64 MiB.
|
||||
let mut data = vec![b'x'; 100_000];
|
||||
data.push(b'\n');
|
||||
let source = Cursor::new(data.clone());
|
||||
let mut reader = LineBufferedRead::spawn_local(source);
|
||||
let mut buf = Vec::new();
|
||||
reader.read_to_end(&mut buf).await.unwrap();
|
||||
assert_eq!(buf, data);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_line_capped_rejects_oversized() {
|
||||
// Test the capped reader directly with a small override isn't
|
||||
// practical (MAX_LINE_SIZE is const), so test via the real limit.
|
||||
// Just verify the function works for normal input.
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
let data = b"normal line\n";
|
||||
let mut reader = BufReader::new(Cursor::new(&data[..]));
|
||||
let mut buf = Vec::new();
|
||||
let n = read_line_capped(&mut reader, &mut buf).await.unwrap();
|
||||
assert_eq!(n, 12);
|
||||
assert_eq!(buf, b"normal line\n");
|
||||
|
||||
// EOF returns 0
|
||||
buf.clear();
|
||||
let n = read_line_capped(&mut reader, &mut buf).await.unwrap();
|
||||
assert_eq!(n, 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_read_buffer() {
|
||||
run(async {
|
||||
// Verify poll_read correctly serves a line across multiple small reads.
|
||||
let source = Cursor::new(b"abcdef\n");
|
||||
let mut reader = LineBufferedRead::spawn_local(source);
|
||||
let mut small_buf = [0u8; 3];
|
||||
|
||||
// First read: "abc"
|
||||
let n = reader.read(&mut small_buf).await.unwrap();
|
||||
assert_eq!(&small_buf[..n], b"abc");
|
||||
|
||||
// Second read: "def"
|
||||
let n = reader.read(&mut small_buf).await.unwrap();
|
||||
assert_eq!(&small_buf[..n], b"def");
|
||||
|
||||
// Third read: "\n"
|
||||
let n = reader.read(&mut small_buf).await.unwrap();
|
||||
assert_eq!(&small_buf[..n], b"\n");
|
||||
|
||||
// EOF
|
||||
let n = reader.read(&mut small_buf).await.unwrap();
|
||||
assert_eq!(n, 0);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
use std::{borrow::Borrow, fmt, ops::Deref};
|
||||
|
||||
use agent_client_protocol as acp;
|
||||
use derive_more::From;
|
||||
use serde::{Deserialize, Serialize, ser::SerializeStruct};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::common::AcpResult;
|
||||
|
||||
pub use self::{
|
||||
agent::{AcpAgentMessage, AcpAgentMessageBox, AcpAgentMessageGeneric},
|
||||
client::{AcpClientMessage, AcpClientMessageBox, AcpClientMessageGeneric},
|
||||
};
|
||||
|
||||
/// Marker trait representing one side of the ACP connection.
|
||||
pub trait AcpSide {
|
||||
/// What does this side receive.
|
||||
type InMessage: AcpMethod + fmt::Debug;
|
||||
/// What does this side send.
|
||||
type OutMessage: AcpMethod + fmt::Debug;
|
||||
/// Marker type for the other side.
|
||||
type OtherSide: AcpSide;
|
||||
/// Display name for this side.
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
/// Marker type representing the agent's view of the ACP connection (as one side of that connection).
|
||||
impl AcpSide for acp::AgentSide {
|
||||
type InMessage = AcpAgentMessage; // inbound messages = messages meant *for* the agent
|
||||
type OutMessage = AcpClientMessage; // outbound messages = messages meant *for* the client
|
||||
type OtherSide = acp::ClientSide;
|
||||
const NAME: &'static str = "agent";
|
||||
}
|
||||
|
||||
/// Marker type representing the agent's view of the ACP connection (as one side of that connection).
|
||||
impl AcpSide for acp::ClientSide {
|
||||
type InMessage = AcpClientMessage; // inbound messages = messages meant *for* the client
|
||||
type OutMessage = AcpAgentMessage; // outbound messages = messages meant *for* the agent
|
||||
type OtherSide = acp::AgentSide;
|
||||
const NAME: &'static str = "client";
|
||||
}
|
||||
|
||||
/// Extends each request/response type pair with the side marker type and schema method name.
|
||||
pub trait AcpMethod {
|
||||
fn method_name(&self) -> &'static str;
|
||||
}
|
||||
|
||||
/// Connect together ACP request and response types for each rpc method.
|
||||
pub trait AcpRequest: Clone + fmt::Debug + Serialize + AcpMethod {
|
||||
type Response: Clone + fmt::Debug + Serialize;
|
||||
}
|
||||
|
||||
/// Contains an ACP request and a oneshot channel where the response of a matching type can be sent.
|
||||
pub struct AcpArgsGeneric<T: AcpRequest, S: StorageMarker> {
|
||||
pub request: S::Type<T>,
|
||||
pub response_tx: oneshot::Sender<AcpResult<T::Response>>,
|
||||
}
|
||||
|
||||
impl<T: AcpRequest, S: StorageMarker> Deref for AcpArgsGeneric<T, S> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.request.borrow()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AcpRequest, S: StorageMarker> fmt::Debug for AcpArgsGeneric<T, S> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{:?}", self.request.borrow())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AcpRequest, S: StorageMarker> AcpMethod for AcpArgsGeneric<T, S> {
|
||||
fn method_name(&self) -> &'static str {
|
||||
self.request.borrow().method_name()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(type_alias_bounds)]
|
||||
pub type AcpArgs<T: AcpRequest> = AcpArgsGeneric<T, Unboxed>;
|
||||
#[allow(type_alias_bounds)]
|
||||
pub type AcpArgsBox<T: AcpRequest> = AcpArgsGeneric<T, Boxed>;
|
||||
|
||||
impl<T: AcpRequest> AcpArgs<T> {
|
||||
pub fn boxed(self) -> AcpArgsBox<T> {
|
||||
AcpArgsBox {
|
||||
request: Box::new(self.request),
|
||||
response_tx: self.response_tx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! acp_define_request_response {
|
||||
($request:ty, $response:ty, $method:expr $(,)?) => {
|
||||
impl AcpRequest for $request {
|
||||
type Response = $response;
|
||||
}
|
||||
|
||||
impl AcpMethod for $request {
|
||||
fn method_name(&self) -> &'static str {
|
||||
$method
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
acp_define_request_response!(acp::ExtRequest, acp::ExtResponse, "ext_method");
|
||||
acp_define_request_response!(acp::ExtNotification, (), "ext_notification");
|
||||
|
||||
pub trait StorageMarker: fmt::Debug + Clone + Copy {
|
||||
type Type<T>: Borrow<T> + From<T>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Unboxed;
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Boxed;
|
||||
|
||||
impl StorageMarker for Unboxed {
|
||||
type Type<T> = T;
|
||||
}
|
||||
|
||||
impl StorageMarker for Boxed {
|
||||
type Type<T> = Box<T>;
|
||||
}
|
||||
|
||||
mod client {
|
||||
use futures::{FutureExt as _, future::LocalBoxFuture};
|
||||
|
||||
use super::*;
|
||||
|
||||
acp_define_request_response!(
|
||||
acp::RequestPermissionRequest,
|
||||
acp::RequestPermissionResponse,
|
||||
acp::CLIENT_METHOD_NAMES.session_request_permission,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::ReadTextFileRequest,
|
||||
acp::ReadTextFileResponse,
|
||||
acp::CLIENT_METHOD_NAMES.fs_read_text_file,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::WriteTextFileRequest,
|
||||
acp::WriteTextFileResponse,
|
||||
acp::CLIENT_METHOD_NAMES.fs_write_text_file,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::SessionNotification,
|
||||
(),
|
||||
acp::CLIENT_METHOD_NAMES.session_update,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::CreateTerminalRequest,
|
||||
acp::CreateTerminalResponse,
|
||||
acp::CLIENT_METHOD_NAMES.terminal_create,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::TerminalOutputRequest,
|
||||
acp::TerminalOutputResponse,
|
||||
acp::CLIENT_METHOD_NAMES.terminal_output,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::ReleaseTerminalRequest,
|
||||
acp::ReleaseTerminalResponse,
|
||||
acp::CLIENT_METHOD_NAMES.terminal_release,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::WaitForTerminalExitRequest,
|
||||
acp::WaitForTerminalExitResponse,
|
||||
acp::CLIENT_METHOD_NAMES.terminal_wait_for_exit,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::KillTerminalRequest,
|
||||
acp::KillTerminalResponse,
|
||||
acp::CLIENT_METHOD_NAMES.terminal_kill,
|
||||
);
|
||||
|
||||
/// ACP messages meant *for* the client.
|
||||
#[derive(Debug, From)]
|
||||
pub enum AcpClientMessageGeneric<S: StorageMarker> {
|
||||
RequestPermission(AcpArgsGeneric<acp::RequestPermissionRequest, S>),
|
||||
ReadTextFile(AcpArgsGeneric<acp::ReadTextFileRequest, S>),
|
||||
WriteTextFile(AcpArgsGeneric<acp::WriteTextFileRequest, S>),
|
||||
SessionNotification(AcpArgsGeneric<acp::SessionNotification, S>),
|
||||
CreateTerminal(AcpArgsGeneric<acp::CreateTerminalRequest, S>),
|
||||
TerminalOutput(AcpArgsGeneric<acp::TerminalOutputRequest, S>),
|
||||
ReleaseTerminal(AcpArgsGeneric<acp::ReleaseTerminalRequest, S>),
|
||||
WaitForTerminalExit(AcpArgsGeneric<acp::WaitForTerminalExitRequest, S>),
|
||||
KillTerminalCommand(AcpArgsGeneric<acp::KillTerminalRequest, S>),
|
||||
ExtMethod(AcpArgsGeneric<acp::ExtRequest, S>),
|
||||
ExtNotification(AcpArgsGeneric<acp::ExtNotification, S>),
|
||||
}
|
||||
|
||||
#[allow(type_alias_bounds)]
|
||||
pub type AcpClientMessage = AcpClientMessageGeneric<Unboxed>;
|
||||
#[allow(type_alias_bounds)]
|
||||
pub type AcpClientMessageBox = AcpClientMessageGeneric<Boxed>;
|
||||
|
||||
impl<S: StorageMarker> AcpMethod for AcpClientMessageGeneric<S> {
|
||||
fn method_name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::RequestPermission(a) => a.method_name(),
|
||||
Self::ReadTextFile(a) => a.method_name(),
|
||||
Self::WriteTextFile(a) => a.method_name(),
|
||||
Self::SessionNotification(a) => a.method_name(),
|
||||
Self::CreateTerminal(a) => a.method_name(),
|
||||
Self::TerminalOutput(a) => a.method_name(),
|
||||
Self::ReleaseTerminal(a) => a.method_name(),
|
||||
Self::WaitForTerminalExit(a) => a.method_name(),
|
||||
Self::KillTerminalCommand(a) => a.method_name(),
|
||||
Self::ExtMethod(a) => a.method_name(),
|
||||
Self::ExtNotification(a) => a.method_name(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AcpClientMessage {
|
||||
pub fn boxed(self) -> AcpClientMessageBox {
|
||||
match self {
|
||||
Self::RequestPermission(args) => {
|
||||
AcpClientMessageBox::RequestPermission(args.boxed())
|
||||
}
|
||||
Self::ReadTextFile(args) => AcpClientMessageBox::ReadTextFile(args.boxed()),
|
||||
Self::WriteTextFile(args) => AcpClientMessageBox::WriteTextFile(args.boxed()),
|
||||
Self::SessionNotification(args) => {
|
||||
AcpClientMessageBox::SessionNotification(args.boxed())
|
||||
}
|
||||
Self::CreateTerminal(args) => AcpClientMessageBox::CreateTerminal(args.boxed()),
|
||||
Self::TerminalOutput(args) => AcpClientMessageBox::TerminalOutput(args.boxed()),
|
||||
Self::ReleaseTerminal(args) => AcpClientMessageBox::ReleaseTerminal(args.boxed()),
|
||||
Self::WaitForTerminalExit(args) => {
|
||||
AcpClientMessageBox::WaitForTerminalExit(args.boxed())
|
||||
}
|
||||
Self::KillTerminalCommand(args) => {
|
||||
AcpClientMessageBox::KillTerminalCommand(args.boxed())
|
||||
}
|
||||
Self::ExtMethod(args) => AcpClientMessageBox::ExtMethod(args.boxed()),
|
||||
Self::ExtNotification(args) => AcpClientMessageBox::ExtNotification(args.boxed()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn route_to_client(
|
||||
self,
|
||||
client: impl acp::Client + 'static, // note: acp::Client is auto-implemented for Rc/Arc
|
||||
spawn: impl Fn(LocalBoxFuture<'static, ()>) + 'static,
|
||||
) {
|
||||
match self {
|
||||
AcpClientMessage::RequestPermission(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.request_permission(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::ReadTextFile(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.read_text_file(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::WriteTextFile(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.write_text_file(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::SessionNotification(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.session_notification(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::CreateTerminal(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.create_terminal(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::TerminalOutput(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.terminal_output(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::ReleaseTerminal(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.release_terminal(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::WaitForTerminalExit(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.wait_for_terminal_exit(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::KillTerminalCommand(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.kill_terminal(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::ExtMethod(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.ext_method(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpClientMessage::ExtNotification(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(client.ext_notification(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod agent {
|
||||
use futures::{FutureExt as _, future::LocalBoxFuture};
|
||||
|
||||
use super::*;
|
||||
|
||||
acp_define_request_response!(
|
||||
acp::InitializeRequest,
|
||||
acp::InitializeResponse,
|
||||
acp::AGENT_METHOD_NAMES.initialize,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::AuthenticateRequest,
|
||||
acp::AuthenticateResponse,
|
||||
acp::AGENT_METHOD_NAMES.authenticate,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::NewSessionRequest,
|
||||
acp::NewSessionResponse,
|
||||
acp::AGENT_METHOD_NAMES.session_new,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::LoadSessionRequest,
|
||||
acp::LoadSessionResponse,
|
||||
acp::AGENT_METHOD_NAMES.session_load,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::SetSessionModeRequest,
|
||||
acp::SetSessionModeResponse,
|
||||
acp::AGENT_METHOD_NAMES.session_set_mode,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::PromptRequest,
|
||||
acp::PromptResponse,
|
||||
acp::AGENT_METHOD_NAMES.session_prompt,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::CancelNotification,
|
||||
(),
|
||||
acp::AGENT_METHOD_NAMES.session_cancel,
|
||||
);
|
||||
acp_define_request_response!(
|
||||
acp::SetSessionModelRequest,
|
||||
acp::SetSessionModelResponse,
|
||||
acp::AGENT_METHOD_NAMES.session_set_model,
|
||||
);
|
||||
|
||||
/// ACP messages meant *for* the agent.
|
||||
#[derive(Debug, From)]
|
||||
pub enum AcpAgentMessageGeneric<S: StorageMarker> {
|
||||
Initialize(AcpArgsGeneric<acp::InitializeRequest, S>),
|
||||
Authenticate(AcpArgsGeneric<acp::AuthenticateRequest, S>),
|
||||
NewSession(AcpArgsGeneric<acp::NewSessionRequest, S>),
|
||||
LoadSession(AcpArgsGeneric<acp::LoadSessionRequest, S>),
|
||||
SetSessionMode(AcpArgsGeneric<acp::SetSessionModeRequest, S>),
|
||||
Prompt(AcpArgsGeneric<acp::PromptRequest, S>),
|
||||
Cancel(AcpArgsGeneric<acp::CancelNotification, S>),
|
||||
ExtMethod(AcpArgsGeneric<acp::ExtRequest, S>),
|
||||
ExtNotification(AcpArgsGeneric<acp::ExtNotification, S>),
|
||||
SetSessionModel(AcpArgsGeneric<acp::SetSessionModelRequest, S>),
|
||||
}
|
||||
|
||||
#[allow(type_alias_bounds)]
|
||||
pub type AcpAgentMessage = AcpAgentMessageGeneric<Unboxed>;
|
||||
#[allow(type_alias_bounds)]
|
||||
pub type AcpAgentMessageBox = AcpAgentMessageGeneric<Boxed>;
|
||||
|
||||
impl<S: StorageMarker> AcpMethod for AcpAgentMessageGeneric<S> {
|
||||
fn method_name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Initialize(a) => a.method_name(),
|
||||
Self::Authenticate(a) => a.method_name(),
|
||||
Self::NewSession(a) => a.method_name(),
|
||||
Self::LoadSession(a) => a.method_name(),
|
||||
Self::SetSessionMode(a) => a.method_name(),
|
||||
Self::Prompt(a) => a.method_name(),
|
||||
Self::Cancel(a) => a.method_name(),
|
||||
Self::ExtMethod(a) => a.method_name(),
|
||||
Self::ExtNotification(a) => a.method_name(),
|
||||
Self::SetSessionModel(a) => a.method_name(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: StorageMarker> Serialize for AcpAgentMessageGeneric<S> {
|
||||
fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
|
||||
where
|
||||
Ser: serde::Serializer,
|
||||
{
|
||||
let mut state = serializer.serialize_struct("AcpAgentMessage", 2)?;
|
||||
state.serialize_field("method_name", self.method_name())?;
|
||||
match self {
|
||||
Self::Initialize(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
Self::Authenticate(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
Self::NewSession(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
Self::LoadSession(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
Self::SetSessionMode(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
Self::Prompt(args) => state.serialize_field("request", args.request.borrow())?,
|
||||
Self::Cancel(args) => state.serialize_field("request", args.request.borrow())?,
|
||||
Self::ExtMethod(args) => state.serialize_field("request", args.request.borrow())?,
|
||||
Self::ExtNotification(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
Self::SetSessionModel(args) => {
|
||||
state.serialize_field("request", args.request.borrow())?
|
||||
}
|
||||
}
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for AcpAgentMessage {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
struct RawMessage {
|
||||
method_name: String,
|
||||
request: serde_json::Value,
|
||||
}
|
||||
|
||||
let raw = RawMessage::deserialize(deserializer)?;
|
||||
let method = raw.method_name.as_str();
|
||||
|
||||
macro_rules! parse {
|
||||
($variant:ident) => {{
|
||||
let (response_tx, _) = oneshot::channel();
|
||||
Ok(Self::$variant(AcpArgs {
|
||||
request: serde_json::from_value(raw.request)
|
||||
.map_err(serde::de::Error::custom)?,
|
||||
response_tx,
|
||||
}))
|
||||
}};
|
||||
}
|
||||
|
||||
if method == acp::AGENT_METHOD_NAMES.initialize {
|
||||
parse!(Initialize)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.authenticate {
|
||||
parse!(Authenticate)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.session_new {
|
||||
parse!(NewSession)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.session_load {
|
||||
parse!(LoadSession)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.session_set_mode {
|
||||
parse!(SetSessionMode)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.session_prompt {
|
||||
parse!(Prompt)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.session_cancel {
|
||||
parse!(Cancel)
|
||||
} else if method == acp::AGENT_METHOD_NAMES.session_set_model {
|
||||
parse!(SetSessionModel)
|
||||
} else if method == "ext_method" {
|
||||
parse!(ExtMethod)
|
||||
} else if method == "ext_notification" {
|
||||
parse!(ExtNotification)
|
||||
} else {
|
||||
Err(serde::de::Error::custom(format!(
|
||||
"Unknown method name: {method}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AcpAgentMessage {
|
||||
pub fn boxed(self) -> AcpAgentMessageBox {
|
||||
match self {
|
||||
Self::Initialize(args) => AcpAgentMessageBox::Initialize(args.boxed()),
|
||||
Self::Authenticate(args) => AcpAgentMessageBox::Authenticate(args.boxed()),
|
||||
Self::NewSession(args) => AcpAgentMessageBox::NewSession(args.boxed()),
|
||||
Self::LoadSession(args) => AcpAgentMessageBox::LoadSession(args.boxed()),
|
||||
Self::SetSessionMode(args) => AcpAgentMessageBox::SetSessionMode(args.boxed()),
|
||||
Self::Prompt(args) => AcpAgentMessageBox::Prompt(args.boxed()),
|
||||
Self::Cancel(args) => AcpAgentMessageBox::Cancel(args.boxed()),
|
||||
Self::ExtMethod(args) => AcpAgentMessageBox::ExtMethod(args.boxed()),
|
||||
Self::ExtNotification(args) => AcpAgentMessageBox::ExtNotification(args.boxed()),
|
||||
Self::SetSessionModel(args) => AcpAgentMessageBox::SetSessionModel(args.boxed()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn route_to_agent(
|
||||
self,
|
||||
agent: impl acp::Agent + 'static, // note: acp::Agent is auto-implemented for Rc/Arc
|
||||
spawn: impl Fn(LocalBoxFuture<'static, ()>) + 'static,
|
||||
) {
|
||||
match self {
|
||||
AcpAgentMessage::Initialize(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.initialize(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::Authenticate(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.authenticate(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::NewSession(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.new_session(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::LoadSession(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.load_session(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::SetSessionMode(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.set_session_mode(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::Prompt(args) => spawn(
|
||||
async move {
|
||||
_ = args.response_tx.send(agent.prompt(args.request).await).ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::Cancel(args) => spawn(
|
||||
async move {
|
||||
_ = args.response_tx.send(agent.cancel(args.request).await).ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::ExtMethod(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.ext_method(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::ExtNotification(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.ext_notification(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
AcpAgentMessage::SetSessionModel(args) => spawn(
|
||||
async move {
|
||||
_ = args
|
||||
.response_tx
|
||||
.send(agent.set_session_model(args.request).await)
|
||||
.ok();
|
||||
}
|
||||
.boxed_local(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Foundation escaped-slash normalization for inbound ACP stdin lines — the
|
||||
//! crate's second `agent-client-protocol` v0.6 wire workaround, alongside
|
||||
//! [`LineBufferedRead`](crate::LineBufferedRead).
|
||||
//!
|
||||
//! [`spawn_stdin_line_reader`](crate::spawn_stdin_line_reader) feeds every
|
||||
//! line through [`normalize_json_line`]; unhooking that one call site removes
|
||||
//! the workaround once the upstream envelope parses `method` as an
|
||||
//! owned/`Cow` string.
|
||||
//!
|
||||
//! Scope: only process-stdin ingress is normalized. Clients that connect
|
||||
//! directly to the leader socket bypass this module — fine today, those are
|
||||
//! first-party clients whose encoders never emit `\/`.
|
||||
//!
|
||||
//! Downstream dependency: the leader bridge's replay sniff
|
||||
//! (`xai-grok-pager-bin/src/main.rs`, the `trimmed.contains("\"session/new\"")`
|
||||
//! checks) matches escaped Foundation input only because this normalization
|
||||
//! runs upstream of it.
|
||||
|
||||
/// Foundation (Xcode) escapes `/` as `\/` by default, and the pinned
|
||||
/// `agent-client-protocol` 0.6 envelope parses `method` as a borrowed `&str`
|
||||
/// ([`RawIncomingMessage`](agent_client_protocol::RawIncomingMessage)), so any
|
||||
/// escape inside `method` fails the whole envelope parse and the line is
|
||||
/// silently dropped. Re-serializing through `serde_json` — which never emits
|
||||
/// `\/` — makes the method borrowable again.
|
||||
///
|
||||
/// Rewrites touch only lines the crate would otherwise drop: the two-byte `\/`
|
||||
/// scan is a cheap prefilter (serde_json / `JSON.stringify` never emit it),
|
||||
/// and a line that then parses as the real pinned envelope — e.g. a
|
||||
/// clean-method prompt whose params contain `s/\//_/g` — passes through
|
||||
/// byte-identical, so healthy clients are untouched by construction. Tradeoff:
|
||||
/// a hypothetical `\u002F`-escaped method is not normalized (no known encoder
|
||||
/// emits that, and `\u` can't be the prefilter — JS legitimately emits
|
||||
/// `\u2028` and surrogate pairs in text).
|
||||
///
|
||||
/// Any line that fails both parses passes through byte-identical —
|
||||
/// deliberately: the acp crate keeps ownership of garbage handling.
|
||||
pub(crate) fn normalize_json_line(line: Vec<u8>) -> Vec<u8> {
|
||||
if !line.windows(2).any(|w| w == br"\/") {
|
||||
return line;
|
||||
}
|
||||
// Same type + bytes the acp crate will parse (trailing terminator is JSON
|
||||
// whitespace): if it accepts the line, forward it byte-identical.
|
||||
if serde_json::from_slice::<agent_client_protocol::RawIncomingMessage>(&line).is_ok() {
|
||||
return line;
|
||||
}
|
||||
let body_len = line
|
||||
.iter()
|
||||
.rposition(|&b| b != b'\n' && b != b'\r')
|
||||
.map_or(0, |pos| pos + 1);
|
||||
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&line[..body_len]) else {
|
||||
// Exactly the line class the acp 0.6 envelope will then drop silently.
|
||||
tracing::debug!(
|
||||
len = line.len(),
|
||||
"unparseable escaped-slash stdin line passed through; acp may drop it"
|
||||
);
|
||||
return line;
|
||||
};
|
||||
let Ok(mut normalized) = serde_json::to_vec(&value) else {
|
||||
return line;
|
||||
};
|
||||
normalized.extend_from_slice(&line[body_len..]);
|
||||
tracing::debug!(
|
||||
len = line.len(),
|
||||
normalized_len = normalized.len(),
|
||||
"normalized escaped-slash line for the acp 0.6 envelope"
|
||||
);
|
||||
normalized
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use agent_client_protocol::RawIncomingMessage;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn escaped_slash_method_accepted_by_upstream_cow_envelope() {
|
||||
// acp 0.10.4+ parses `method` as Cow<str>, so Foundation-style
|
||||
// `session\/prompt` is accepted without our re-serialization rewrite.
|
||||
let raw =
|
||||
br#"{"jsonrpc":"2.0","id":"5DE7EA60-0B0C-4A43-9650-2B72CDF6A44B","method":"session\/prompt","params":{}}"#;
|
||||
let mut line = raw.to_vec();
|
||||
line.push(b'\n');
|
||||
assert!(serde_json::from_slice::<RawIncomingMessage>(raw).is_ok());
|
||||
|
||||
let normalized = normalize_json_line(line.clone());
|
||||
// Early-return path: envelope-acceptable lines pass through byte-identical.
|
||||
assert_eq!(normalized, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_json_with_escaped_slash_passes_through_byte_identical() {
|
||||
let line = b"not json \\/ at all\n".to_vec();
|
||||
assert_eq!(normalize_json_line(line.clone()), line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_without_backslash_passes_through_untouched() {
|
||||
let expected = br#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#.to_vec();
|
||||
let line = expected.clone();
|
||||
let ptr = line.as_ptr();
|
||||
|
||||
let normalized = normalize_json_line(line);
|
||||
|
||||
assert_eq!(normalized, expected);
|
||||
// Same allocation: the fast path never parsed or re-serialized.
|
||||
assert_eq!(normalized.as_ptr(), ptr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_escapes_without_escaped_slash_pass_through_untouched() {
|
||||
let raw =
|
||||
br#"{"jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"text":"a\nb \"q\" c\\d"}}"#;
|
||||
let expected = raw.to_vec();
|
||||
let line = expected.clone();
|
||||
let ptr = line.as_ptr();
|
||||
|
||||
let normalized = normalize_json_line(line);
|
||||
|
||||
assert_eq!(normalized, expected);
|
||||
// Same allocation: `\n`/`\"`/`\\` escapes alone never trip the rewrite.
|
||||
assert_eq!(normalized.as_ptr(), ptr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_slash_in_params_with_clean_method_passes_through_byte_identical() {
|
||||
// serde_json wire form of a prompt containing `s/\//_/g`: the `\\/`
|
||||
// bytes trip the `\/` prefilter, but the envelope parses the line.
|
||||
let raw =
|
||||
br#"{"jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"text":"s/\\//_/g"}}"#;
|
||||
assert!(raw.windows(2).any(|w| w == br"\/"));
|
||||
assert!(serde_json::from_slice::<RawIncomingMessage>(raw).is_ok());
|
||||
let expected = raw.to_vec();
|
||||
let line = expected.clone();
|
||||
let ptr = line.as_ptr();
|
||||
|
||||
let normalized = normalize_json_line(line);
|
||||
|
||||
assert_eq!(normalized, expected);
|
||||
// Same allocation: envelope-acceptable lines are never re-serialized.
|
||||
assert_eq!(normalized.as_ptr(), ptr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_string_escapes_keep_their_semantics() {
|
||||
let raw =
|
||||
br#"{"jsonrpc":"2.0","id":1,"method":"session\/prompt","params":{"text":"a\/b\nc \"q\" d\\e"}}"#;
|
||||
let mut line = raw.to_vec();
|
||||
line.push(b'\n');
|
||||
|
||||
let normalized = normalize_json_line(line);
|
||||
|
||||
let value: serde_json::Value = serde_json::from_slice(&normalized).unwrap();
|
||||
assert_eq!(value["method"], "session/prompt");
|
||||
assert_eq!(value["params"]["text"], "a/b\nc \"q\" d\\e");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_terminator_is_preserved() {
|
||||
let mut line = br#"{"id":2,"method":"session\/new"}"#.to_vec();
|
||||
line.extend_from_slice(b"\r\n");
|
||||
|
||||
let normalized = normalize_json_line(line);
|
||||
|
||||
assert!(normalized.ends_with(b"\r\n"));
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_slice(&normalized[..normalized.len() - 2]).unwrap();
|
||||
assert_eq!(value["method"], "session/new");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_line_without_newline_gains_no_newline() {
|
||||
let line = br#"{"id":3,"method":"session\/new"}"#.to_vec();
|
||||
|
||||
let normalized = normalize_json_line(line);
|
||||
|
||||
assert_ne!(normalized.last(), Some(&b'\n'));
|
||||
let value: serde_json::Value = serde_json::from_slice(&normalized).unwrap();
|
||||
assert_eq!(value["method"], "session/new");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Dedicated-thread reader for the ACP stdio transport's standard input.
|
||||
//!
|
||||
//! Every ACP client (VS Code extension, grok-desktop, the leader bridge) drives
|
||||
//! the agent over a **persistent, bidirectional** newline-delimited JSON-RPC
|
||||
//! stream on stdio: it writes requests on the child's stdin and reads responses
|
||||
//! on stdout, keeping **stdin open for the whole session**.
|
||||
//!
|
||||
//! # Why not `tokio::io::stdin()`
|
||||
//!
|
||||
//! `tokio::io::stdin()` is not truly asynchronous. Tokio services it with a
|
||||
//! blocking `std::io` read on an internal pool thread, and that read **cannot be
|
||||
//! cancelled**. For interactive / persistent uses the
|
||||
//! [`tokio::io::Stdin`](https://docs.rs/tokio/latest/tokio/io/struct.Stdin.html)
|
||||
//! docs recommend "spawn a thread dedicated to user input and use blocking IO
|
||||
//! directly in that thread". [`spawn_stdin_line_reader`] does exactly that.
|
||||
//!
|
||||
//! # Why the reader takes *exclusive* ownership of stdin (Windows)
|
||||
//!
|
||||
//! `std::io::Stdin` is a process-global handle guarded by a re-entrant mutex
|
||||
//! (the `StdinLock`). A blocking read **holds that lock for the entire duration
|
||||
//! of the read** — and for the persistent stdio transport the reader is almost
|
||||
//! always parked in a read, waiting for the client's next line. If *any other*
|
||||
//! code in the process then calls `std::io::stdin()` (e.g. a stray interactive
|
||||
//! prompt reached only on a particular platform), it blocks on the lock until
|
||||
//! the reader's in-flight read returns — which only happens at **EOF**, i.e.
|
||||
//! when the client closes stdin. For a persistent ACP client that never closes
|
||||
//! stdin mid-session this is a hard hang: the agent freezes part-way through a
|
||||
//! request (observed on **Windows** during `session/new`) and only unblocks when
|
||||
//! the transport is torn down. macOS/Linux don't reach the offending stray read,
|
||||
//! so they were unaffected — but the hazard is real on any platform.
|
||||
//!
|
||||
//! To make the transport robust, on Windows the reader thread takes a **private
|
||||
//! duplicate** of the real stdin handle and then points the process's standard
|
||||
//! input at **`NUL`**. The reader keeps reading the client's bytes through its
|
||||
//! private handle, while every *other* `std::io::stdin()` read in the process
|
||||
//! observes immediate EOF instead of deadlocking on the lock. This mirrors what
|
||||
//! already makes leader mode safe (the agent subprocess is spawned with
|
||||
//! `stdin = NUL`, so its stray reads EOF instantly). Unix keeps reading
|
||||
//! `std::io::stdin()` directly — it has no second stdin reader on these paths
|
||||
//! and the extra FFI/`dup` would add risk for no benefit.
|
||||
//!
|
||||
//! # Escaped-slash normalization (acp 0.6 wire workaround)
|
||||
//!
|
||||
//! Every line is forwarded through `normalize_json_line` — see the
|
||||
//! crate-private `normalize` module for the contract and its scope.
|
||||
|
||||
use std::io::BufRead;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::normalize::normalize_json_line;
|
||||
|
||||
/// Channel depth for buffered stdin lines. Small: the reader thread blocks on a
|
||||
/// full channel, applying natural backpressure to a flooding peer rather than
|
||||
/// growing memory without bound.
|
||||
const STDIN_LINE_CHANNEL_DEPTH: usize = 64;
|
||||
|
||||
/// Spawn a dedicated OS thread that reads newline-delimited lines from the
|
||||
/// process's standard input with **synchronous, blocking** `std::io` and yields
|
||||
/// each line (its trailing `\n` included, like `read_line`/`read_until`) on the
|
||||
/// returned channel. A final line without a trailing newline is still delivered
|
||||
/// before the channel closes.
|
||||
///
|
||||
/// Yielded lines are **not guaranteed byte-verbatim**: a line the pinned acp
|
||||
/// 0.6 envelope would otherwise drop (a `\/`-escaped `method`, as Foundation
|
||||
/// encoders emit) is re-serialized compactly (key order, whitespace, and
|
||||
/// number formatting normalized) before forwarding — see the crate-private
|
||||
/// `normalize` module. Every line the envelope already accepts, and anything
|
||||
/// that fails to parse, passes through byte-identical (trailing terminator
|
||||
/// always preserved).
|
||||
///
|
||||
/// The channel closes (so [`recv`](mpsc::Receiver::recv) returns `None`) when
|
||||
/// stdin reaches EOF, the read fails, or the [`Receiver`](mpsc::Receiver) is
|
||||
/// dropped. The reader is meant to be the **sole** stdin consumer in the
|
||||
/// agent-stdio / leader-bridge paths; on Windows it enforces that by redirecting
|
||||
/// the process's standard input to `NUL` so stray readers can't deadlock on it
|
||||
/// (see the [module docs](self)).
|
||||
pub fn spawn_stdin_line_reader() -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel::<Vec<u8>>(STDIN_LINE_CHANNEL_DEPTH);
|
||||
|
||||
// On Windows, synchronously take a private duplicate of the real stdin and
|
||||
// redirect the process's standard input to `NUL` *before* the reader thread
|
||||
// parks in a blocking read holding the global `StdinLock`. After this, any
|
||||
// other `std::io::stdin()` read in the process EOFs immediately instead of
|
||||
// deadlocking. `None` means we couldn't isolate (we fall back to reading
|
||||
// `std::io::stdin()` directly — no worse than before).
|
||||
#[cfg(windows)]
|
||||
let private_stdin: Option<std::fs::File> = isolate_process_stdin();
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("acp-stdin".to_string())
|
||||
.spawn(move || {
|
||||
#[cfg(windows)]
|
||||
if let Some(file) = private_stdin {
|
||||
forward_lines(std::io::BufReader::new(file), &tx);
|
||||
return;
|
||||
}
|
||||
let stdin = std::io::stdin();
|
||||
forward_lines(stdin.lock(), &tx);
|
||||
})
|
||||
.expect("failed to spawn acp-stdin reader thread");
|
||||
rx
|
||||
}
|
||||
|
||||
/// Read `\n`-delimited lines from `reader` and forward each on `tx` — via
|
||||
/// [`normalize_json_line`], so bytes are verbatim except for the lines that
|
||||
/// workaround rewrites (terminator always preserved) — until EOF, a read
|
||||
/// error, or the receiver is dropped.
|
||||
fn forward_lines<R: BufRead>(mut reader: R, tx: &mpsc::Sender<Vec<u8>>) {
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
line.clear();
|
||||
match reader.read_until(b'\n', &mut line) {
|
||||
// EOF or a fatal read error: return, dropping `tx` closes the channel.
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
let normalized = normalize_json_line(std::mem::take(&mut line));
|
||||
// `blocking_send` parks this thread (not a runtime worker) when the
|
||||
// channel is full, and errors only once the receiver is dropped — at
|
||||
// which point there is nothing left to feed.
|
||||
if tx.blocking_send(normalized).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Duplicate the real stdin handle for private use and repoint the process's
|
||||
/// `STD_INPUT_HANDLE` at `NUL`, returning the duplicate as an owned [`File`].
|
||||
///
|
||||
/// Returns `None` (caller falls back to `std::io::stdin()`) when there is no
|
||||
/// stdin handle or duplication fails. Win32 declarations are inlined to avoid a
|
||||
/// `windows`/`windows-sys` dependency, matching the pager's console setup.
|
||||
///
|
||||
/// [`File`]: std::fs::File
|
||||
#[cfg(windows)]
|
||||
fn isolate_process_stdin() -> Option<std::fs::File> {
|
||||
use std::os::windows::io::FromRawHandle as _;
|
||||
|
||||
// Win32 constants (inlined to avoid a dependency).
|
||||
const STD_INPUT_HANDLE: u32 = 0xFFFF_FFF6; // (DWORD)-10
|
||||
const DUPLICATE_SAME_ACCESS: u32 = 0x0000_0002;
|
||||
const GENERIC_READ: u32 = 0x8000_0000;
|
||||
const FILE_SHARE_READ: u32 = 0x0000_0001;
|
||||
const FILE_SHARE_WRITE: u32 = 0x0000_0002;
|
||||
const OPEN_EXISTING: u32 = 0x0000_0003;
|
||||
const INVALID_HANDLE: *mut core::ffi::c_void = -1_isize as *mut core::ffi::c_void;
|
||||
|
||||
unsafe extern "system" {
|
||||
fn GetStdHandle(nStdHandle: u32) -> *mut core::ffi::c_void;
|
||||
fn SetStdHandle(nStdHandle: u32, hHandle: *mut core::ffi::c_void) -> i32;
|
||||
fn GetCurrentProcess() -> *mut core::ffi::c_void;
|
||||
fn DuplicateHandle(
|
||||
hSourceProcessHandle: *mut core::ffi::c_void,
|
||||
hSourceHandle: *mut core::ffi::c_void,
|
||||
hTargetProcessHandle: *mut core::ffi::c_void,
|
||||
lpTargetHandle: *mut *mut core::ffi::c_void,
|
||||
dwDesiredAccess: u32,
|
||||
bInheritHandle: i32,
|
||||
dwOptions: u32,
|
||||
) -> i32;
|
||||
fn CreateFileW(
|
||||
lpFileName: *const u16,
|
||||
dwDesiredAccess: u32,
|
||||
dwShareMode: u32,
|
||||
lpSecurityAttributes: *mut core::ffi::c_void,
|
||||
dwCreationDisposition: u32,
|
||||
dwFlagsAndAttributes: u32,
|
||||
hTemplateFile: *mut core::ffi::c_void,
|
||||
) -> *mut core::ffi::c_void;
|
||||
}
|
||||
|
||||
// SAFETY: standard Win32 console/file calls; every return value is checked
|
||||
// before use and the duplicated handle is wrapped in an owning `File`.
|
||||
unsafe {
|
||||
let current = GetStdHandle(STD_INPUT_HANDLE);
|
||||
if current.is_null() || current == INVALID_HANDLE {
|
||||
return None;
|
||||
}
|
||||
|
||||
let process = GetCurrentProcess();
|
||||
let mut duplicate: *mut core::ffi::c_void = std::ptr::null_mut();
|
||||
if DuplicateHandle(
|
||||
process,
|
||||
current,
|
||||
process,
|
||||
&mut duplicate,
|
||||
0,
|
||||
0, // not inheritable
|
||||
DUPLICATE_SAME_ACCESS,
|
||||
) == 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
// Repoint the process's std input at NUL so stray `std::io::stdin()`
|
||||
// reads observe EOF instead of blocking on the held `StdinLock`. If NUL
|
||||
// can't be opened we still return the duplicate so the reader works;
|
||||
// we just forgo the stray-read isolation.
|
||||
let nul: Vec<u16> = "NUL\0".encode_utf16().collect();
|
||||
let nul_handle = CreateFileW(
|
||||
nul.as_ptr(),
|
||||
GENERIC_READ,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
std::ptr::null_mut(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
if nul_handle != INVALID_HANDLE && !nul_handle.is_null() {
|
||||
SetStdHandle(STD_INPUT_HANDLE, nul_handle);
|
||||
}
|
||||
|
||||
Some(std::fs::File::from_raw_handle(duplicate as _))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
edition.workspace = true
|
||||
name = "xai-agent-lifecycle"
|
||||
version = "0.1.0"
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Host-agnostic agent lifecycle hooks shared by multiple agent hosts (e.g. xai-grok-shell).
|
||||
//! Contributors receive data-only per-hook inputs at dispatch time; anything they act through is a
|
||||
//! capability injected at install time, and they never own loop control.
|
||||
|
||||
pub mod local;
|
||||
pub mod send;
|
||||
|
||||
pub use local::{
|
||||
LocalCommandContributor, LocalExtensionRegistry, LocalExtensionRegistryBuilder,
|
||||
LocalSessionLifecycleContributor, LocalTurnInputContributor, LocalTurnLifecycleContributor,
|
||||
};
|
||||
pub use send::{
|
||||
CommandAction, CommandContributor, CommandInvocation, CommandSpec, ExtensionRegistry,
|
||||
ExtensionRegistryBuilder, SessionIdleInput, SessionLifecycleContributor, TurnAbortInput,
|
||||
TurnAbortReason, TurnDoneInput, TurnErrorInput, TurnInputContext, TurnInputContributor,
|
||||
TurnInputFragment, TurnLifecycleContributor, TurnStartInput,
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod contributors;
|
||||
pub mod registry;
|
||||
|
||||
pub use contributors::{
|
||||
LocalCommandContributor, LocalSessionLifecycleContributor, LocalTurnInputContributor,
|
||||
LocalTurnLifecycleContributor,
|
||||
};
|
||||
pub use registry::{LocalExtensionRegistry, LocalExtensionRegistryBuilder};
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod command;
|
||||
pub mod session_lifecycle;
|
||||
pub mod turn_input;
|
||||
pub mod turn_lifecycle;
|
||||
|
||||
pub use command::LocalCommandContributor;
|
||||
pub use session_lifecycle::LocalSessionLifecycleContributor;
|
||||
pub use turn_input::LocalTurnInputContributor;
|
||||
pub use turn_lifecycle::LocalTurnLifecycleContributor;
|
||||
@@ -0,0 +1,27 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::send::contributors::command::{
|
||||
CommandAction, CommandContributor, CommandInvocation, CommandSpec,
|
||||
};
|
||||
|
||||
/// `?Send` twin of [`CommandContributor`] for single-threaded hosts like grok build's TUI agent, whose session state is `Rc`/`RefCell`-based and can
|
||||
/// never satisfy the `Send` bounds the send flavor bakes into its boxed hook futures.
|
||||
#[async_trait(?Send)]
|
||||
pub trait LocalCommandContributor {
|
||||
fn advertised_commands(&self) -> Vec<CommandSpec>;
|
||||
|
||||
async fn handle_command(&self, _input: &CommandInvocation<'_>)
|
||||
-> Result<CommandAction, String>;
|
||||
}
|
||||
|
||||
/// Send contributors work in single-threaded hosts as-is, so shared logic implements [`CommandContributor`] once and both hosts can register it.
|
||||
#[async_trait(?Send)]
|
||||
impl<T: CommandContributor> LocalCommandContributor for T {
|
||||
fn advertised_commands(&self) -> Vec<CommandSpec> {
|
||||
CommandContributor::advertised_commands(self)
|
||||
}
|
||||
|
||||
async fn handle_command(&self, input: &CommandInvocation<'_>) -> Result<CommandAction, String> {
|
||||
CommandContributor::handle_command(self, input).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::send::contributors::session_lifecycle::{SessionIdleInput, SessionLifecycleContributor};
|
||||
|
||||
/// `?Send` twin of [`SessionLifecycleContributor`].
|
||||
#[async_trait(?Send)]
|
||||
pub trait LocalSessionLifecycleContributor {
|
||||
/// Fired when the session settles idle (no running turn or queued work); the host owns the check.
|
||||
async fn on_session_idle(&self, _input: &SessionIdleInput) {}
|
||||
}
|
||||
|
||||
/// Send contributors are usable in single-threaded hosts as-is, so shared logic implements
|
||||
/// [`SessionLifecycleContributor`] once and both hosts can register it.
|
||||
#[async_trait(?Send)]
|
||||
impl<T: SessionLifecycleContributor> LocalSessionLifecycleContributor for T {
|
||||
async fn on_session_idle(&self, input: &SessionIdleInput) {
|
||||
SessionLifecycleContributor::on_session_idle(self, input).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::send::contributors::turn_input::{
|
||||
TurnInputContext, TurnInputContributor, TurnInputFragment,
|
||||
};
|
||||
|
||||
/// `?Send` twin of [`TurnInputContributor`] for single-threaded hosts like grok build's TUI agent, whose session state is `Rc`/`RefCell`-based
|
||||
/// and can never satisfy the `Send` bounds the send flavor bakes into its boxed hook futures.
|
||||
#[async_trait(?Send)]
|
||||
pub trait LocalTurnInputContributor {
|
||||
async fn contribute_turn_input(&self, _input: &TurnInputContext) -> Vec<TurnInputFragment> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Send contributors are usable in single-threaded hosts as-is, so shared logic implements [`TurnInputContributor`] once for both hosts.
|
||||
#[async_trait(?Send)]
|
||||
impl<T: TurnInputContributor> LocalTurnInputContributor for T {
|
||||
async fn contribute_turn_input(&self, input: &TurnInputContext) -> Vec<TurnInputFragment> {
|
||||
TurnInputContributor::contribute_turn_input(self, input).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::send::contributors::turn_lifecycle::{
|
||||
TurnAbortInput, TurnDoneInput, TurnErrorInput, TurnLifecycleContributor, TurnStartInput,
|
||||
};
|
||||
|
||||
/// `?Send` twin of [`TurnLifecycleContributor`] for single-threaded hosts like grok build's TUI
|
||||
/// agent, whose session state is `Rc`/`RefCell`-based and can never satisfy the `Send` bounds the
|
||||
/// send flavor bakes into its boxed hook futures.
|
||||
#[async_trait(?Send)]
|
||||
pub trait LocalTurnLifecycleContributor {
|
||||
async fn on_turn_start(&self, _input: &TurnStartInput) {}
|
||||
|
||||
async fn on_turn_done(&self, _input: &TurnDoneInput) {}
|
||||
|
||||
async fn on_turn_abort(&self, _input: &TurnAbortInput) {}
|
||||
|
||||
async fn on_turn_error(&self, _input: &TurnErrorInput<'_>) {}
|
||||
}
|
||||
|
||||
/// Send contributors are usable in single-threaded hosts as-is, so shared logic implements
|
||||
/// [`TurnLifecycleContributor`] once and both hosts can register it.
|
||||
#[async_trait(?Send)]
|
||||
impl<T: TurnLifecycleContributor> LocalTurnLifecycleContributor for T {
|
||||
async fn on_turn_start(&self, input: &TurnStartInput) {
|
||||
TurnLifecycleContributor::on_turn_start(self, input).await;
|
||||
}
|
||||
|
||||
async fn on_turn_done(&self, input: &TurnDoneInput) {
|
||||
TurnLifecycleContributor::on_turn_done(self, input).await;
|
||||
}
|
||||
|
||||
async fn on_turn_abort(&self, input: &TurnAbortInput) {
|
||||
TurnLifecycleContributor::on_turn_abort(self, input).await;
|
||||
}
|
||||
|
||||
async fn on_turn_error(&self, input: &TurnErrorInput<'_>) {
|
||||
TurnLifecycleContributor::on_turn_error(self, input).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::local::contributors::{
|
||||
LocalCommandContributor, LocalSessionLifecycleContributor, LocalTurnInputContributor,
|
||||
LocalTurnLifecycleContributor,
|
||||
};
|
||||
|
||||
/// Mutable registry used while hosts register typed runtime contributions.
|
||||
#[derive(Default)]
|
||||
pub struct LocalExtensionRegistryBuilder {
|
||||
turn_lifecycle_contributors: Vec<Rc<dyn LocalTurnLifecycleContributor>>,
|
||||
session_lifecycle_contributors: Vec<Rc<dyn LocalSessionLifecycleContributor>>,
|
||||
turn_input_contributors: Vec<Rc<dyn LocalTurnInputContributor>>,
|
||||
command_contributors: Vec<Rc<dyn LocalCommandContributor>>,
|
||||
}
|
||||
|
||||
impl LocalExtensionRegistryBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn turn_lifecycle_contributor(
|
||||
&mut self,
|
||||
contributor: Rc<dyn LocalTurnLifecycleContributor>,
|
||||
) {
|
||||
self.turn_lifecycle_contributors.push(contributor);
|
||||
}
|
||||
|
||||
pub fn session_lifecycle_contributor(
|
||||
&mut self,
|
||||
contributor: Rc<dyn LocalSessionLifecycleContributor>,
|
||||
) {
|
||||
self.session_lifecycle_contributors.push(contributor);
|
||||
}
|
||||
|
||||
pub fn turn_input_contributor(&mut self, contributor: Rc<dyn LocalTurnInputContributor>) {
|
||||
self.turn_input_contributors.push(contributor);
|
||||
}
|
||||
|
||||
pub fn command_contributor(&mut self, contributor: Rc<dyn LocalCommandContributor>) {
|
||||
self.command_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Routes each advertised command to its one owner. Duplicate names are a composition bug:
|
||||
/// first registration wins, panics in debug builds, logs in release.
|
||||
pub fn build(self) -> LocalExtensionRegistry {
|
||||
let mut command_handlers: HashMap<String, Rc<dyn LocalCommandContributor>> = HashMap::new();
|
||||
for contributor in &self.command_contributors {
|
||||
for spec in contributor.advertised_commands() {
|
||||
if command_handlers.contains_key(&spec.name) {
|
||||
debug_assert!(false, "duplicate command contributed: /{}", spec.name);
|
||||
tracing::error!(command = %spec.name, "Duplicate command contributed; first registration wins");
|
||||
continue;
|
||||
}
|
||||
command_handlers.insert(spec.name, contributor.clone());
|
||||
}
|
||||
}
|
||||
|
||||
LocalExtensionRegistry {
|
||||
turn_lifecycle_contributors: self.turn_lifecycle_contributors,
|
||||
session_lifecycle_contributors: self.session_lifecycle_contributors,
|
||||
turn_input_contributors: self.turn_input_contributors,
|
||||
command_contributors: self.command_contributors,
|
||||
command_handlers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable typed registry produced after extensions are installed.
|
||||
#[derive(Default)]
|
||||
pub struct LocalExtensionRegistry {
|
||||
turn_lifecycle_contributors: Vec<Rc<dyn LocalTurnLifecycleContributor>>,
|
||||
session_lifecycle_contributors: Vec<Rc<dyn LocalSessionLifecycleContributor>>,
|
||||
turn_input_contributors: Vec<Rc<dyn LocalTurnInputContributor>>,
|
||||
command_contributors: Vec<Rc<dyn LocalCommandContributor>>,
|
||||
command_handlers: HashMap<String, Rc<dyn LocalCommandContributor>>,
|
||||
}
|
||||
|
||||
impl LocalExtensionRegistry {
|
||||
pub fn turn_lifecycle_contributors(&self) -> &[Rc<dyn LocalTurnLifecycleContributor>] {
|
||||
&self.turn_lifecycle_contributors
|
||||
}
|
||||
|
||||
pub fn session_lifecycle_contributors(&self) -> &[Rc<dyn LocalSessionLifecycleContributor>] {
|
||||
&self.session_lifecycle_contributors
|
||||
}
|
||||
|
||||
pub fn turn_input_contributors(&self) -> &[Rc<dyn LocalTurnInputContributor>] {
|
||||
&self.turn_input_contributors
|
||||
}
|
||||
|
||||
pub fn command_contributors(&self) -> &[Rc<dyn LocalCommandContributor>] {
|
||||
&self.command_contributors
|
||||
}
|
||||
|
||||
/// The one contributor owning `name`, or `None` when no extension advertised it.
|
||||
pub fn command_handler(&self, name: &str) -> Option<&Rc<dyn LocalCommandContributor>> {
|
||||
self.command_handlers.get(name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
pub mod contributors;
|
||||
pub mod registry;
|
||||
|
||||
pub use contributors::{
|
||||
CommandAction, CommandContributor, CommandInvocation, CommandSpec, SessionIdleInput,
|
||||
SessionLifecycleContributor, TurnAbortInput, TurnAbortReason, TurnDoneInput, TurnErrorInput,
|
||||
TurnInputContext, TurnInputContributor, TurnInputFragment, TurnLifecycleContributor,
|
||||
TurnStartInput,
|
||||
};
|
||||
pub use registry::{ExtensionRegistry, ExtensionRegistryBuilder};
|
||||
@@ -0,0 +1,12 @@
|
||||
pub mod command;
|
||||
pub mod session_lifecycle;
|
||||
pub mod turn_input;
|
||||
pub mod turn_lifecycle;
|
||||
|
||||
pub use command::{CommandAction, CommandContributor, CommandInvocation, CommandSpec};
|
||||
pub use session_lifecycle::{SessionIdleInput, SessionLifecycleContributor};
|
||||
pub use turn_input::{TurnInputContext, TurnInputContributor, TurnInputFragment};
|
||||
pub use turn_lifecycle::{
|
||||
TurnAbortInput, TurnAbortReason, TurnDoneInput, TurnErrorInput, TurnLifecycleContributor,
|
||||
TurnStartInput,
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
/// A slash command a contributor advertises; the host maps it onto its own advertising protocol.
|
||||
pub struct CommandSpec {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub arg_hint: String,
|
||||
}
|
||||
|
||||
/// A parsed `/name args` invocation. The host owns parsing and routes it to the command's one owner.
|
||||
pub struct CommandInvocation<'a> {
|
||||
pub name: &'a str,
|
||||
pub args: &'a str, // Whitespace-trimmed; empty for a bare `/name`.
|
||||
}
|
||||
|
||||
/// What a handled command does to the turn; rejections travel as the `Err` reason.
|
||||
pub enum CommandAction {
|
||||
/// Replace the model-visible copy of the message with `model_text`.
|
||||
Rewrite { model_text: String },
|
||||
/// Side effect performed, nothing to say; the state change surfaces through the host's own rendering.
|
||||
Acted,
|
||||
}
|
||||
|
||||
/// Handles the slash commands the extension advertises. Only invoked for commands this contributor
|
||||
/// owns; the `Err` reason is the only channel for "why not", so hosts must surface it.
|
||||
#[async_trait]
|
||||
pub trait CommandContributor: Send + Sync {
|
||||
fn advertised_commands(&self) -> Vec<CommandSpec>;
|
||||
|
||||
async fn handle_command(&self, _input: &CommandInvocation<'_>)
|
||||
-> Result<CommandAction, String>;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
/// Input supplied when the host observes the session settling idle.
|
||||
pub struct SessionIdleInput;
|
||||
|
||||
#[async_trait]
|
||||
pub trait SessionLifecycleContributor: Send + Sync {
|
||||
/// Fired when the session settles idle (no running turn or queued work); the host owns the check.
|
||||
async fn on_session_idle(&self, _input: &SessionIdleInput) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
/// Turn facts supplied when the host pulls extension input at its sampling chokepoint.
|
||||
pub struct TurnInputContext {
|
||||
/// Stable host-owned turn identifier.
|
||||
pub turn_id: String,
|
||||
/// True when the harness produced the turn (auto-wake, drain, cron, continuation), not the user.
|
||||
pub synthetic: bool,
|
||||
}
|
||||
|
||||
/// A model-visible input fragment contributed into the active turn. The host owns wrapping, origin stamping, and placement.
|
||||
pub struct TurnInputFragment {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Contributes model-visible input fragments into the active turn when the host pulls at its sampling chokepoint.
|
||||
/// Fragments land in the same turn, never a new one.
|
||||
#[async_trait]
|
||||
pub trait TurnInputContributor: Send + Sync {
|
||||
async fn contribute_turn_input(&self, _input: &TurnInputContext) -> Vec<TurnInputFragment> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
/// Input supplied when the host starts a turn.
|
||||
pub struct TurnStartInput {
|
||||
/// True when the harness produced the turn (auto-wake, drain, cron, continuation), not the user.
|
||||
pub synthetic: bool,
|
||||
}
|
||||
|
||||
impl TurnStartInput {
|
||||
pub fn new(synthetic: bool) -> Self {
|
||||
TurnStartInput { synthetic }
|
||||
}
|
||||
}
|
||||
|
||||
/// Input supplied when the host completes a turn.
|
||||
pub struct TurnDoneInput;
|
||||
|
||||
/// Why the host aborted the turn instead of completing it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TurnAbortReason {
|
||||
/// The client went away mid-turn.
|
||||
Disconnected,
|
||||
/// The user interrupted the turn before it completed.
|
||||
Interrupted,
|
||||
}
|
||||
|
||||
/// Input supplied when the host aborts a turn.
|
||||
pub struct TurnAbortInput {
|
||||
pub reason: TurnAbortReason,
|
||||
}
|
||||
|
||||
impl TurnAbortInput {
|
||||
pub fn new(reason: TurnAbortReason) -> Self {
|
||||
TurnAbortInput { reason }
|
||||
}
|
||||
}
|
||||
|
||||
/// Input supplied when the host observes an error for a turn.
|
||||
pub struct TurnErrorInput<'a> {
|
||||
pub message: &'a str,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait TurnLifecycleContributor: Send + Sync {
|
||||
async fn on_turn_start(&self, _input: &TurnStartInput) {}
|
||||
|
||||
async fn on_turn_done(&self, _input: &TurnDoneInput) {}
|
||||
|
||||
async fn on_turn_abort(&self, _input: &TurnAbortInput) {}
|
||||
|
||||
async fn on_turn_error(&self, _input: &TurnErrorInput<'_>) {}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::send::contributors::{
|
||||
CommandContributor, SessionLifecycleContributor, TurnInputContributor, TurnLifecycleContributor,
|
||||
};
|
||||
|
||||
/// Mutable registry used while hosts register typed runtime contributions.
|
||||
#[derive(Default)]
|
||||
pub struct ExtensionRegistryBuilder {
|
||||
turn_lifecycle_contributors: Vec<Arc<dyn TurnLifecycleContributor>>,
|
||||
session_lifecycle_contributors: Vec<Arc<dyn SessionLifecycleContributor>>,
|
||||
turn_input_contributors: Vec<Arc<dyn TurnInputContributor>>,
|
||||
command_contributors: Vec<Arc<dyn CommandContributor>>,
|
||||
}
|
||||
|
||||
impl ExtensionRegistryBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn turn_lifecycle_contributor(&mut self, contributor: Arc<dyn TurnLifecycleContributor>) {
|
||||
self.turn_lifecycle_contributors.push(contributor);
|
||||
}
|
||||
|
||||
pub fn session_lifecycle_contributor(
|
||||
&mut self,
|
||||
contributor: Arc<dyn SessionLifecycleContributor>,
|
||||
) {
|
||||
self.session_lifecycle_contributors.push(contributor);
|
||||
}
|
||||
|
||||
pub fn turn_input_contributor(&mut self, contributor: Arc<dyn TurnInputContributor>) {
|
||||
self.turn_input_contributors.push(contributor);
|
||||
}
|
||||
|
||||
pub fn command_contributor(&mut self, contributor: Arc<dyn CommandContributor>) {
|
||||
self.command_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Routes each advertised command to its one owner. Duplicate names are a composition bug:
|
||||
/// first registration wins, panics in debug builds, logs in release.
|
||||
pub fn build(self) -> ExtensionRegistry {
|
||||
let mut command_handlers: HashMap<String, Arc<dyn CommandContributor>> = HashMap::new();
|
||||
for contributor in &self.command_contributors {
|
||||
for spec in contributor.advertised_commands() {
|
||||
if command_handlers.contains_key(&spec.name) {
|
||||
debug_assert!(false, "duplicate command contributed: /{}", spec.name);
|
||||
tracing::error!(command = %spec.name, "Duplicate command contributed; first registration wins");
|
||||
continue;
|
||||
}
|
||||
command_handlers.insert(spec.name, contributor.clone());
|
||||
}
|
||||
}
|
||||
|
||||
ExtensionRegistry {
|
||||
turn_lifecycle_contributors: self.turn_lifecycle_contributors,
|
||||
session_lifecycle_contributors: self.session_lifecycle_contributors,
|
||||
turn_input_contributors: self.turn_input_contributors,
|
||||
command_contributors: self.command_contributors,
|
||||
command_handlers,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable typed registry produced after extensions are installed.
|
||||
#[derive(Default)]
|
||||
pub struct ExtensionRegistry {
|
||||
turn_lifecycle_contributors: Vec<Arc<dyn TurnLifecycleContributor>>,
|
||||
session_lifecycle_contributors: Vec<Arc<dyn SessionLifecycleContributor>>,
|
||||
turn_input_contributors: Vec<Arc<dyn TurnInputContributor>>,
|
||||
command_contributors: Vec<Arc<dyn CommandContributor>>,
|
||||
command_handlers: HashMap<String, Arc<dyn CommandContributor>>,
|
||||
}
|
||||
|
||||
impl ExtensionRegistry {
|
||||
pub fn turn_lifecycle_contributors(&self) -> &[Arc<dyn TurnLifecycleContributor>] {
|
||||
&self.turn_lifecycle_contributors
|
||||
}
|
||||
|
||||
pub fn session_lifecycle_contributors(&self) -> &[Arc<dyn SessionLifecycleContributor>] {
|
||||
&self.session_lifecycle_contributors
|
||||
}
|
||||
|
||||
pub fn turn_input_contributors(&self) -> &[Arc<dyn TurnInputContributor>] {
|
||||
&self.turn_input_contributors
|
||||
}
|
||||
|
||||
pub fn command_contributors(&self) -> &[Arc<dyn CommandContributor>] {
|
||||
&self.command_contributors
|
||||
}
|
||||
|
||||
/// The one contributor owning `name`, or `None` when no extension advertised it.
|
||||
pub fn command_handler(&self, name: &str) -> Option<&Arc<dyn CommandContributor>> {
|
||||
self.command_handlers.get(name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::*;
|
||||
use crate::send::contributors::{
|
||||
CommandAction, CommandInvocation, CommandSpec, SessionIdleInput, TurnAbortInput,
|
||||
TurnAbortReason, TurnDoneInput, TurnErrorInput, TurnInputContext, TurnInputFragment,
|
||||
TurnStartInput,
|
||||
};
|
||||
|
||||
struct Counter(AtomicUsize);
|
||||
|
||||
#[async_trait]
|
||||
impl TurnLifecycleContributor for Counter {
|
||||
async fn on_turn_done(&self, _input: &TurnDoneInput) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SessionLifecycleContributor for Counter {
|
||||
async fn on_session_idle(&self, _input: &SessionIdleInput) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TurnInputContributor for Counter {
|
||||
async fn contribute_turn_input(&self, _input: &TurnInputContext) -> Vec<TurnInputFragment> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
vec![TurnInputFragment {
|
||||
text: "nudge".to_string(),
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CommandContributor for Counter {
|
||||
fn advertised_commands(&self) -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
name: "goal".to_string(),
|
||||
description: "Set a goal".to_string(),
|
||||
arg_hint: "<text>".to_string(),
|
||||
}]
|
||||
}
|
||||
|
||||
async fn handle_command(
|
||||
&self,
|
||||
input: &CommandInvocation<'_>,
|
||||
) -> Result<CommandAction, String> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(CommandAction::Rewrite {
|
||||
model_text: format!("{} {}", input.name, input.args),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "duplicate command contributed: /goal")]
|
||||
fn build_rejects_duplicate_command_names() {
|
||||
let counter = Arc::new(Counter(AtomicUsize::new(0)));
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
builder.command_contributor(counter.clone());
|
||||
builder.command_contributor(counter);
|
||||
builder.build();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn builder_freezes_and_registry_dispatches_in_order() {
|
||||
let counter = Arc::new(Counter(AtomicUsize::new(0)));
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
builder.turn_lifecycle_contributor(counter.clone());
|
||||
builder.turn_lifecycle_contributor(counter.clone());
|
||||
builder.session_lifecycle_contributor(counter.clone());
|
||||
builder.turn_input_contributor(counter.clone());
|
||||
builder.command_contributor(counter.clone());
|
||||
let registry = builder.build();
|
||||
|
||||
for contributor in registry.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_start(&TurnStartInput { synthetic: false })
|
||||
.await;
|
||||
contributor.on_turn_done(&TurnDoneInput).await;
|
||||
contributor
|
||||
.on_turn_abort(&TurnAbortInput {
|
||||
reason: TurnAbortReason::Interrupted,
|
||||
})
|
||||
.await;
|
||||
contributor
|
||||
.on_turn_error(&TurnErrorInput { message: "boom" })
|
||||
.await;
|
||||
}
|
||||
|
||||
for contributor in registry.session_lifecycle_contributors() {
|
||||
contributor.on_session_idle(&SessionIdleInput).await;
|
||||
}
|
||||
|
||||
for contributor in registry.turn_input_contributors() {
|
||||
let fragments = contributor
|
||||
.contribute_turn_input(&TurnInputContext {
|
||||
turn_id: "turn-1".to_string(),
|
||||
synthetic: false,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(1, fragments.len());
|
||||
assert_eq!("nudge", fragments[0].text);
|
||||
}
|
||||
|
||||
assert!(registry.command_handler("nope").is_none());
|
||||
let handler = registry.command_handler("goal").expect("goal has an owner");
|
||||
let action = handler
|
||||
.handle_command(&CommandInvocation {
|
||||
name: "goal",
|
||||
args: "ship it",
|
||||
})
|
||||
.await
|
||||
.expect("command should be handled");
|
||||
let CommandAction::Rewrite { model_text } = action else {
|
||||
panic!("expected a rewrite");
|
||||
};
|
||||
assert_eq!("goal ship it", model_text);
|
||||
|
||||
assert_eq!(5, counter.0.load(Ordering::SeqCst));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
name = "xai-chat-state"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
description = "Actor-based chat state management for xAI agents"
|
||||
|
||||
[features]
|
||||
default-bazel = []
|
||||
|
||||
[dependencies]
|
||||
indexmap = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
strum = { workspace = true }
|
||||
tokio = { workspace = true, features = ["sync", "rt", "macros"] }
|
||||
tokio-util = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
xai-grok-compaction = { path = "../../common/xai-grok-compaction" }
|
||||
xai-grok-sampling-types = { path = "../xai-grok-sampling-types" }
|
||||
xai-token-estimation = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,394 @@
|
||||
//! ChatStateActor — runs in a dedicated tokio task and owns all chat state.
|
||||
//!
|
||||
//! This module is organized into submodules by responsibility:
|
||||
//! - `state`: Internal state types (ChatState)
|
||||
//! - `mutations`: State mutation handlers (push_user_message, replace_conversation, etc.)
|
||||
//! - `queries`: Read-only query handlers (get_conversation, snapshot, etc.)
|
||||
|
||||
mod mutations;
|
||||
mod queries;
|
||||
pub(crate) mod request_builder;
|
||||
pub mod state;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::debug;
|
||||
|
||||
use crate::commands::ChatStateCommand;
|
||||
use crate::events::ChatStateEvent;
|
||||
use crate::handle::ChatStateHandle;
|
||||
use crate::persistence::ChatPersistence;
|
||||
use crate::types::{PruningConfig, TurnCapture};
|
||||
|
||||
use state::ChatState;
|
||||
use xai_grok_sampling_types::{ConversationItem, SamplingConfig};
|
||||
|
||||
/// The actor that owns all chat state.
|
||||
/// Runs in a dedicated tokio task and processes commands sequentially.
|
||||
pub struct ChatStateActor {
|
||||
/// Internal state — conversation, tokens, config, etc.
|
||||
state: ChatState,
|
||||
/// Pruning configuration for tool-result trimming.
|
||||
pruning_config: PruningConfig,
|
||||
/// Persistence implementation — owned exclusively, called with `&mut self`.
|
||||
persistence: Box<dyn ChatPersistence>,
|
||||
/// Channel to receive commands from handles.
|
||||
cmd_rx: mpsc::UnboundedReceiver<ChatStateCommand>,
|
||||
/// Channel to send events to the session main loop.
|
||||
event_tx: mpsc::UnboundedSender<ChatStateEvent>,
|
||||
/// Cancellation token for graceful shutdown.
|
||||
cancellation_token: tokio_util::sync::CancellationToken,
|
||||
}
|
||||
|
||||
impl ChatStateActor {
|
||||
/// Send an event to subscribers, logging if the channel is closed.
|
||||
fn send_event(&self, event: ChatStateEvent) {
|
||||
if self.event_tx.send(event).is_err() {
|
||||
debug!("ChatState event channel closed, event dropped");
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn the actor and return a handle to communicate with it.
|
||||
pub fn spawn(
|
||||
initial_conversation: Vec<ConversationItem>,
|
||||
sampling_config: SamplingConfig,
|
||||
persistence: Box<dyn ChatPersistence>,
|
||||
event_tx: mpsc::UnboundedSender<ChatStateEvent>,
|
||||
cancellation_token: tokio_util::sync::CancellationToken,
|
||||
) -> ChatStateHandle {
|
||||
Self::spawn_with_pruning(
|
||||
initial_conversation,
|
||||
sampling_config,
|
||||
PruningConfig::default(),
|
||||
persistence,
|
||||
event_tx,
|
||||
cancellation_token,
|
||||
)
|
||||
}
|
||||
|
||||
/// Spawn the actor with a custom pruning config.
|
||||
pub fn spawn_with_pruning(
|
||||
initial_conversation: Vec<ConversationItem>,
|
||||
sampling_config: SamplingConfig,
|
||||
pruning_config: PruningConfig,
|
||||
persistence: Box<dyn ChatPersistence>,
|
||||
event_tx: mpsc::UnboundedSender<ChatStateEvent>,
|
||||
cancellation_token: tokio_util::sync::CancellationToken,
|
||||
) -> ChatStateHandle {
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
|
||||
let actor = ChatStateActor {
|
||||
state: ChatState::new(initial_conversation, sampling_config),
|
||||
pruning_config,
|
||||
persistence,
|
||||
cmd_rx,
|
||||
event_tx,
|
||||
cancellation_token,
|
||||
};
|
||||
|
||||
tokio::spawn(actor.run());
|
||||
|
||||
ChatStateHandle::new(cmd_tx)
|
||||
}
|
||||
|
||||
/// Main actor loop — processes commands until shutdown or cancellation.
|
||||
async fn run(mut self) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation_token.cancelled() => {
|
||||
debug!("ChatStateActor shutting down via cancellation");
|
||||
break;
|
||||
}
|
||||
cmd = self.cmd_rx.recv() => {
|
||||
let Some(cmd) = cmd else {
|
||||
debug!("ChatStateActor shutting down: all handles dropped");
|
||||
break;
|
||||
};
|
||||
self.handle_command(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch a command to the appropriate mutation or query handler.
|
||||
fn handle_command(&mut self, cmd: ChatStateCommand) {
|
||||
match cmd {
|
||||
// ═══ Mutations ═══
|
||||
ChatStateCommand::PushUserMessage { item } => {
|
||||
self.push_user_message(item);
|
||||
}
|
||||
ChatStateCommand::PushUserMessageAndAck { item, reply } => {
|
||||
self.push_user_message(item);
|
||||
let _ = reply.send(());
|
||||
}
|
||||
ChatStateCommand::PushUserMessageWithRepairReason { item, reason } => {
|
||||
self.push_user_message_with_repair_reason(item, reason);
|
||||
}
|
||||
ChatStateCommand::PushAssistantResponse { item } => {
|
||||
self.push_message(item);
|
||||
}
|
||||
ChatStateCommand::PushToolResult { item } => {
|
||||
self.push_message(item);
|
||||
}
|
||||
ChatStateCommand::RecordTokenUsage { total_tokens } => {
|
||||
self.record_token_usage(total_tokens);
|
||||
}
|
||||
ChatStateCommand::RecordLastTurnUsage { usage } => {
|
||||
self.record_last_turn_usage(usage);
|
||||
}
|
||||
ChatStateCommand::RecordModelCallUsage {
|
||||
model_id,
|
||||
usage,
|
||||
api_duration_ms,
|
||||
cost_usd_ticks,
|
||||
} => {
|
||||
self.record_model_call_usage(model_id, &usage, api_duration_ms, cost_usd_ticks);
|
||||
}
|
||||
ChatStateCommand::RecordSubagentUsage {
|
||||
by_model,
|
||||
attribute_to_prompt,
|
||||
incomplete,
|
||||
reply,
|
||||
} => {
|
||||
self.record_subagent_usage(&by_model, attribute_to_prompt, incomplete);
|
||||
let _ = reply.send(());
|
||||
}
|
||||
ChatStateCommand::MarkUsageIncomplete {
|
||||
prompt,
|
||||
session,
|
||||
reply,
|
||||
} => {
|
||||
self.mark_usage_incomplete(prompt, session);
|
||||
let _ = reply.send(());
|
||||
}
|
||||
ChatStateCommand::IncrementPromptIndex => {
|
||||
self.increment_prompt_index();
|
||||
}
|
||||
ChatStateCommand::UpdateSamplingConfig { config } => {
|
||||
self.state.sampling_config = config;
|
||||
}
|
||||
ChatStateCommand::RecordAgentEditedPath { path } => {
|
||||
self.state.agent_edited_paths.insert(path);
|
||||
}
|
||||
ChatStateCommand::RecordStreamStart { timestamp_ms } => {
|
||||
self.state.stream_start_ms = Some(timestamp_ms);
|
||||
}
|
||||
ChatStateCommand::RecordTurnStart { timestamp_ms } => {
|
||||
self.state.turn_start_ms = Some(timestamp_ms);
|
||||
}
|
||||
ChatStateCommand::ReplaceConversation {
|
||||
items,
|
||||
is_compaction,
|
||||
} => {
|
||||
self.replace_conversation(items, is_compaction);
|
||||
}
|
||||
ChatStateCommand::RepairHistory {
|
||||
dry_run,
|
||||
turn_active,
|
||||
reply,
|
||||
} => {
|
||||
// Checked here so refusal and mutation are serialized; a
|
||||
// `false` at processing time means pre-turn state (see the
|
||||
// command's doc).
|
||||
let blocked = turn_active
|
||||
.as_ref()
|
||||
.map(|f| f.load(std::sync::atomic::Ordering::SeqCst))
|
||||
.unwrap_or(false);
|
||||
let result = if blocked {
|
||||
Err(crate::commands::RepairHistoryBlocked)
|
||||
} else {
|
||||
Ok(self.repair_history(dry_run))
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
ChatStateCommand::ReplaceSystemHead { prompt, reply } => {
|
||||
let changed = self.replace_system_head(&prompt);
|
||||
let _ = reply.send(changed);
|
||||
}
|
||||
ChatStateCommand::CachePromptText { text } => {
|
||||
self.state.prompt_texts.push(text);
|
||||
}
|
||||
ChatStateCommand::RecordCompactionAt { prompt_index } => {
|
||||
self.state.last_compaction_prompt_index = Some(prompt_index);
|
||||
}
|
||||
ChatStateCommand::Flush => {
|
||||
self.persistence.flush();
|
||||
}
|
||||
ChatStateCommand::UpdateCredentials { credentials } => {
|
||||
self.state.credentials = credentials;
|
||||
}
|
||||
ChatStateCommand::RestoreSnapshot(snapshot) => {
|
||||
self.restore_snapshot(*snapshot);
|
||||
}
|
||||
ChatStateCommand::BeginTurnCapture => {
|
||||
self.state.turn_capture = Some(state::TurnCaptureState {
|
||||
turn_start_offset: self.state.conversation.len(),
|
||||
pre_replacement_messages: Vec::new(),
|
||||
compaction_occurred: false,
|
||||
});
|
||||
}
|
||||
ChatStateCommand::AppendHarnessTraceItems { items } => {
|
||||
self.state.harness_trace_buffer.extend(items);
|
||||
}
|
||||
ChatStateCommand::FlushHarnessTraceTurn => {
|
||||
self.state.seal_harness_trace_turn();
|
||||
}
|
||||
ChatStateCommand::RepairDanglingAfterHarnessHalt { class } => {
|
||||
self.repair_dangling_after_harness_halt(class);
|
||||
}
|
||||
|
||||
// ═══ Queries ═══
|
||||
//
|
||||
// Read queries are pure reads — repair only at write boundaries:
|
||||
// `ChatState::new()` (startup) and `push_user_message()` (new turn).
|
||||
// `BuildConversationRequest` retains the guard because it is only
|
||||
// ever issued by the agent loop between turns, never by background tasks.
|
||||
ChatStateCommand::BuildConversationRequest {
|
||||
tool_definitions,
|
||||
memory_reminder,
|
||||
persist_memory_reminder,
|
||||
trace,
|
||||
conv_id,
|
||||
req_id,
|
||||
reply,
|
||||
} => {
|
||||
self.ensure_conversation_integrity();
|
||||
let request = self.build_conversation_request(
|
||||
tool_definitions,
|
||||
memory_reminder,
|
||||
persist_memory_reminder,
|
||||
trace,
|
||||
conv_id,
|
||||
req_id,
|
||||
);
|
||||
let _ = reply.send(request);
|
||||
}
|
||||
ChatStateCommand::GetConversation { reply } => {
|
||||
tracing::debug!(
|
||||
conversation_len = self.state.conversation.len(),
|
||||
"ChatState: cloning full conversation for GetConversation"
|
||||
);
|
||||
let _ = reply.send(self.state.conversation.clone());
|
||||
}
|
||||
ChatStateCommand::GetPromptIndex { reply } => {
|
||||
let _ = reply.send(self.state.prompt_index);
|
||||
}
|
||||
ChatStateCommand::GetLastCompactionPromptIndex { reply } => {
|
||||
let _ = reply.send(self.state.last_compaction_prompt_index);
|
||||
}
|
||||
ChatStateCommand::GetTotalTokens { reply } => {
|
||||
let _ = reply.send(self.state.total_tokens);
|
||||
}
|
||||
ChatStateCommand::GetLastTurnUsage { reply } => {
|
||||
let _ = reply.send(self.state.last_turn_usage.clone());
|
||||
}
|
||||
ChatStateCommand::GetPromptUsage { reply } => {
|
||||
let _ = reply.send(self.state.prompt_usage.clone());
|
||||
}
|
||||
ChatStateCommand::GetSessionUsage { reply } => {
|
||||
let _ = reply.send(self.state.session_usage.clone());
|
||||
}
|
||||
ChatStateCommand::GetEstimatedTotalTokens { reply } => {
|
||||
let _ =
|
||||
reply.send(self.state.total_tokens + self.state.estimated_tokens_since_model);
|
||||
}
|
||||
ChatStateCommand::GetSamplingConfig { reply } => {
|
||||
let _ = reply.send(self.state.sampling_config.clone());
|
||||
}
|
||||
ChatStateCommand::GetAgentEditedPaths { reply } => {
|
||||
let _ = reply.send(self.state.agent_edited_paths.clone());
|
||||
}
|
||||
ChatStateCommand::GetNotificationMeta { reply } => {
|
||||
let _ = reply.send(self.get_notification_meta());
|
||||
}
|
||||
ChatStateCommand::Snapshot { reply } => {
|
||||
tracing::debug!(
|
||||
conversation_len = self.state.conversation.len(),
|
||||
"ChatState: cloning full state for Snapshot"
|
||||
);
|
||||
let _ = reply.send(self.snapshot());
|
||||
}
|
||||
ChatStateCommand::TruncateToPromptIndex {
|
||||
target_prompt_index,
|
||||
reply,
|
||||
} => {
|
||||
self.truncate_to_prompt_index(target_prompt_index);
|
||||
self.state.turn_capture = None;
|
||||
self.state.prompt_usage = None;
|
||||
// `harness_trace_buffer` / `harness_trace_turns` intentionally
|
||||
// survive a rewind: the goal planner / verifier subagents
|
||||
// genuinely ran, so their sealed trace turns stay uploadable as
|
||||
// siblings even when the live turn that triggered them is undone.
|
||||
let _ = reply.send(());
|
||||
}
|
||||
ChatStateCommand::CheckAutoCompactNeeded {
|
||||
threshold_percent,
|
||||
reply,
|
||||
} => {
|
||||
let _ = reply.send(self.check_auto_compact_needed(threshold_percent));
|
||||
}
|
||||
ChatStateCommand::GetCredentials { reply } => {
|
||||
let _ = reply.send(self.state.credentials.clone());
|
||||
}
|
||||
ChatStateCommand::GetLastModelMetadata { reply } => {
|
||||
let _ = reply.send(self.get_last_model_metadata());
|
||||
}
|
||||
ChatStateCommand::TakeTurnMessages { reply } => {
|
||||
let result = self.state.turn_capture.take().map(|cap| {
|
||||
let mut messages = cap.pre_replacement_messages;
|
||||
messages.extend(
|
||||
Self::turn_tail(&self.state.conversation, cap.turn_start_offset)
|
||||
.iter()
|
||||
.cloned(),
|
||||
);
|
||||
TurnCapture {
|
||||
messages,
|
||||
compaction_occurred: cap.compaction_occurred,
|
||||
}
|
||||
});
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
ChatStateCommand::TakeHarnessTraceTurns { reply } => {
|
||||
// Defensive seal: a phase that recorded items but never flushed
|
||||
// still rides its own turn rather than stranding.
|
||||
self.state.seal_harness_trace_turn();
|
||||
let _ = reply.send(std::mem::take(&mut self.state.harness_trace_turns));
|
||||
}
|
||||
|
||||
// ─── Narrow targeted queries ──────────────────────────────────
|
||||
ChatStateCommand::GetConversationLen { reply } => {
|
||||
let _ = reply.send(self.get_conversation_len());
|
||||
}
|
||||
ChatStateCommand::HasDanglingToolCalls { reply } => {
|
||||
let _ = reply.send(self.has_dangling_tool_calls());
|
||||
}
|
||||
ChatStateCommand::GetLastAssistantText { reply } => {
|
||||
let _ = reply.send(self.get_last_assistant_text());
|
||||
}
|
||||
ChatStateCommand::GetLastAssistantTextInTurn { reply } => {
|
||||
let _ = reply.send(self.get_last_assistant_text_in_turn());
|
||||
}
|
||||
ChatStateCommand::GetFirstUserText { reply } => {
|
||||
let _ = reply.send(self.get_first_user_text());
|
||||
}
|
||||
ChatStateCommand::GetConversationItemAt { index, reply } => {
|
||||
let _ = reply.send(self.get_conversation_item_at(index));
|
||||
}
|
||||
ChatStateCommand::GetLastUserQueryText { reply } => {
|
||||
let _ = reply.send(self.get_last_user_query_text());
|
||||
}
|
||||
ChatStateCommand::GetConversationCounts { reply } => {
|
||||
let _ = reply.send(self.get_conversation_counts());
|
||||
}
|
||||
ChatStateCommand::GetSystemMessage { reply } => {
|
||||
let _ = reply.send(self.get_system_message());
|
||||
}
|
||||
ChatStateCommand::GetEstimatedMessagesTokens { reply } => {
|
||||
let _ = reply.send(state::estimate_messages_tokens(&self.state.conversation));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
//! Mutation handlers for the ChatStateActor.
|
||||
|
||||
use xai_grok_sampling_types::{
|
||||
ContentPart, ConversationItem, DanglingToolCallReason, dedup_duplicate_tool_results,
|
||||
repair_dangling_tool_calls,
|
||||
};
|
||||
|
||||
use super::ChatStateActor;
|
||||
use super::request_builder::HARD_CLEAR_PLACEHOLDER;
|
||||
use crate::events::ChatStateEvent;
|
||||
use crate::types::ChatStateSnapshot;
|
||||
|
||||
/// Static string label for tracing on `ConversationItem` (avoids pulling
|
||||
/// the `Role` enum into the format string).
|
||||
fn item_kind_str(item: &ConversationItem) -> &'static str {
|
||||
match item {
|
||||
ConversationItem::System(_) => "system",
|
||||
ConversationItem::User(_) => "user",
|
||||
ConversationItem::Assistant(_) => "assistant",
|
||||
ConversationItem::ToolResult(_) => "tool_result",
|
||||
ConversationItem::BackendToolCall(_) => "backend_tool_call",
|
||||
ConversationItem::Reasoning(_) => "reasoning",
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatStateActor {
|
||||
/// Repair any dangling tool calls in the conversation and persist the fix.
|
||||
///
|
||||
/// A "dangling" tool call is an assistant message with tool call IDs that
|
||||
/// lack matching `ToolResult` entries. This can happen when:
|
||||
/// - The user cancels (Ctrl+C) mid-tool-execution in a live session
|
||||
/// - The process crashes between pushing the assistant and tool results
|
||||
/// - The tokio task is aborted at an `.await` point
|
||||
///
|
||||
/// This method repairs the state in-place and persists the fix to disk.
|
||||
/// It is idempotent — calling it on a clean conversation is a cheap no-op
|
||||
/// (single forward scan, no allocations).
|
||||
///
|
||||
/// Only call at write boundaries where the previous turn is definitively
|
||||
/// over (`ChatState::new()`, `push_user_message()`, `BuildConversationRequest`).
|
||||
/// Do NOT call from read handlers — background tasks run concurrently with
|
||||
/// tool execution and would misidentify in-flight calls as dangling.
|
||||
pub(super) fn ensure_conversation_integrity(&mut self) {
|
||||
self.ensure_conversation_integrity_with_reason(DanglingToolCallReason::UserCancelled);
|
||||
}
|
||||
|
||||
/// Like [`Self::ensure_conversation_integrity`] but takes an explicit reason.
|
||||
pub(super) fn ensure_conversation_integrity_with_reason(
|
||||
&mut self,
|
||||
reason: DanglingToolCallReason,
|
||||
) {
|
||||
// In-place integrity repair can add/remove items ahead of an active capture's
|
||||
// boundary, so snapshot + rebase the offset like the replace/restore paths.
|
||||
self.snapshot_turn_slice();
|
||||
let deduped = dedup_duplicate_tool_results(&mut self.state.conversation);
|
||||
if deduped > 0 {
|
||||
tracing::info!(
|
||||
deduped_count = deduped,
|
||||
"Removed duplicate tool results in conversation"
|
||||
);
|
||||
}
|
||||
let repaired = repair_dangling_tool_calls(&mut self.state.conversation, reason);
|
||||
if repaired > 0 || deduped > 0 {
|
||||
tracing::info!(
|
||||
repaired_count = repaired,
|
||||
"Repaired dangling tool calls in conversation"
|
||||
);
|
||||
self.persistence.replace_history(&self.state.conversation);
|
||||
}
|
||||
self.rebase_turn_capture_offset();
|
||||
}
|
||||
|
||||
/// Repair dangling tool calls after a harness-initiated halt.
|
||||
pub(super) fn repair_dangling_after_harness_halt(&mut self, class: &'static str) {
|
||||
self.ensure_conversation_integrity_with_reason(DanglingToolCallReason::HarnessHalted {
|
||||
class,
|
||||
});
|
||||
}
|
||||
|
||||
/// Out-of-band history repair (`x.ai/session/repair`): run
|
||||
/// [`crate::compaction_utils::repair_history`] and persist changes via
|
||||
/// [`Self::replace_conversation`]. Unlike
|
||||
/// [`Self::ensure_conversation_integrity`], this also removes orphaned
|
||||
/// `ToolResult`s — the shape that bricks a session with provider 400s.
|
||||
/// `dry_run` only reports.
|
||||
pub(super) fn repair_history(
|
||||
&mut self,
|
||||
dry_run: bool,
|
||||
) -> crate::compaction_utils::HistoryRepairReport {
|
||||
if dry_run {
|
||||
let mut copy = self.state.conversation.clone();
|
||||
return crate::compaction_utils::repair_history(&mut copy);
|
||||
}
|
||||
let mut items = std::mem::take(&mut self.state.conversation);
|
||||
let report = crate::compaction_utils::repair_history(&mut items);
|
||||
if report.changed() {
|
||||
tracing::warn!(
|
||||
duplicates_removed = report.duplicates_removed,
|
||||
stripped_tool_result_ids = ?report.stripped_tool_result_ids,
|
||||
synthetic_results_inserted = report.synthetic_results_inserted,
|
||||
"History repair modified the conversation"
|
||||
);
|
||||
// Full replace: persists atomically and re-bases token estimates.
|
||||
self.replace_conversation(items, false);
|
||||
} else {
|
||||
// Nothing changed — put the conversation back untouched.
|
||||
self.state.conversation = items;
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Push any conversation item (user, assistant, or tool result) and persist it.
|
||||
pub(super) fn push_message(&mut self, item: ConversationItem) {
|
||||
let count_in_delta = !matches!(item, ConversationItem::Assistant(_));
|
||||
if count_in_delta {
|
||||
let estimated_tokens = super::state::estimate_item_tokens(&item);
|
||||
self.state.estimated_tokens_since_model += estimated_tokens;
|
||||
tracing::debug!(
|
||||
item_kind = item_kind_str(&item),
|
||||
estimated_tokens_delta = estimated_tokens,
|
||||
estimated_total = self.state.total_tokens + self.state.estimated_tokens_since_model,
|
||||
model_reported_total = self.state.total_tokens,
|
||||
"ChatState: push_message updated estimated_tokens_since_model"
|
||||
);
|
||||
}
|
||||
self.persistence.persist_message(&item);
|
||||
self.state.conversation.push(item);
|
||||
}
|
||||
|
||||
/// Push a user message, ensuring conversation integrity first.
|
||||
///
|
||||
/// When the user cancels a turn while the model was executing parallel
|
||||
/// tool calls, the conversation may have dangling tool call IDs. This
|
||||
/// method repairs them before appending the new message so the on-disk
|
||||
/// and in-memory state stay consistent.
|
||||
///
|
||||
/// Also runs [`prune_retained_conversation`] to eagerly hard-clear very
|
||||
/// old tool results from the in-memory state, bounding long-session
|
||||
/// retained memory without waiting for the context-window threshold.
|
||||
pub(super) fn push_user_message(&mut self, item: ConversationItem) {
|
||||
self.push_user_message_with_repair_reason(item, DanglingToolCallReason::UserCancelled);
|
||||
}
|
||||
|
||||
/// Like [`Self::push_user_message`] but takes an explicit repair reason.
|
||||
pub(super) fn push_user_message_with_repair_reason(
|
||||
&mut self,
|
||||
item: ConversationItem,
|
||||
reason: DanglingToolCallReason,
|
||||
) {
|
||||
self.ensure_conversation_integrity_with_reason(reason);
|
||||
let estimated_tokens = super::state::estimate_item_tokens(&item);
|
||||
self.state.estimated_tokens_since_model += estimated_tokens;
|
||||
tracing::debug!(
|
||||
item_kind = item_kind_str(&item),
|
||||
estimated_tokens_delta = estimated_tokens,
|
||||
estimated_total = self.state.total_tokens + self.state.estimated_tokens_since_model,
|
||||
model_reported_total = self.state.total_tokens,
|
||||
"ChatState: push_user_message updated estimated_tokens_since_model"
|
||||
);
|
||||
self.persistence.persist_message(&item);
|
||||
self.state.conversation.push(item);
|
||||
self.prune_retained_conversation();
|
||||
}
|
||||
|
||||
/// Eagerly hard-clear tool results from very old turns in the retained
|
||||
/// in-memory conversation, freeing the actual string bytes.
|
||||
///
|
||||
/// Unlike the API-copy pruning in `build_conversation_request` (which runs
|
||||
/// on a *clone* only when context > 50% full), this operates on
|
||||
/// `self.state.conversation` directly and runs after every user turn.
|
||||
///
|
||||
/// # What this does
|
||||
///
|
||||
/// Only **hard-clears** are applied (no soft-trim). Soft-trimming is a
|
||||
/// context-management operation that changes what the model sees;
|
||||
/// hard-clearing is a memory-management operation that replaces content
|
||||
/// that is so old the model should not need it again. The threshold is
|
||||
/// controlled by `PruningConfig::hard_clear_age_turns`.
|
||||
///
|
||||
/// # Retained-memory measurement
|
||||
///
|
||||
/// When any clearing occurs, a `tracing::debug!` event reports:
|
||||
/// - `hard_cleared` — number of tool results cleared
|
||||
/// - `bytes_freed` — approximate bytes recovered (sum of content lengths)
|
||||
/// - `conversation_len` — total item count after the pass
|
||||
///
|
||||
/// # Synthetic User items and turn-age accuracy
|
||||
///
|
||||
/// The shell can inject synthetic `User` items mid-turn (e.g. system
|
||||
/// corrective warnings) without calling `increment_prompt_index`. These
|
||||
/// do not represent real user turns. The backward scan here counts every
|
||||
/// `User` item as a turn boundary, so synthetic items would normally cause
|
||||
/// old tool results to appear older than they really are.
|
||||
///
|
||||
/// This is compensated by raising the effective clearing threshold by the
|
||||
/// number of synthetic User items (`total_user_items - prompt_index`).
|
||||
/// The result: a tool result is never cleared before `hard_clear_age_turns`
|
||||
/// REAL turns have elapsed, even in sessions with many synthetic messages.
|
||||
///
|
||||
/// # Replay / rewind correctness
|
||||
///
|
||||
/// `updates.jsonl` is **never touched**, so cross-compaction
|
||||
/// `replay_to_prompt` is unaffected. The pruned `chat_history.jsonl`
|
||||
/// on disk mirrors the in-memory state — both lose old bulk content but
|
||||
/// `updates.jsonl` retains the original data for replay.
|
||||
pub(super) fn prune_retained_conversation(&mut self) -> usize {
|
||||
if !self.pruning_config.enabled {
|
||||
return 0;
|
||||
}
|
||||
// Fast exit: not enough turns have elapsed for any hard-clear to apply.
|
||||
if self.state.prompt_index < self.pruning_config.hard_clear_age_turns {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Compute how many synthetic User items exist (system reminders, etc.).
|
||||
// Synthetic User items are NOT real user turns — they are injected by the
|
||||
// shell mid-turn and do not increment `prompt_index`. The naive backward
|
||||
// scan counts every User item as a turn boundary, so synthetic items make
|
||||
// old tool results appear older than they really are and can cause
|
||||
// premature hard-clears.
|
||||
//
|
||||
// Fix: raise the effective clearing threshold by the number of synthetic
|
||||
// User items. This guarantees a tool result is never cleared before
|
||||
// `hard_clear_age_turns` REAL turns have elapsed, regardless of how many
|
||||
// synthetic messages the session contains.
|
||||
let total_user_items = self
|
||||
.state
|
||||
.conversation
|
||||
.iter()
|
||||
.filter(|i| matches!(i, ConversationItem::User(_)))
|
||||
.count();
|
||||
let synthetic_count = total_user_items.saturating_sub(self.state.prompt_index);
|
||||
let effective_threshold = self
|
||||
.pruning_config
|
||||
.hard_clear_age_turns
|
||||
.saturating_add(synthetic_count);
|
||||
|
||||
let before_bytes = self.conversation_content_bytes();
|
||||
let mut cleared = 0usize;
|
||||
let mut turn_from_end: usize = 0;
|
||||
let mut seen_first_user = false;
|
||||
|
||||
for i in (0..self.state.conversation.len()).rev() {
|
||||
if matches!(&self.state.conversation[i], ConversationItem::User(_)) {
|
||||
if seen_first_user {
|
||||
turn_from_end += 1;
|
||||
}
|
||||
seen_first_user = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let ConversationItem::ToolResult(tr) = &mut self.state.conversation[i] else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if turn_from_end < effective_threshold {
|
||||
continue;
|
||||
}
|
||||
|
||||
if tr.content.as_ref() != HARD_CLEAR_PLACEHOLDER {
|
||||
tr.content = std::sync::Arc::<str>::from(HARD_CLEAR_PLACEHOLDER);
|
||||
cleared += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if cleared > 0 {
|
||||
let after_bytes = self.conversation_content_bytes();
|
||||
tracing::debug!(
|
||||
hard_cleared = cleared,
|
||||
bytes_freed = before_bytes.saturating_sub(after_bytes),
|
||||
conversation_len = self.state.conversation.len(),
|
||||
"ChatState: in-memory tool-result prune"
|
||||
);
|
||||
self.persistence.replace_history(&self.state.conversation);
|
||||
}
|
||||
|
||||
cleared
|
||||
}
|
||||
|
||||
/// Approximate byte footprint of all string content in the conversation.
|
||||
///
|
||||
/// Used for before/after measurement logging when pruning runs.
|
||||
/// Sums the byte lengths of all string fields; does not allocate.
|
||||
fn conversation_content_bytes(&self) -> usize {
|
||||
self.state
|
||||
.conversation
|
||||
.iter()
|
||||
.map(|item| match item {
|
||||
ConversationItem::System(s) => s.content.len(),
|
||||
ConversationItem::User(u) => u
|
||||
.content
|
||||
.iter()
|
||||
.map(|p| match p {
|
||||
ContentPart::Text { text } => text.len(),
|
||||
ContentPart::Image { url } => url.len(),
|
||||
})
|
||||
.sum::<usize>(),
|
||||
ConversationItem::Assistant(a) => a.content.len(),
|
||||
ConversationItem::ToolResult(tr) => tr.content.len(),
|
||||
ConversationItem::BackendToolCall(b) => b.text_summary().len(),
|
||||
ConversationItem::Reasoning(r) => {
|
||||
xai_grok_sampling_types::reasoning_item_text(r).len()
|
||||
+ r.encrypted_content.as_deref().map(str::len).unwrap_or(0)
|
||||
}
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Record accumulated token usage and emit an event.
|
||||
pub(super) fn record_token_usage(&mut self, total_tokens: u64) {
|
||||
self.state.estimated_tokens_since_model = 0;
|
||||
self.state.estimate_at_last_response =
|
||||
super::state::estimate_conversation_tokens(&self.state.conversation);
|
||||
self.state.total_tokens = total_tokens;
|
||||
self.send_event(ChatStateEvent::TokensUpdated { total_tokens });
|
||||
}
|
||||
|
||||
/// Stash the per-turn `TokenUsage` from the most recent model response.
|
||||
/// No event is emitted — this slot is read on demand at `PromptResponse`
|
||||
/// construction time, not pushed to subscribers.
|
||||
pub(super) fn record_last_turn_usage(&mut self, usage: xai_grok_sampling_types::TokenUsage) {
|
||||
self.state.last_turn_usage = Some(usage);
|
||||
}
|
||||
|
||||
pub(super) fn record_model_call_usage(
|
||||
&mut self,
|
||||
model_id: Option<String>,
|
||||
usage: &xai_grok_sampling_types::TokenUsage,
|
||||
api_duration_ms: Option<u64>,
|
||||
cost_usd_ticks: Option<i64>,
|
||||
) {
|
||||
let model_key = match model_id.as_deref() {
|
||||
Some(id) if !id.is_empty() => id,
|
||||
_ => self.state.sampling_config.model.as_str(),
|
||||
}
|
||||
.to_owned();
|
||||
self.state
|
||||
.prompt_usage
|
||||
.get_or_insert_default()
|
||||
.record_main_loop_call(&model_key, usage, api_duration_ms, cost_usd_ticks);
|
||||
self.state.session_usage.record_main_loop_call(
|
||||
&model_key,
|
||||
usage,
|
||||
api_duration_ms,
|
||||
cost_usd_ticks,
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn record_subagent_usage(
|
||||
&mut self,
|
||||
by_model: &[(String, crate::usage::UsageTotals)],
|
||||
attribute_to_prompt: bool,
|
||||
incomplete: bool,
|
||||
) {
|
||||
if by_model.is_empty() && !incomplete {
|
||||
return;
|
||||
}
|
||||
if attribute_to_prompt {
|
||||
self.state
|
||||
.prompt_usage
|
||||
.get_or_insert_default()
|
||||
.record_subagent(by_model, incomplete);
|
||||
}
|
||||
// The session ledger always folds, even when the usage is not
|
||||
// attributable to the open prompt (its pin may belong to an earlier
|
||||
// prompt). Reporting that gap is the coordinator's sticky flag's job —
|
||||
// never mark a different live prompt's ledger.
|
||||
self.state
|
||||
.session_usage
|
||||
.record_subagent(by_model, incomplete);
|
||||
}
|
||||
|
||||
pub(super) fn mark_usage_incomplete(&mut self, prompt: bool, session: bool) {
|
||||
if prompt {
|
||||
self.state
|
||||
.prompt_usage
|
||||
.get_or_insert_default()
|
||||
.mark_incomplete();
|
||||
}
|
||||
if session {
|
||||
self.state.session_usage.mark_incomplete();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn increment_prompt_index(&mut self) {
|
||||
self.state.prompt_usage = None;
|
||||
self.state.prompt_index += 1;
|
||||
self.send_event(ChatStateEvent::PromptIndexChanged {
|
||||
new_index: self.state.prompt_index,
|
||||
});
|
||||
}
|
||||
|
||||
/// Replace the entire conversation, persist, re-estimate `total_tokens`,
|
||||
/// and emit reset + token-update events.
|
||||
///
|
||||
/// Compaction replaces carry the provider-side overhead forward as a
|
||||
/// *ratio* (`base_estimate × provider_total ÷ estimate_at_last_response`,
|
||||
/// capped at the pre-compaction total; `base_estimate` when that estimate is
|
||||
/// 0) so the reseed neither springs back nor over-counts (see
|
||||
/// `COMPACTION.md`).
|
||||
pub(super) fn replace_conversation(
|
||||
&mut self,
|
||||
items: Vec<ConversationItem>,
|
||||
is_compaction: bool,
|
||||
) {
|
||||
self.snapshot_turn_slice();
|
||||
if is_compaction && let Some(cap) = &mut self.state.turn_capture {
|
||||
cap.compaction_occurred = true;
|
||||
}
|
||||
let pre_replace_total = self.state.total_tokens;
|
||||
// `harness_trace_buffer` / `harness_trace_turns` intentionally untouched:
|
||||
// the planner/verifier subagents ran, so their sealed trace turns survive
|
||||
// a conversation replace (same intent as the `TruncateToPromptIndex` arm).
|
||||
self.persistence.replace_history(&items);
|
||||
let base_estimate = super::state::estimate_conversation_tokens(&items);
|
||||
let mut estimated_tokens =
|
||||
if is_compaction && pre_replace_total > 0 && self.state.estimate_at_last_response > 0 {
|
||||
let ratio = pre_replace_total as f64 / self.state.estimate_at_last_response as f64;
|
||||
(base_estimate as f64 * ratio).round() as u64
|
||||
} else {
|
||||
base_estimate
|
||||
};
|
||||
// Compaction must never appear to increase usage.
|
||||
if is_compaction && pre_replace_total > 0 {
|
||||
estimated_tokens = estimated_tokens.min(pre_replace_total);
|
||||
}
|
||||
self.state.conversation = items;
|
||||
self.state.estimated_tokens_since_model = 0;
|
||||
self.state.total_tokens = estimated_tokens;
|
||||
self.state.estimate_at_last_response =
|
||||
super::state::estimate_conversation_tokens(&self.state.conversation);
|
||||
self.rebase_turn_capture_offset();
|
||||
self.send_event(ChatStateEvent::ConversationReset {
|
||||
new_len: self.state.conversation.len(),
|
||||
});
|
||||
self.send_event(ChatStateEvent::TokensUpdated {
|
||||
total_tokens: estimated_tokens,
|
||||
});
|
||||
}
|
||||
|
||||
/// Atomically swap the leading `System` message with `prompt` (or insert one
|
||||
/// if absent), persisting when changed. Runs inside the actor's command loop
|
||||
/// so it serializes with turn pushes — no lost-update race on a mid-turn
|
||||
/// reconnect. Returns whether the conversation changed.
|
||||
///
|
||||
/// The conversation is cloned (items are `Arc`-backed, so the clone is
|
||||
/// shallow) rather than `mem::take`n: `replace_conversation` snapshots the
|
||||
/// in-flight turn-capture tail from `state.conversation` before swapping,
|
||||
/// so the state must stay intact until then.
|
||||
pub(super) fn replace_system_head(&mut self, prompt: &str) -> bool {
|
||||
if let Some(ConversationItem::System(sys)) = self.state.conversation.first()
|
||||
&& crate::conversation_util::canonical_system_prompt_eq(sys.content.as_ref(), prompt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut conversation = self.state.conversation.clone();
|
||||
let changed =
|
||||
crate::conversation_util::replace_or_insert_system_head(&mut conversation, prompt);
|
||||
debug_assert!(changed, "head mismatch must produce a change");
|
||||
self.replace_conversation(conversation, false);
|
||||
changed
|
||||
}
|
||||
|
||||
/// Restore all state fields from a snapshot.
|
||||
pub(super) fn restore_snapshot(&mut self, snap: ChatStateSnapshot) {
|
||||
self.snapshot_turn_slice();
|
||||
// Harness trace buffers are transient (not part of the snapshot) and
|
||||
// intentionally survive a restore — see `replace_conversation`.
|
||||
self.state.conversation = snap.conversation;
|
||||
self.rebase_turn_capture_offset();
|
||||
self.state.sampling_config = snap.sampling_config;
|
||||
self.state.prompt_index = snap.prompt_index;
|
||||
self.state.total_tokens = snap.total_tokens;
|
||||
self.state.estimated_tokens_since_model = 0;
|
||||
self.state.estimate_at_last_response = if snap.estimate_at_last_response > 0 {
|
||||
snap.estimate_at_last_response
|
||||
} else {
|
||||
super::state::estimate_conversation_tokens(&self.state.conversation)
|
||||
};
|
||||
self.state.agent_edited_paths = snap.agent_edited_paths;
|
||||
self.state.prompt_texts = snap.prompt_texts;
|
||||
self.state.stream_start_ms = snap.stream_start_ms;
|
||||
self.state.turn_start_ms = snap.turn_start_ms;
|
||||
self.state.last_compaction_prompt_index = snap.last_compaction_prompt_index;
|
||||
self.state.credentials = snap.credentials;
|
||||
// Drop abandoned prompt billing; session ledger is lifetime.
|
||||
self.state.prompt_usage = None;
|
||||
}
|
||||
|
||||
/// If turn capture is active, append the current turn's tail items into
|
||||
/// `pre_replacement_messages` before an in-place mutation shifts or drops them.
|
||||
pub(super) fn snapshot_turn_slice(&mut self) {
|
||||
if let Some(cap) = &mut self.state.turn_capture {
|
||||
cap.pre_replacement_messages
|
||||
.extend_from_slice(Self::turn_tail(
|
||||
&self.state.conversation,
|
||||
cap.turn_start_offset,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-base an active turn capture's start offset to the current conversation
|
||||
/// length after an in-place mutation, keeping the tail slice valid.
|
||||
pub(super) fn rebase_turn_capture_offset(&mut self) {
|
||||
if let Some(cap) = &mut self.state.turn_capture {
|
||||
cap.turn_start_offset = self.state.conversation.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fail-safe `conversation[offset..]` for turn capture: a capture accounting
|
||||
/// slip must never abort the user's session (a raw index here SIGABRT-crashed
|
||||
/// a live CLI), so an out-of-range offset yields an empty slice — loud in dev
|
||||
/// via `debug_assert!`, with a prod breadcrumb via `error!`.
|
||||
pub(super) fn turn_tail(
|
||||
conversation: &[ConversationItem],
|
||||
offset: usize,
|
||||
) -> &[ConversationItem] {
|
||||
debug_assert!(
|
||||
offset <= conversation.len(),
|
||||
"turn_start_offset {offset} > len {}",
|
||||
conversation.len()
|
||||
);
|
||||
conversation.get(offset..).unwrap_or_else(|| {
|
||||
tracing::error!(
|
||||
offset,
|
||||
len = conversation.len(),
|
||||
"turn-capture offset past conversation end; trace tail dropped"
|
||||
);
|
||||
&[]
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Query handlers for the ChatStateActor.
|
||||
|
||||
use super::ChatStateActor;
|
||||
use crate::compaction_utils::extract_last_user_query;
|
||||
use crate::events::ChatStateEvent;
|
||||
use crate::types::{AutoCompactTrigger, ChatStateSnapshot, ConversationCounts, NotificationMeta};
|
||||
|
||||
impl ChatStateActor {
|
||||
/// Build a notification meta from current timing state.
|
||||
pub(super) fn get_notification_meta(&self) -> NotificationMeta {
|
||||
NotificationMeta {
|
||||
stream_start_ms: self.state.stream_start_ms,
|
||||
turn_start_ms: self.state.turn_start_ms,
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a full snapshot of the actor's state.
|
||||
pub(super) fn snapshot(&self) -> ChatStateSnapshot {
|
||||
ChatStateSnapshot {
|
||||
conversation: self.state.conversation.clone(),
|
||||
sampling_config: self.state.sampling_config.clone(),
|
||||
prompt_index: self.state.prompt_index,
|
||||
total_tokens: self.state.total_tokens,
|
||||
estimate_at_last_response: self.state.estimate_at_last_response,
|
||||
agent_edited_paths: self.state.agent_edited_paths.clone(),
|
||||
prompt_texts: self.state.prompt_texts.clone(),
|
||||
stream_start_ms: self.state.stream_start_ms,
|
||||
turn_start_ms: self.state.turn_start_ms,
|
||||
last_compaction_prompt_index: self.state.last_compaction_prompt_index,
|
||||
credentials: self.state.credentials.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Truncate conversation to a target prompt index (rewind).
|
||||
///
|
||||
/// Walks the conversation to find the Nth `User` item (where N =
|
||||
/// `target_prompt_index`), truncates everything from that point onward,
|
||||
/// truncates `prompt_texts` to match, persists, and emits `ConversationReset`.
|
||||
///
|
||||
/// Prompt index semantics:
|
||||
/// - 0 = no user turns have started (only system message, if any)
|
||||
/// - 1 = one user turn completed
|
||||
/// - N = N user turns completed
|
||||
///
|
||||
/// Truncating to `target_prompt_index = 1` keeps only items up to (but not
|
||||
/// including) the 2nd `User` message.
|
||||
pub(super) fn truncate_to_prompt_index(&mut self, target_prompt_index: usize) {
|
||||
if target_prompt_index >= self.state.prompt_index {
|
||||
// Nothing to truncate — already at or before the target.
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the conversation position of the Nth User item.
|
||||
// Items before that position are kept; from that position onward removed.
|
||||
let mut user_count = 0;
|
||||
let mut truncate_at = self.state.conversation.len();
|
||||
|
||||
for (i, item) in self.state.conversation.iter().enumerate() {
|
||||
if matches!(item, xai_grok_sampling_types::ConversationItem::User(_)) {
|
||||
if user_count == target_prompt_index {
|
||||
truncate_at = i;
|
||||
break;
|
||||
}
|
||||
user_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
self.state.conversation.truncate(truncate_at);
|
||||
self.state.prompt_texts.truncate(target_prompt_index);
|
||||
self.state.prompt_index = target_prompt_index;
|
||||
self.state.total_tokens =
|
||||
super::state::estimate_conversation_tokens(&self.state.conversation);
|
||||
self.state.estimated_tokens_since_model = 0;
|
||||
self.state.estimate_at_last_response = self.state.total_tokens;
|
||||
|
||||
self.persistence.replace_history(&self.state.conversation);
|
||||
|
||||
self.send_event(ChatStateEvent::ConversationReset {
|
||||
new_len: self.state.conversation.len(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Check if auto-compact is needed based on token utilization.
|
||||
///
|
||||
/// Returns `Some(AutoCompactTrigger)` if `total_tokens` exceeds
|
||||
/// `context_window * threshold_percent / 100`, otherwise `None`.
|
||||
pub(super) fn check_auto_compact_needed(
|
||||
&self,
|
||||
threshold_percent: u8,
|
||||
) -> Option<AutoCompactTrigger> {
|
||||
let context_window = self.state.sampling_config.context_window;
|
||||
let cw = context_window.get();
|
||||
|
||||
if xai_token_estimation::exceeds_threshold(self.state.total_tokens, cw, threshold_percent) {
|
||||
let utilization_percent =
|
||||
xai_token_estimation::usage_percentage_truncated_u8(self.state.total_tokens, cw);
|
||||
Some(AutoCompactTrigger {
|
||||
total_tokens: self.state.total_tokens,
|
||||
context_window,
|
||||
utilization_percent,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn get_last_model_metadata(&self) -> crate::commands::ModelMetadata {
|
||||
self.state
|
||||
.conversation
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| {
|
||||
if let xai_grok_sampling_types::ConversationItem::Assistant(a) = item {
|
||||
Some(crate::commands::ModelMetadata {
|
||||
resolved_model_id: a.model_id.clone(),
|
||||
model_fingerprint: a.model_fingerprint.clone(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ─── Narrow targeted queries ─────────────────────────────────────────────
|
||||
|
||||
/// Return the number of items in the conversation.
|
||||
pub(super) fn get_conversation_len(&self) -> usize {
|
||||
self.state.conversation.len()
|
||||
}
|
||||
|
||||
/// Whether the conversation has any assistant tool call without a matching
|
||||
/// `ToolResult` (the dangling-tool-call repair would fire on the next build).
|
||||
pub(super) fn has_dangling_tool_calls(&self) -> bool {
|
||||
xai_grok_sampling_types::has_dangling_tool_calls(&self.state.conversation)
|
||||
}
|
||||
|
||||
/// Return the text content of the last assistant message with non-empty text.
|
||||
///
|
||||
/// Walks the conversation backwards and returns the first `Assistant` item
|
||||
/// whose `content` field is non-empty after trimming. Returns `None` when
|
||||
/// no such item exists.
|
||||
pub(super) fn get_last_assistant_text(&self) -> Option<String> {
|
||||
self.state.conversation.iter().rev().find_map(|item| {
|
||||
if let xai_grok_sampling_types::ConversationItem::Assistant(a) = item
|
||||
&& !a.content.trim().is_empty()
|
||||
{
|
||||
return Some(a.content.as_ref().to_owned());
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the current turn's last assistant message with non-empty text, or
|
||||
/// `None` when the turn produced none.
|
||||
///
|
||||
/// Like [`Self::get_last_assistant_text`], but the backwards walk stops at the
|
||||
/// turn boundary (a user item with `prompt_index` set, a genuine user message,
|
||||
/// or a synthetic reason with [`SyntheticReason::starts_prompt_turn`]); mid-turn
|
||||
/// synthetic injections are walked past.
|
||||
///
|
||||
/// [`SyntheticReason::starts_prompt_turn`]: xai_grok_sampling_types::SyntheticReason::starts_prompt_turn
|
||||
pub(super) fn get_last_assistant_text_in_turn(&self) -> Option<String> {
|
||||
for item in self.state.conversation.iter().rev() {
|
||||
match item {
|
||||
xai_grok_sampling_types::ConversationItem::Assistant(a)
|
||||
if !a.content.trim().is_empty() =>
|
||||
{
|
||||
return Some(a.content.as_ref().to_owned());
|
||||
}
|
||||
xai_grok_sampling_types::ConversationItem::User(u)
|
||||
if u.prompt_index.is_some()
|
||||
|| u.synthetic_reason
|
||||
.as_ref()
|
||||
.is_none_or(|r| r.starts_prompt_turn()) =>
|
||||
{
|
||||
return None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Return the text of the **first content part** of the first `User` message,
|
||||
/// if and only if that part is `ContentPart::Text`.
|
||||
///
|
||||
/// Matches the original call-site semantics exactly: if the first user
|
||||
/// message leads with a non-text part (e.g. an image in a multimodal
|
||||
/// prompt), this returns `None` rather than scanning further parts.
|
||||
/// Callers that need "any text part" rather than "first-part-is-text"
|
||||
/// should use `get_conversation()` directly.
|
||||
pub(super) fn get_first_user_text(&self) -> Option<String> {
|
||||
self.state.conversation.iter().find_map(|item| {
|
||||
if let xai_grok_sampling_types::ConversationItem::User(u) = item {
|
||||
// Only return text if the first part is Text — behaviour-preserving
|
||||
// w.r.t. the original `content.first().and_then(|p| if Text { … })`.
|
||||
u.content.first().and_then(|part| {
|
||||
if let xai_grok_sampling_types::ContentPart::Text { text } = part {
|
||||
Some(text.as_ref().to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the conversation item at `index`, or `None` if out of bounds.
|
||||
pub(super) fn get_conversation_item_at(
|
||||
&self,
|
||||
index: usize,
|
||||
) -> Option<xai_grok_sampling_types::ConversationItem> {
|
||||
self.state.conversation.get(index).cloned()
|
||||
}
|
||||
|
||||
/// Return the processed text of the last user query (metadata tags stripped).
|
||||
///
|
||||
/// Delegates to [`extract_last_user_query`] so the caller does not need a
|
||||
/// full conversation clone.
|
||||
pub(super) fn get_last_user_query_text(&self) -> Option<String> {
|
||||
extract_last_user_query(&self.state.conversation)
|
||||
}
|
||||
|
||||
/// Return conversation item counts by role without cloning any items.
|
||||
pub(super) fn get_conversation_counts(&self) -> ConversationCounts {
|
||||
let mut counts = ConversationCounts {
|
||||
total: self.state.conversation.len(),
|
||||
..Default::default()
|
||||
};
|
||||
for item in &self.state.conversation {
|
||||
match item {
|
||||
xai_grok_sampling_types::ConversationItem::User(_) => counts.user += 1,
|
||||
xai_grok_sampling_types::ConversationItem::Assistant(_) => {
|
||||
counts.assistant += 1;
|
||||
}
|
||||
xai_grok_sampling_types::ConversationItem::ToolResult(_) => {
|
||||
counts.tool_result += 1;
|
||||
}
|
||||
xai_grok_sampling_types::ConversationItem::System(_) => {}
|
||||
xai_grok_sampling_types::ConversationItem::BackendToolCall(_) => {}
|
||||
xai_grok_sampling_types::ConversationItem::Reasoning(_) => {}
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Return the first `System` message in the conversation, or `None`.
|
||||
pub(super) fn get_system_message(&self) -> Option<xai_grok_sampling_types::ConversationItem> {
|
||||
self.state
|
||||
.conversation
|
||||
.iter()
|
||||
.find(|item| matches!(item, xai_grok_sampling_types::ConversationItem::System(_)))
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
//! ConversationRequest assembly — image compaction, pruning, repair, memory injection.
|
||||
|
||||
use xai_grok_sampling_types::{
|
||||
ContentPart, ConversationItem, ConversationRequest, ToolSpec, TraceContext,
|
||||
};
|
||||
|
||||
use super::ChatStateActor;
|
||||
use crate::events::ChatStateEvent;
|
||||
use crate::types::PruningConfig;
|
||||
|
||||
/// Placeholder inserted when a tool result is hard-cleared.
|
||||
///
|
||||
/// `pub(super)` so that `mutations.rs` can use the same string when it
|
||||
/// hard-clears tool results in the retained in-memory conversation.
|
||||
pub(super) const HARD_CLEAR_PLACEHOLDER: &str = "[Tool result omitted — too old]";
|
||||
|
||||
/// Separator inserted between head and tail in soft-trimmed results.
|
||||
const SOFT_TRIM_SEPARATOR: &str = "\n\n[…trimmed…]\n\n";
|
||||
|
||||
impl ChatStateActor {
|
||||
/// Build a `ConversationRequest` from the current actor state.
|
||||
///
|
||||
/// 1. Evict oldest inline images when the inline-image bytes near 50 MB
|
||||
/// 2. Prune old tool results if over 50% context utilization
|
||||
/// 3. Optionally persist the memory reminder into actor state
|
||||
/// 4. Inject memory reminder into the request clone (if needed)
|
||||
/// 5. Assemble and return the `ConversationRequest`
|
||||
///
|
||||
/// # Repair invariant
|
||||
///
|
||||
/// The `BuildConversationRequest` command handler calls
|
||||
/// `ensure_conversation_integrity()` on the actor's own conversation
|
||||
/// **before** this function runs. The clone therefore starts from an
|
||||
/// already-repaired state, so there is no need to run
|
||||
/// `dedup_duplicate_tool_results` / `repair_dangling_tool_calls` on the
|
||||
/// clone — those would be O(n) no-ops.
|
||||
pub(super) fn build_conversation_request(
|
||||
&mut self,
|
||||
tool_definitions: Vec<ToolSpec>,
|
||||
memory_reminder: Option<String>,
|
||||
persist_memory_reminder: bool,
|
||||
trace: Option<Box<dyn TraceContext>>,
|
||||
conv_id: String,
|
||||
req_id: String,
|
||||
) -> ConversationRequest {
|
||||
let needs_prune = should_prune(
|
||||
self.state.total_tokens,
|
||||
self.state.sampling_config.context_window,
|
||||
);
|
||||
let mut memory_reminder = memory_reminder;
|
||||
if let Some(reminder) = memory_reminder.as_deref()
|
||||
&& persist_memory_reminder
|
||||
{
|
||||
// A live in-place inject can prepend a `System` item, shifting indices
|
||||
// under an active capture; snapshot + rebase like the other mutators.
|
||||
self.snapshot_turn_slice();
|
||||
let injected = inject_memory_reminder(&mut self.state.conversation, reminder);
|
||||
if injected {
|
||||
self.persistence.replace_history(&self.state.conversation);
|
||||
memory_reminder = None;
|
||||
}
|
||||
self.rebase_turn_capture_offset();
|
||||
}
|
||||
// Measure the exact serialized body and evict only once it approaches
|
||||
// the 50 MB ceiling. `conversation_body_bytes` is wire-accurate yet
|
||||
// cheap — it skips the multi-MB base64 escape scan (see its docs) — so
|
||||
// it runs inline on every turn with no blocking-thread offload.
|
||||
// Eviction rewrites earlier turns and busts the KV-cache prefix, so we
|
||||
// only pay it when the body is actually near the limit (the original
|
||||
// behavior — evicting every turn — caused chronic cache misses).
|
||||
let body_bytes = conversation_body_bytes(&self.state.conversation);
|
||||
let inline_images = inline_image_count(&self.state.conversation);
|
||||
let needs_image_compaction = body_bytes >= IMAGE_COMPACT_TRIGGER_BYTES;
|
||||
let needs_mutation = needs_prune || memory_reminder.is_some() || needs_image_compaction;
|
||||
|
||||
// Only allocate the mutable working copy when a mutation path is taken.
|
||||
let mut eviction: Option<ImageEvictionOutcome> = None;
|
||||
let items = if needs_mutation {
|
||||
let mut items = self.state.conversation.clone();
|
||||
|
||||
// Step 1: When the body nears the 50 MB ceiling, evict oldest
|
||||
// images down to the low-water mark (not just under the trigger).
|
||||
// Reclaiming a batch frees headroom for many subsequent image
|
||||
// turns, so the prefix is rewritten once and then stays cache-warm
|
||||
// — instead of re-triggering and re-busting the cache every turn.
|
||||
if needs_image_compaction {
|
||||
eviction = Some(compact_images_to_byte_budget(
|
||||
&mut items,
|
||||
body_bytes,
|
||||
IMAGE_COMPACT_RECLAIM_TARGET_BYTES,
|
||||
));
|
||||
}
|
||||
|
||||
// Step 2: Prune old tool results if context is > 50% utilized
|
||||
if needs_prune {
|
||||
prune_conversation(&mut items, &self.pruning_config);
|
||||
}
|
||||
|
||||
// Step 3: Inject memory reminder into the system message
|
||||
if let Some(reminder) = memory_reminder {
|
||||
inject_memory_reminder(&mut items, &reminder);
|
||||
}
|
||||
|
||||
items
|
||||
} else {
|
||||
// Hot path: no pruning, no memory reminder, no old images —
|
||||
// clone directly into the request without any intermediate mutation passes.
|
||||
self.state.conversation.clone()
|
||||
};
|
||||
|
||||
// Per-turn image-budget record for local verification. Emitted on the
|
||||
// ChatState event channel (chat-state can't reach the shell's unified
|
||||
// log directly); the session consumer writes it to the local log file.
|
||||
// Only on image-bearing turns to avoid noise.
|
||||
if inline_images > 0 {
|
||||
self.send_event(ChatStateEvent::ImageBudget {
|
||||
body_bytes,
|
||||
trigger_bytes: IMAGE_COMPACT_TRIGGER_BYTES,
|
||||
reclaim_target_bytes: IMAGE_COMPACT_RECLAIM_TARGET_BYTES,
|
||||
inline_images,
|
||||
needs_image_compaction,
|
||||
evicted: eviction.as_ref().map_or(0, |o| o.evicted),
|
||||
body_bytes_after: eviction.as_ref().map_or(body_bytes, |o| o.body_bytes_after),
|
||||
});
|
||||
}
|
||||
|
||||
// Step 4: Assemble request
|
||||
ConversationRequest {
|
||||
items,
|
||||
tools: tool_definitions,
|
||||
hosted_tools: vec![],
|
||||
tool_choice: None,
|
||||
model: Some(self.state.sampling_config.model.clone()),
|
||||
temperature: self.state.sampling_config.temperature,
|
||||
max_output_tokens: self.state.sampling_config.max_completion_tokens,
|
||||
top_p: self.state.sampling_config.top_p,
|
||||
x_grok_conv_id: Some(conv_id),
|
||||
x_grok_req_id: Some(req_id),
|
||||
x_grok_session_id: None,
|
||||
x_grok_turn_idx: None,
|
||||
x_grok_agent_id: None,
|
||||
x_grok_deployment_id: None,
|
||||
x_grok_user_id: None,
|
||||
trace,
|
||||
reasoning_effort: self.state.sampling_config.reasoning_effort,
|
||||
json_schema: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Pruning (standalone functions, no actor state needed)
|
||||
// ============================================================================
|
||||
|
||||
/// Check whether pruning should run based on context utilization.
|
||||
///
|
||||
/// Returns `true` when `total_tokens` exceeds 50% of `context_window`.
|
||||
pub(crate) fn should_prune(total_tokens: u64, context_window: std::num::NonZeroU64) -> bool {
|
||||
total_tokens > context_window.get() / 2
|
||||
}
|
||||
|
||||
/// Prune old, large tool results from the conversation in place.
|
||||
///
|
||||
/// Turn age is estimated by walking backward through the conversation and
|
||||
/// counting `User` items to determine which "turn" each tool result belongs to.
|
||||
pub(crate) fn prune_conversation(conversation: &mut [ConversationItem], config: &PruningConfig) {
|
||||
if !config.enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut turn_from_end: usize = 0;
|
||||
let mut seen_first_user = false;
|
||||
|
||||
for i in (0..conversation.len()).rev() {
|
||||
if matches!(&conversation[i], ConversationItem::User(_)) {
|
||||
if seen_first_user {
|
||||
turn_from_end += 1;
|
||||
}
|
||||
seen_first_user = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let ConversationItem::ToolResult(tool_result) = &mut conversation[i] else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Never prune recent turns.
|
||||
if turn_from_end < config.keep_last_n_turns {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Hard clear: very old tool results → replace entirely.
|
||||
if turn_from_end >= config.hard_clear_age_turns {
|
||||
if tool_result.content.as_ref() != HARD_CLEAR_PLACEHOLDER {
|
||||
tool_result.content = std::sync::Arc::<str>::from(HARD_CLEAR_PLACEHOLDER);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Soft trim: large tool results → keep head + tail.
|
||||
let content_len = tool_result.content.chars().count();
|
||||
if content_len > config.soft_trim_threshold {
|
||||
let head = safe_char_slice(&tool_result.content, 0, config.soft_trim_head);
|
||||
let tail = safe_char_slice_tail(&tool_result.content, config.soft_trim_tail);
|
||||
tool_result.content =
|
||||
std::sync::Arc::<str>::from(format!("{head}{SOFT_TRIM_SEPARATOR}{tail}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Image size-gated compaction (request-copy only)
|
||||
// ============================================================================
|
||||
|
||||
/// Replaces an inline image evicted to keep the request body under the proxy's
|
||||
/// 50 MB limit. Phrased so the model treats the image as gone rather than
|
||||
/// describing it from memory — a silently-stripped image otherwise induces
|
||||
/// confident hallucination of its contents.
|
||||
const IMAGE_COMPACT_PLACEHOLDER: &str = "[An earlier image was removed to keep the request within its size limit and is no longer visible. Do not describe or reason about its contents from memory; ask the user to re-share it if you need to see it again.]";
|
||||
|
||||
/// Hard request-body ceiling enforced by the inference proxy
|
||||
/// (nginx `proxy-body-size`). Bodies larger than this are rejected with HTTP
|
||||
/// 413 — or a connection reset before the response is written. Inline image
|
||||
/// `data:` URLs (base64) are the dominant term in this size.
|
||||
const MAX_REQUEST_BYTES: usize = 50 * 1024 * 1024;
|
||||
|
||||
/// Evict old images once the serialized body reaches this size.
|
||||
///
|
||||
/// We gate on the exact body (see [`conversation_body_bytes`]) — system prompt,
|
||||
/// all message text, tool results, and image `data:` URLs are all counted
|
||||
/// precisely. This sits 3 MB below [`MAX_REQUEST_BYTES`] as headroom for the
|
||||
/// only parts of the wire request the body measurement does **not** include:
|
||||
/// - **tool definitions** — sent alongside the conversation but not part of it
|
||||
/// (tool JSON schemas + MCP tools); this is the bulk of the gap.
|
||||
/// - the request envelope and sampling params.
|
||||
/// - the small delta between our internal `ContentPart` JSON and the public-API
|
||||
/// wire format (the dominant base64 image bytes are identical in both).
|
||||
///
|
||||
/// The uncounted remainder is only sub-MB to low-MB in practice, so 3 MB covers
|
||||
/// it without needlessly sacrificing image capacity. The sampler's reactive 413
|
||||
/// image-strip is the final backstop if this is ever under-estimated.
|
||||
///
|
||||
/// Below this threshold every image stays in place so the KV-cache prefix is
|
||||
/// byte-stable across turns; eviction rewrites earlier turns and busts the
|
||||
/// prefix cache, so we only pay that cost when a 413 is actually near.
|
||||
pub(crate) const IMAGE_COMPACT_TRIGGER_BYTES: usize = MAX_REQUEST_BYTES - 3 * 1024 * 1024;
|
||||
|
||||
/// Low-water mark that eviction reclaims down to once it fires (hysteresis).
|
||||
///
|
||||
/// Eviction is **gated** at [`IMAGE_COMPACT_TRIGGER_BYTES`] but **reclaims** to
|
||||
/// this strictly lower mark. Evicting only enough to clear the trigger means
|
||||
/// the next image-bearing turn re-crosses it and evicts again — rewriting the
|
||||
/// prefix and busting the KV cache on essentially every turn once the body sits
|
||||
/// at the ceiling. Dropping to half the hard limit instead frees ~25 MB of
|
||||
/// headroom, so the prefix is rewritten once and then stays stable (cache-warm)
|
||||
/// across many turns until the headroom is consumed again. The oldest images
|
||||
/// (least useful) are sacrificed in a batch rather than one-per-turn — a
|
||||
/// high-water trigger paired with a lower reclaim mark (classic hysteresis).
|
||||
pub(crate) const IMAGE_COMPACT_RECLAIM_TARGET_BYTES: usize = MAX_REQUEST_BYTES / 2;
|
||||
|
||||
// Hysteresis invariant: eviction is gated at the trigger but reclaims to a
|
||||
// strictly lower mark, so one batch eviction buys many cache-warm turns rather
|
||||
// than re-triggering (and re-busting the prompt cache) every turn at the
|
||||
// ceiling. Enforced at compile time so the two constants can't drift together.
|
||||
const _: () = assert!(IMAGE_COMPACT_RECLAIM_TARGET_BYTES < IMAGE_COMPACT_TRIGGER_BYTES);
|
||||
|
||||
/// An [`std::io::Write`] sink that counts bytes instead of storing them. Lets
|
||||
/// us measure a `serde_json` encoding's length without allocating the full
|
||||
/// (potentially tens-of-MB) output buffer.
|
||||
#[derive(Default)]
|
||||
struct ByteCounter(usize);
|
||||
|
||||
impl std::io::Write for ByteCounter {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0 += buf.len();
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact JSON-serialized byte length of any value, measured through a
|
||||
/// [`ByteCounter`] so no encoded buffer is allocated. JSON quoting and string
|
||||
/// escaping are captured precisely (not estimated from field lengths).
|
||||
fn serialized_json_bytes<T: serde::Serialize + ?Sized>(value: &T) -> usize {
|
||||
let mut counter = ByteCounter::default();
|
||||
if let Err(err) = serde_json::to_writer(&mut counter, value) {
|
||||
// Serializing in-memory state to a byte sink is infallible in
|
||||
// practice; if it ever fails, fall back to the bytes counted so far
|
||||
// (a lower bound) rather than forcing a needless compaction.
|
||||
tracing::warn!(%err, "failed to measure serialized size");
|
||||
}
|
||||
counter.0
|
||||
}
|
||||
|
||||
/// Serialized JSON frame of one image content part with an empty URL —
|
||||
/// `{"type":"image","url":""}`. The real payload adds exactly `url.len()` on
|
||||
/// top: an inline base64 `data:` URL contains no JSON-escaped characters, so
|
||||
/// its encoded length equals its raw length. Identical in our internal JSON and
|
||||
/// on the public-API wire (the base64 bytes are the same in both).
|
||||
const IMAGE_PART_FRAME_BYTES: usize = r#"{"type":"image","url":""}"#.len();
|
||||
|
||||
/// Exact serialized size of a single inline image part (frame + raw URL bytes).
|
||||
fn image_part_bytes(url: &str) -> usize {
|
||||
IMAGE_PART_FRAME_BYTES + url.len()
|
||||
}
|
||||
|
||||
/// Count of inline images in the conversation — for observability only.
|
||||
fn inline_image_count(conversation: &[ConversationItem]) -> usize {
|
||||
conversation
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
ConversationItem::User(u) => Some(u),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|u| u.content.iter())
|
||||
.filter(|p| matches!(p, ContentPart::Image { .. }))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Outcome of [`compact_images_to_byte_budget`], surfaced for logging and
|
||||
/// local verification.
|
||||
pub(crate) struct ImageEvictionOutcome {
|
||||
/// Number of inline images replaced with the placeholder.
|
||||
pub evicted: usize,
|
||||
/// Estimated serialized body size after eviction (`current_bytes` minus the
|
||||
/// net bytes freed) — at or below `target_bytes` once enough images go.
|
||||
pub body_bytes_after: usize,
|
||||
}
|
||||
|
||||
/// Exact serialized size of the conversation body — the figure the inference
|
||||
/// proxy weighs against its 50 MB limit — computed **without** scanning the
|
||||
/// multi-MB base64 image payloads.
|
||||
///
|
||||
/// `serde_json` escape-scans every byte of every string, so encoding the real
|
||||
/// conversation would walk tens of MB of base64 on every turn. Instead we
|
||||
/// serialize a copy with image URLs blanked (cheap: only the small non-image
|
||||
/// content — system prompt, message text, tool results — is scanned, and it is
|
||||
/// measured *exactly*, escaping included) and add back each URL's raw length.
|
||||
/// Because base64 never escapes, that length is its exact serialized
|
||||
/// contribution, so the result is byte-for-byte the true body size.
|
||||
///
|
||||
/// The blanking copy is cheap: image data lives behind `Arc<str>`, so cloning
|
||||
/// only bumps refcounts and the blanked clone drops them without copying bytes.
|
||||
fn conversation_body_bytes(conversation: &[ConversationItem]) -> usize {
|
||||
let mut blanked = conversation.to_vec();
|
||||
let mut image_url_bytes = 0usize;
|
||||
for item in &mut blanked {
|
||||
if let ConversationItem::User(user) = item {
|
||||
for part in &mut user.content {
|
||||
if let ContentPart::Image { url } = part {
|
||||
image_url_bytes += url.len();
|
||||
*url = std::sync::Arc::<str>::from("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
serialized_json_bytes(&blanked) + image_url_bytes
|
||||
}
|
||||
|
||||
/// Replace the oldest inline images with [`IMAGE_COMPACT_PLACEHOLDER`] until
|
||||
/// the serialized request body drops back to `target_bytes`, keeping the
|
||||
/// newest images. `current_bytes` is the already-measured whole-body size (see
|
||||
/// [`conversation_body_bytes`]); each eviction drops `running` by the image
|
||||
/// part's exact serialized size minus the placeholder that replaces it, so it
|
||||
/// tracks the true body byte-for-byte as images are removed.
|
||||
///
|
||||
/// Operates on a mutable slice — intended for the request *copy* so the stored
|
||||
/// conversation is never modified.
|
||||
///
|
||||
/// ## Cache behavior
|
||||
///
|
||||
/// Eviction is **oldest-first**, which is sticky by construction: because we
|
||||
/// always retain the newest images, an image only transitions image →
|
||||
/// placeholder as *newer/larger* payloads push the body past the limit, never
|
||||
/// placeholder → image within a stable prefix. (Token compaction removes old
|
||||
/// turns wholesale and can free room to restore a previously-evicted image,
|
||||
/// but that already rewrites the prefix and invalidates the server-side prompt
|
||||
/// cache, so the restore is free.)
|
||||
///
|
||||
/// The caller gates eviction at [`IMAGE_COMPACT_TRIGGER_BYTES`] but passes the
|
||||
/// lower [`IMAGE_COMPACT_RECLAIM_TARGET_BYTES`] as `target_bytes`, so one
|
||||
/// eviction reclaims a batch of the oldest images and frees headroom for many
|
||||
/// later image turns. This turns "rewrite the prefix on essentially every turn
|
||||
/// once at the ceiling" into one larger, rare rewrite followed by a long
|
||||
/// cache-warm stretch — the prefix-cache cost of dropping the oldest (least
|
||||
/// useful) image is paid infrequently instead of per turn.
|
||||
///
|
||||
/// This replaces the previous policy — strip every image older than the most
|
||||
/// recent user turn on *every* request — which (a) busted the prompt-cache
|
||||
/// prefix on the turn after any image, and (b) dropped images the model still
|
||||
/// needed one turn later, causing it to hallucinate their contents.
|
||||
pub(crate) fn compact_images_to_byte_budget(
|
||||
conversation: &mut [ConversationItem],
|
||||
current_bytes: usize,
|
||||
target_bytes: usize,
|
||||
) -> ImageEvictionOutcome {
|
||||
if current_bytes <= target_bytes {
|
||||
return ImageEvictionOutcome {
|
||||
evicted: 0,
|
||||
body_bytes_after: current_bytes,
|
||||
};
|
||||
}
|
||||
|
||||
// The text part each evicted image is replaced with. Measured once: every
|
||||
// eviction shrinks the body by the image part's bytes and grows it back by
|
||||
// this placeholder's bytes, so the net saving is `image - placeholder`.
|
||||
let placeholder = ContentPart::Text {
|
||||
text: std::sync::Arc::<str>::from(IMAGE_COMPACT_PLACEHOLDER),
|
||||
};
|
||||
let placeholder_bytes = serialized_json_bytes(&placeholder);
|
||||
|
||||
// (item_idx, part_idx, exact serialized image-part bytes) for every inline
|
||||
// image, oldest-first.
|
||||
let mut images: Vec<(usize, usize, usize)> = Vec::new();
|
||||
for (i, item) in conversation.iter().enumerate() {
|
||||
if let ConversationItem::User(user) = item {
|
||||
for (j, part) in user.content.iter().enumerate() {
|
||||
if let ContentPart::Image { url } = part {
|
||||
images.push((i, j, image_part_bytes(url)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Evict oldest-first until the body fits again, keeping the newest images.
|
||||
let mut running = current_bytes;
|
||||
let mut evicted = 0usize;
|
||||
for &(i, j, image_bytes) in &images {
|
||||
if running <= target_bytes {
|
||||
break;
|
||||
}
|
||||
if let ConversationItem::User(user) = &mut conversation[i]
|
||||
&& let Some(part) = user.content.get_mut(j)
|
||||
{
|
||||
*part = placeholder.clone();
|
||||
// Net body saving: the image part leaves, the placeholder takes its
|
||||
// slot. Everything else (siblings, commas, brackets) is untouched,
|
||||
// so this is the exact change in the serialized body size.
|
||||
running = running.saturating_sub(image_bytes.saturating_sub(placeholder_bytes));
|
||||
evicted += 1;
|
||||
}
|
||||
}
|
||||
|
||||
ImageEvictionOutcome {
|
||||
evicted,
|
||||
body_bytes_after: running,
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Memory reminder injection
|
||||
// ============================================================================
|
||||
|
||||
use crate::types::MEMORY_CONTEXT_OPEN_TAG;
|
||||
|
||||
/// Upsert a memory reminder into the conversation's system message.
|
||||
///
|
||||
/// If the first item is a `System` message, any previously injected memory
|
||||
/// reminder section is replaced in-place; otherwise the reminder is appended.
|
||||
/// If no system message exists, a new `System` item is prepended.
|
||||
///
|
||||
/// Returns `true` when the conversation was changed.
|
||||
pub(super) fn inject_memory_reminder(items: &mut Vec<ConversationItem>, reminder: &str) -> bool {
|
||||
let reminder = reminder.trim();
|
||||
if reminder.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Some(ConversationItem::System(sys)) = items.first_mut() {
|
||||
upsert_memory_reminder_text(&mut sys.content, reminder)
|
||||
} else {
|
||||
items.insert(0, ConversationItem::system(reminder));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn upsert_memory_reminder_text(system_prompt: &mut std::sync::Arc<str>, reminder: &str) -> bool {
|
||||
let existing_start = system_prompt
|
||||
.find(MEMORY_CONTEXT_OPEN_TAG)
|
||||
.map(|idx| system_prompt[..idx].trim_end_matches('\n').len());
|
||||
|
||||
let updated: String = if let Some(prefix_len) = existing_start {
|
||||
let prefix = system_prompt[..prefix_len].trim_end_matches('\n');
|
||||
if prefix.is_empty() {
|
||||
reminder.to_string()
|
||||
} else {
|
||||
format!("{prefix}\n\n{reminder}")
|
||||
}
|
||||
} else if system_prompt.trim_end() == reminder {
|
||||
system_prompt.as_ref().to_owned()
|
||||
} else if system_prompt.is_empty() {
|
||||
reminder.to_string()
|
||||
} else {
|
||||
format!("{}\n\n{reminder}", system_prompt.trim_end_matches('\n'))
|
||||
};
|
||||
|
||||
if system_prompt.as_ref() == updated.as_str() {
|
||||
false
|
||||
} else {
|
||||
*system_prompt = std::sync::Arc::<str>::from(updated);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// String helpers
|
||||
// ============================================================================
|
||||
|
||||
fn safe_char_slice(s: &str, start: usize, count: usize) -> String {
|
||||
s.chars().skip(start).take(count).collect()
|
||||
}
|
||||
|
||||
fn safe_char_slice_tail(s: &str, count: usize) -> String {
|
||||
let total = s.chars().count();
|
||||
if count >= total {
|
||||
return s.to_string();
|
||||
}
|
||||
s.chars().skip(total - count).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn should_prune_gating() {
|
||||
use std::num::NonZeroU64;
|
||||
let cw = NonZeroU64::new(10000).unwrap();
|
||||
assert!(!should_prune(1000, cw)); // 10%
|
||||
assert!(should_prune(6000, cw)); // 60%
|
||||
assert!(!should_prune(5000, cw)); // 50% exact (> not >=)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_disabled_is_noop() {
|
||||
let mut conv = vec![ConversationItem::tool_result("c1", "x".repeat(10_000))];
|
||||
let config = PruningConfig {
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
};
|
||||
prune_conversation(&mut conv, &config);
|
||||
if let ConversationItem::ToolResult(ref tr) = conv[0] {
|
||||
assert_eq!(tr.content.len(), 10_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inject_memory_into_existing_system() {
|
||||
let mut items = vec![
|
||||
ConversationItem::system("You are helpful."),
|
||||
ConversationItem::user("hi"),
|
||||
];
|
||||
inject_memory_reminder(&mut items, "Remember: user likes rust");
|
||||
if let ConversationItem::System(ref sys) = items[0] {
|
||||
assert!(sys.content.contains("Remember: user likes rust"));
|
||||
assert!(sys.content.starts_with("You are helpful."));
|
||||
}
|
||||
assert_eq!(items.len(), 2); // no new item added
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inject_memory_prepends_when_no_system() {
|
||||
let mut items = vec![ConversationItem::user("hi")];
|
||||
inject_memory_reminder(&mut items, "Remember: user likes rust");
|
||||
assert_eq!(items.len(), 2);
|
||||
assert!(matches!(&items[0], ConversationItem::System(_)));
|
||||
}
|
||||
|
||||
// -- image size-gated compaction tests --
|
||||
|
||||
/// A user message with a small fixed inline image.
|
||||
fn user_with_image(text: &str) -> ConversationItem {
|
||||
let mut item = ConversationItem::user(text);
|
||||
item.add_image("data:image/png;base64,iVBORw0KGgo=");
|
||||
item
|
||||
}
|
||||
|
||||
/// A user message carrying an inline image whose `data:` URL is exactly
|
||||
/// `url_bytes` long (must be >= the data-URL prefix length).
|
||||
fn user_with_image_of_bytes(text: &str, url_bytes: usize) -> ConversationItem {
|
||||
const PREFIX: &str = "data:image/png;base64,";
|
||||
let pad = url_bytes.saturating_sub(PREFIX.len());
|
||||
let mut item = ConversationItem::user(text);
|
||||
item.add_image(format!("{PREFIX}{}", "A".repeat(pad)));
|
||||
item
|
||||
}
|
||||
|
||||
fn has_image(item: &ConversationItem) -> bool {
|
||||
matches!(
|
||||
item,
|
||||
ConversationItem::User(u)
|
||||
if u.content.iter().any(|p| matches!(p, ContentPart::Image { .. }))
|
||||
)
|
||||
}
|
||||
|
||||
fn has_placeholder(item: &ConversationItem) -> bool {
|
||||
matches!(
|
||||
item,
|
||||
ConversationItem::User(u) if u.content.iter().any(|p| matches!(
|
||||
p,
|
||||
ContentPart::Text { text }
|
||||
if text.as_ref() == IMAGE_COMPACT_PLACEHOLDER
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
// Images are sized ~100 KB so the ~235 B placeholder that replaces an
|
||||
// evicted image is negligible: each eviction frees ~one image's bytes.
|
||||
const TEST_IMG_BYTES: usize = 100_000;
|
||||
|
||||
#[test]
|
||||
fn no_eviction_when_at_or_below_target() {
|
||||
// Multiple old image turns are *retained* when the body already fits —
|
||||
// the key behavior change from the old "strip everything but newest".
|
||||
let mut conv = vec![
|
||||
ConversationItem::system("sys"),
|
||||
user_with_image_of_bytes("first", TEST_IMG_BYTES),
|
||||
ConversationItem::assistant("a"),
|
||||
user_with_image_of_bytes("second", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("third", TEST_IMG_BYTES),
|
||||
];
|
||||
// current < target: nothing to do.
|
||||
compact_images_to_byte_budget(&mut conv, 300_000, 400_000);
|
||||
assert_eq!(conv.iter().filter(|i| has_image(i)).count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicts_oldest_until_under_target() {
|
||||
let mut conv = vec![
|
||||
user_with_image_of_bytes("oldest", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("middle", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("newest", TEST_IMG_BYTES),
|
||||
];
|
||||
// current 300k, target 250k: evicting the oldest (~100 KB) fits.
|
||||
compact_images_to_byte_budget(&mut conv, 300_000, 250_000);
|
||||
assert!(has_placeholder(&conv[0]), "oldest evicted");
|
||||
assert!(has_image(&conv[1]), "middle kept");
|
||||
assert!(has_image(&conv[2]), "newest kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicts_more_oldest_for_lower_target() {
|
||||
let mut conv = vec![
|
||||
user_with_image_of_bytes("oldest", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("middle", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("newest", TEST_IMG_BYTES),
|
||||
];
|
||||
// current 300k, target 150k: must drop the two oldest to fit.
|
||||
compact_images_to_byte_budget(&mut conv, 300_000, 150_000);
|
||||
assert!(has_placeholder(&conv[0]));
|
||||
assert!(has_placeholder(&conv[1]));
|
||||
assert!(has_image(&conv[2]), "newest kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eviction_reclaims_batch_to_low_water_mark() {
|
||||
// Mirror production: a body sitting just over the trigger, made of many
|
||||
// equal images, is reclaimed in one pass down to the low-water mark —
|
||||
// dropping a *batch* of the oldest, not just the one image needed to
|
||||
// clear the trigger. This is the hysteresis that keeps the prefix
|
||||
// cache-warm for the following turns.
|
||||
let img_bytes = 1_000_000usize; // ~1 MB url each
|
||||
let n = (IMAGE_COMPACT_TRIGGER_BYTES / img_bytes) + 2; // body just over trigger
|
||||
let mut conv: Vec<ConversationItem> = (0..n)
|
||||
.map(|i| user_with_image_of_bytes(&format!("i{i}"), img_bytes))
|
||||
.collect();
|
||||
let current = n * img_bytes;
|
||||
assert!(current > IMAGE_COMPACT_TRIGGER_BYTES);
|
||||
|
||||
compact_images_to_byte_budget(&mut conv, current, IMAGE_COMPACT_RECLAIM_TARGET_BYTES);
|
||||
|
||||
let kept = conv.iter().filter(|i| has_image(i)).count();
|
||||
let evicted = conv.iter().filter(|i| has_placeholder(i)).count();
|
||||
|
||||
// Clearing only the trigger would evict ~3 images; reclaiming to the
|
||||
// low-water mark (~half the ceiling) must evict far more.
|
||||
assert!(
|
||||
evicted > n / 4,
|
||||
"expected batch eviction to the low-water mark, only {evicted}/{n} evicted"
|
||||
);
|
||||
// Oldest-first stops at the mark, so the most recent image survives.
|
||||
assert!(kept > 0);
|
||||
assert!(
|
||||
has_image(conv.last().unwrap()),
|
||||
"most recent image must be retained"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicts_all_when_target_below_one_image() {
|
||||
let mut conv = vec![
|
||||
user_with_image_of_bytes("a", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("b", TEST_IMG_BYTES),
|
||||
];
|
||||
compact_images_to_byte_budget(&mut conv, 200_000, 50_000);
|
||||
assert!(has_placeholder(&conv[0]));
|
||||
assert!(has_placeholder(&conv[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eviction_keeps_newest_and_is_idempotent() {
|
||||
let mut conv = vec![
|
||||
user_with_image_of_bytes("i0", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("i1", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("i2", TEST_IMG_BYTES),
|
||||
user_with_image_of_bytes("i3", TEST_IMG_BYTES),
|
||||
];
|
||||
// current 400k, target 250k: drop the two oldest, keep the newest two.
|
||||
compact_images_to_byte_budget(&mut conv, 400_000, 250_000);
|
||||
assert!(has_placeholder(&conv[0]) && has_placeholder(&conv[1]));
|
||||
assert!(has_image(&conv[2]) && has_image(&conv[3]));
|
||||
|
||||
// Re-running with the now-smaller body is a no-op (sticky): the two
|
||||
// surviving images already fit.
|
||||
compact_images_to_byte_budget(&mut conv, 200_000, 250_000);
|
||||
assert!(has_placeholder(&conv[0]) && has_placeholder(&conv[1]));
|
||||
assert!(has_image(&conv[2]) && has_image(&conv[3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicted_image_uses_honest_placeholder() {
|
||||
let mut conv = vec![user_with_image_of_bytes("x", TEST_IMG_BYTES)];
|
||||
compact_images_to_byte_budget(&mut conv, 100_000, 10);
|
||||
assert!(has_placeholder(&conv[0]));
|
||||
}
|
||||
|
||||
// -- conversation_body_bytes tests --
|
||||
|
||||
#[test]
|
||||
fn conversation_body_bytes_empty_is_json_array() {
|
||||
// serde encodes an empty slice as "[]" (2 bytes).
|
||||
assert_eq!(conversation_body_bytes(&[]), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversation_body_bytes_matches_serde_json_exactly() {
|
||||
// The blank-and-add-URLs measurement must equal a full serde_json
|
||||
// encode byte-for-byte — including non-image content and string
|
||||
// escaping. The `"` in the system text is escaped by serde; the
|
||||
// measurement must account for it.
|
||||
let conv = vec![
|
||||
ConversationItem::system("system \"quoted\" prompt"),
|
||||
user_with_image("look"),
|
||||
ConversationItem::assistant("a longer assistant reply with text"),
|
||||
ConversationItem::user("plain follow-up turn"),
|
||||
];
|
||||
let expected = serde_json::to_vec(&conv).unwrap().len();
|
||||
assert_eq!(conversation_body_bytes(&conv), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversation_body_bytes_matches_serde_json_with_large_image() {
|
||||
// Exact even for a multi-KB base64 payload — the scan we deliberately
|
||||
// skip still lands on the same byte count.
|
||||
let conv = vec![user_with_image_of_bytes("big", 50_000)];
|
||||
let expected = serde_json::to_vec(&conv).unwrap().len();
|
||||
assert_eq!(conversation_body_bytes(&conv), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversation_body_bytes_small_image_is_below_trigger() {
|
||||
// A normal small inline image must not trip the 50 MB gate — the case
|
||||
// the cache-miss fix preserves.
|
||||
let conv = vec![
|
||||
user_with_image("old"),
|
||||
ConversationItem::assistant("reply"),
|
||||
ConversationItem::user("current"),
|
||||
];
|
||||
assert!(conversation_body_bytes(&conv) < IMAGE_COMPACT_TRIGGER_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversation_body_bytes_large_image_reaches_trigger() {
|
||||
let conv = vec![user_with_image_of_bytes("big", IMAGE_COMPACT_TRIGGER_BYTES)];
|
||||
assert!(conversation_body_bytes(&conv) >= IMAGE_COMPACT_TRIGGER_BYTES);
|
||||
}
|
||||
|
||||
// -- edge cases: exactness, boundaries, ordering --
|
||||
|
||||
#[test]
|
||||
fn body_bytes_parity_multi_image_unicode_escaping() {
|
||||
// The gate is only as correct as this equality. Exercise multiple
|
||||
// images in one turn, multibyte unicode (passed through, not escaped),
|
||||
// and chars serde *does* escape (`"`, `\`, control).
|
||||
let mut turn = ConversationItem::user("two pics 🚀 with \"quotes\" and \\ slash");
|
||||
turn.add_image("data:image/png;base64,AAAA");
|
||||
turn.add_image("data:image/png;base64,BBBBBB");
|
||||
let conv = vec![
|
||||
ConversationItem::system("sys 日本語 \t control"),
|
||||
turn,
|
||||
ConversationItem::assistant("reply"),
|
||||
ConversationItem::user("plain follow-up"),
|
||||
];
|
||||
assert_eq!(
|
||||
conversation_body_bytes(&conv),
|
||||
serde_json::to_vec(&conv).unwrap().len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_eviction_when_exactly_at_target() {
|
||||
// The no-op guard is `current <= target`; pin the inclusive boundary.
|
||||
let mut conv = vec![user_with_image_of_bytes("a", TEST_IMG_BYTES)];
|
||||
compact_images_to_byte_budget(&mut conv, 250_000, 250_000);
|
||||
assert!(has_image(&conv[0]), "exactly at target must not evict");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminates_when_placeholder_exceeds_image() {
|
||||
// Tiny images: each "saving" saturates to 0, but the loop must still
|
||||
// terminate and replace every image when the target is unreachable.
|
||||
let mut conv = vec![
|
||||
user_with_image_of_bytes("a", 40),
|
||||
user_with_image_of_bytes("b", 40),
|
||||
];
|
||||
compact_images_to_byte_budget(&mut conv, 1_000, 10);
|
||||
assert!(has_placeholder(&conv[0]) && has_placeholder(&conv[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicts_oldest_image_parts_first() {
|
||||
// `has_image`/`has_placeholder` are per-item, so count actual image
|
||||
// parts to verify oldest-first ordering across parts within a turn.
|
||||
fn image_parts(conv: &[ConversationItem]) -> usize {
|
||||
conv.iter()
|
||||
.filter_map(|i| match i {
|
||||
ConversationItem::User(u) => Some(u),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|u| u.content.iter())
|
||||
.filter(|p| matches!(p, ContentPart::Image { .. }))
|
||||
.count()
|
||||
}
|
||||
let mut newest = ConversationItem::user("newest turn");
|
||||
newest.add_image(format!(
|
||||
"data:image/png;base64,{}",
|
||||
"A".repeat(TEST_IMG_BYTES)
|
||||
));
|
||||
newest.add_image(format!(
|
||||
"data:image/png;base64,{}",
|
||||
"B".repeat(TEST_IMG_BYTES)
|
||||
));
|
||||
let mut conv = vec![user_with_image_of_bytes("oldest", TEST_IMG_BYTES), newest];
|
||||
assert_eq!(image_parts(&conv), 3);
|
||||
|
||||
// ~300k body, reclaim to 150k: drop the two oldest, keep the newest.
|
||||
compact_images_to_byte_budget(&mut conv, 300_000, 150_000);
|
||||
assert_eq!(image_parts(&conv), 1, "newest image survives");
|
||||
assert!(has_placeholder(&conv[0]), "oldest turn evicted");
|
||||
assert!(has_image(&conv[1]), "newest turn keeps an image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_remote_url_is_a_lower_bound_only() {
|
||||
// base64 `data:` URLs are exact; a remote URL with a JSON-escaped char
|
||||
// under-counts by the escape bytes. Pin that documented bound so the
|
||||
// measurement can't silently drift past it.
|
||||
let mut item = ConversationItem::user("");
|
||||
item.add_image(r#"https://example.com/a"b"#);
|
||||
let conv = vec![item];
|
||||
assert!(conversation_body_bytes(&conv) <= serde_json::to_vec(&conv).unwrap().len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Internal state types for the ChatStateActor.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use xai_grok_sampling_types::{
|
||||
ConversationItem, DanglingToolCallReason, SamplingConfig, TokenUsage,
|
||||
dedup_duplicate_tool_results, repair_dangling_tool_calls,
|
||||
};
|
||||
|
||||
use crate::types::Credentials;
|
||||
use crate::usage::UsageLedger;
|
||||
|
||||
/// Bytes/4 estimate of the system prompt portion of a [`ConversationItem`].
|
||||
/// Returns 0 for non-system items so callers can pipe through whatever they
|
||||
/// have without unwrapping.
|
||||
pub fn estimate_system_message_tokens(item: &ConversationItem) -> u64 {
|
||||
match item {
|
||||
ConversationItem::System(s) => xai_token_estimation::estimate_tokens(&s.content),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes/4 estimate of one tool definition (name + description + the
|
||||
/// JSON-serialized parameters).
|
||||
pub fn estimate_tool_definition_tokens(td: &xai_grok_sampling_types::ToolDefinition) -> u64 {
|
||||
let name_len = td.function.name.len();
|
||||
let desc_len = td.function.description.as_deref().map_or(0, |d| d.len());
|
||||
let params_len = td.function.parameters.to_string().len();
|
||||
((name_len + desc_len + params_len) as u64) / xai_token_estimation::BYTES_PER_TOKEN
|
||||
}
|
||||
|
||||
/// Sum [`estimate_tool_definition_tokens`] across a slice.
|
||||
pub fn estimate_tool_definitions_tokens(tds: &[xai_grok_sampling_types::ToolDefinition]) -> u64 {
|
||||
tds.iter().map(estimate_tool_definition_tokens).sum()
|
||||
}
|
||||
|
||||
/// Bytes/4 estimate for a single [`ConversationItem`].
|
||||
///
|
||||
/// Images are counted at [`xai_token_estimation::IMAGE_TOKEN_ESTIMATE`] each.
|
||||
/// Shared by [`estimate_conversation_tokens`] and [`estimate_messages_tokens`]
|
||||
/// so the per-variant arithmetic stays in one place.
|
||||
pub fn estimate_item_tokens(item: &ConversationItem) -> u64 {
|
||||
use xai_grok_sampling_types::ContentPart;
|
||||
match item {
|
||||
ConversationItem::System(s) => xai_token_estimation::estimate_tokens(&s.content),
|
||||
ConversationItem::User(u) => {
|
||||
let mut bytes: usize = 0;
|
||||
let mut images: u64 = 0;
|
||||
for p in &u.content {
|
||||
match p {
|
||||
ContentPart::Text { text } => bytes += text.len(),
|
||||
ContentPart::Image { .. } => images += 1,
|
||||
}
|
||||
}
|
||||
(bytes as u64) / xai_token_estimation::BYTES_PER_TOKEN
|
||||
+ xai_token_estimation::estimate_image_tokens(images)
|
||||
}
|
||||
ConversationItem::Assistant(a) => {
|
||||
let bytes = a.content.len()
|
||||
+ a.tool_calls
|
||||
.iter()
|
||||
.map(|tc| tc.arguments.len())
|
||||
.sum::<usize>();
|
||||
(bytes as u64) / xai_token_estimation::BYTES_PER_TOKEN
|
||||
}
|
||||
ConversationItem::ToolResult(tr) => xai_token_estimation::estimate_tokens(&tr.content),
|
||||
ConversationItem::BackendToolCall(b) => {
|
||||
xai_token_estimation::estimate_tokens(&b.text_summary())
|
||||
}
|
||||
ConversationItem::Reasoning(r) => {
|
||||
// Summary + content text follow the standard bytes-per-token
|
||||
// estimate; encrypted blobs are base64 and don't survive
|
||||
// tokenization 1:1, so estimate at len/4 as well.
|
||||
let text_bytes = xai_grok_sampling_types::reasoning_item_text(r).len();
|
||||
let enc_bytes = r.encrypted_content.as_deref().map(str::len).unwrap_or(0);
|
||||
((text_bytes + enc_bytes) as u64) / xai_token_estimation::BYTES_PER_TOKEN
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Estimate token footprint: text bytes / 4, images at the per-image
|
||||
/// constant defined by [`xai_token_estimation::IMAGE_TOKEN_ESTIMATE`].
|
||||
pub fn estimate_conversation_tokens(items: &[ConversationItem]) -> u64 {
|
||||
items.iter().map(estimate_item_tokens).sum()
|
||||
}
|
||||
|
||||
/// grok-build's [`ItemTokenCounter`](xai_grok_compaction::ItemTokenCounter)
|
||||
/// for the shared compaction engine: the bytes/4 estimate grok-build already
|
||||
/// uses to drive its compaction triggers, exposed through the seam so the
|
||||
/// shared budgeting math gets the *same* trusted count.
|
||||
///
|
||||
/// Where another host plugs a real BPE tokenizer into the same seam,
|
||||
/// grok-build estimates instead, reusing [`estimate_item_tokens`] so the
|
||||
/// per-variant arithmetic (images, reasoning blobs, tool-call args) stays in
|
||||
/// one place.
|
||||
pub struct EstimatedItemTokenCounter;
|
||||
|
||||
impl xai_grok_compaction::ItemTokenCounter<ConversationItem> for EstimatedItemTokenCounter {
|
||||
fn count_item_tokens(&self, item: &ConversationItem) -> u32 {
|
||||
// The estimate is a `u64`; a single item never approaches `u32::MAX`
|
||||
// tokens, but saturate rather than wrap if one somehow does.
|
||||
estimate_item_tokens(item).try_into().unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes/4 estimate of every non-system item in `items`.
|
||||
pub fn estimate_messages_tokens(items: &[ConversationItem]) -> u64 {
|
||||
items
|
||||
.iter()
|
||||
.filter(|i| !matches!(i, ConversationItem::System(_)))
|
||||
.map(estimate_item_tokens)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Internal mutable state for the ChatStateActor.
|
||||
///
|
||||
/// All fields are owned exclusively by the actor task — no locks needed.
|
||||
pub(crate) struct ChatState {
|
||||
/// The full conversation history.
|
||||
pub conversation: Vec<ConversationItem>,
|
||||
/// Current sampling configuration (model, context window, etc.).
|
||||
pub sampling_config: SamplingConfig,
|
||||
/// Current prompt index (incremented per user turn).
|
||||
pub prompt_index: usize,
|
||||
/// Cached prompt texts for rewind preview.
|
||||
pub prompt_texts: Vec<String>,
|
||||
/// Accumulated token usage.
|
||||
pub total_tokens: u64,
|
||||
/// Timestamp when the current stream started (epoch ms).
|
||||
pub stream_start_ms: Option<i64>,
|
||||
/// Timestamp when the current turn started (epoch ms).
|
||||
pub turn_start_ms: Option<i64>,
|
||||
/// File paths the agent has edited.
|
||||
pub agent_edited_paths: BTreeSet<String>,
|
||||
/// Prompt index at which the last compaction occurred.
|
||||
pub last_compaction_prompt_index: Option<usize>,
|
||||
/// Opaque credential secrets (api key, optional extra auth, client version).
|
||||
/// Stored opaquely — the actor never interprets them.
|
||||
pub credentials: Credentials,
|
||||
/// Bytes/4 estimate of tokens added since the last `record_token_usage`.
|
||||
/// Used by `check_preflight_overflow` to detect context window overflows
|
||||
/// between model responses.
|
||||
pub estimated_tokens_since_model: u64,
|
||||
/// Bytes/4 estimate of the conversation as of the last `record_token_usage`
|
||||
/// (or last reseed). `total_tokens − estimate_at_last_response` is the
|
||||
/// provider-side overhead carried across compaction.
|
||||
pub estimate_at_last_response: u64,
|
||||
/// Per-turn token usage from the most recent model response.
|
||||
/// Stashed by `record_last_turn_usage()` and read at `PromptResponse`
|
||||
/// construction to enrich `_meta` with `inputTokens` / `outputTokens` /
|
||||
/// `cachedReadTokens`. `None` means no model turn has completed yet
|
||||
/// in this session (or this is a freshly restored session that did not
|
||||
/// persist last_turn_usage). Always overwritten by the most recent turn —
|
||||
/// historical turns are not retained here.
|
||||
pub last_turn_usage: Option<TokenUsage>,
|
||||
/// Billing for the open prompt (cleared on next prompt; not persisted).
|
||||
pub prompt_usage: Option<UsageLedger>,
|
||||
/// Lifetime session billing (not persisted).
|
||||
pub session_usage: UsageLedger,
|
||||
/// Offset-based turn capture state. `Some` = capture active, `None` = inactive.
|
||||
/// Cleared on `TakeTurnMessages` (consumed), `BeginTurnCapture` (new turn),
|
||||
/// and `TruncateToPromptIndex` (rewind abandons the turn).
|
||||
pub(super) turn_capture: Option<TurnCaptureState>,
|
||||
/// Accumulator for the in-progress harness-subagent trace phase (the goal
|
||||
/// planner at `setup_goal`, or one verifier skeptic panel). Synthetic
|
||||
/// `task` pairs recorded via `AppendHarnessTraceItems` land here;
|
||||
/// `FlushHarnessTraceTurn` seals the accumulated items into one entry of
|
||||
/// `harness_trace_turns`. Independent of `turn_capture` (the planner runs
|
||||
/// ahead of `BeginTurnCapture`) and never enters the live `conversation`.
|
||||
pub(super) harness_trace_buffer: Vec<ConversationItem>,
|
||||
/// Sealed harness trace turns awaiting drain by the agent, which uploads
|
||||
/// each as its own sibling `turn_{N}` artifact so orchestrators can
|
||||
/// discover harness subagents via their `<subagent_result>` footer.
|
||||
/// Drained by `TakeHarnessTraceTurns` at the end of the user-facing turn.
|
||||
pub(super) harness_trace_turns: Vec<Vec<ConversationItem>>,
|
||||
}
|
||||
|
||||
/// Tracks which conversation items belong to the current turn without
|
||||
/// cloning every pushed item into a side buffer.
|
||||
///
|
||||
/// Instead of duplicating each `ConversationItem` on push, we record the
|
||||
/// conversation length at capture start (`turn_start_offset`). At take
|
||||
/// time, `conversation[turn_start_offset..]` gives us the turn's items
|
||||
/// with a single bulk clone.
|
||||
///
|
||||
/// When `replace_conversation` or `restore_snapshot` replaces the vec
|
||||
/// mid-turn, we snapshot `conversation[turn_start_offset..]` into
|
||||
/// `pre_replacement_messages` before the old vec is dropped, and reset
|
||||
/// the offset to the new vec's length.
|
||||
pub(super) struct TurnCaptureState {
|
||||
/// Index into `conversation` where this turn's messages start.
|
||||
pub turn_start_offset: usize,
|
||||
/// Messages saved from before a conversation replacement (compaction,
|
||||
/// snapshot restore). Extended (not replaced) if multiple replacements
|
||||
/// occur in one turn.
|
||||
pub pre_replacement_messages: Vec<ConversationItem>,
|
||||
/// Whether compaction occurred during this capture.
|
||||
pub compaction_occurred: bool,
|
||||
}
|
||||
|
||||
impl ChatState {
|
||||
/// Create a new `ChatState` with the given conversation and sampling config,
|
||||
/// all other fields defaulted.
|
||||
///
|
||||
/// Repairs any dangling tool calls in the initial conversation. This handles
|
||||
/// the race condition where the process was killed mid-tool-execution and
|
||||
/// `chat_history.jsonl` has an assistant message with tool call IDs that
|
||||
/// lack matching `ToolResult` entries. Without this, the in-memory state
|
||||
/// would carry broken conversation history until the next `build_request`.
|
||||
pub fn new(mut conversation: Vec<ConversationItem>, sampling_config: SamplingConfig) -> Self {
|
||||
let deduped = dedup_duplicate_tool_results(&mut conversation);
|
||||
if deduped > 0 {
|
||||
tracing::info!(
|
||||
deduped_count = deduped,
|
||||
"Removed duplicate tool results in initial conversation"
|
||||
);
|
||||
}
|
||||
let repaired =
|
||||
repair_dangling_tool_calls(&mut conversation, DanglingToolCallReason::UserCancelled);
|
||||
if repaired > 0 {
|
||||
tracing::info!(
|
||||
repaired_count = repaired,
|
||||
"Repaired dangling tool calls in initial conversation (likely from a previous crash)"
|
||||
);
|
||||
}
|
||||
|
||||
let initial_tokens = estimate_conversation_tokens(&conversation);
|
||||
|
||||
Self {
|
||||
conversation,
|
||||
sampling_config,
|
||||
prompt_index: 0,
|
||||
prompt_texts: Vec::new(),
|
||||
total_tokens: initial_tokens,
|
||||
stream_start_ms: None,
|
||||
turn_start_ms: None,
|
||||
agent_edited_paths: BTreeSet::new(),
|
||||
last_compaction_prompt_index: None,
|
||||
credentials: Credentials::default(),
|
||||
estimated_tokens_since_model: 0,
|
||||
estimate_at_last_response: initial_tokens,
|
||||
last_turn_usage: None,
|
||||
prompt_usage: None,
|
||||
session_usage: UsageLedger::default(),
|
||||
turn_capture: None,
|
||||
harness_trace_buffer: Vec::new(),
|
||||
harness_trace_turns: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seal the items accumulated since the last flush into one harness trace
|
||||
/// turn. No-op when nothing was recorded since the last seal. Shared by the
|
||||
/// explicit `FlushHarnessTraceTurn` (one call per harness phase) and the
|
||||
/// defensive seal in `TakeHarnessTraceTurns`.
|
||||
pub(super) fn seal_harness_trace_turn(&mut self) {
|
||||
if !self.harness_trace_buffer.is_empty() {
|
||||
let turn = std::mem::take(&mut self.harness_trace_buffer);
|
||||
self.harness_trace_turns.push(turn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_sampling_config() -> SamplingConfig {
|
||||
SamplingConfig {
|
||||
base_url: "https://api.example.com".to_string(),
|
||||
model: "test-model".to_string(),
|
||||
max_completion_tokens: None,
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
api_backend: Default::default(),
|
||||
extra_headers: Default::default(),
|
||||
context_window: std::num::NonZeroU64::new(128_000).unwrap(),
|
||||
reasoning_effort: None,
|
||||
stream_tool_calls: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimated_item_token_counter_matches_estimate_item_tokens() {
|
||||
use xai_grok_compaction::ItemTokenCounter;
|
||||
|
||||
let counter = EstimatedItemTokenCounter;
|
||||
let items = vec![
|
||||
ConversationItem::system("you are a helpful assistant"),
|
||||
ConversationItem::user("fix the login bug in auth.rs"),
|
||||
ConversationItem::assistant("let me look at the file"),
|
||||
ConversationItem::tool_result("tc1", "fn login() {}"),
|
||||
];
|
||||
for item in &items {
|
||||
assert_eq!(
|
||||
u64::from(counter.count_item_tokens(item)),
|
||||
estimate_item_tokens(item),
|
||||
"counter must report the same trusted count as estimate_item_tokens"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_state_has_correct_defaults() {
|
||||
let state = ChatState::new(vec![], test_sampling_config());
|
||||
assert_eq!(state.prompt_index, 0);
|
||||
assert_eq!(state.total_tokens, 0); // empty conversation → 0
|
||||
assert!(state.conversation.is_empty());
|
||||
assert!(state.agent_edited_paths.is_empty());
|
||||
assert!(state.prompt_texts.is_empty());
|
||||
assert!(state.stream_start_ms.is_none());
|
||||
assert!(state.turn_start_ms.is_none());
|
||||
assert!(state.last_compaction_prompt_index.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_state_preserves_initial_conversation() {
|
||||
let items = vec![
|
||||
ConversationItem::system("sys"),
|
||||
ConversationItem::user("hello"),
|
||||
];
|
||||
let state = ChatState::new(items, test_sampling_config());
|
||||
assert_eq!(state.conversation.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_state_estimates_tokens_from_conversation() {
|
||||
// 4000 bytes of text per item, bytes / 4 = 1000 tokens each
|
||||
let items = vec![
|
||||
ConversationItem::system("x".repeat(4000).as_str()),
|
||||
ConversationItem::user("y".repeat(4000).as_str()),
|
||||
ConversationItem::assistant("z".repeat(4000).as_str()),
|
||||
ConversationItem::tool_result("call-1", "w".repeat(4000).as_str()),
|
||||
];
|
||||
let state = ChatState::new(items, test_sampling_config());
|
||||
assert_eq!(state.total_tokens, 4000); // 4 * (4000/4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_system_message_tokens_only_counts_system_items() {
|
||||
let sys = ConversationItem::system("a".repeat(400));
|
||||
assert_eq!(estimate_system_message_tokens(&sys), 100);
|
||||
let user = ConversationItem::user("hello");
|
||||
assert_eq!(estimate_system_message_tokens(&user), 0);
|
||||
let asst = ConversationItem::assistant("hi");
|
||||
assert_eq!(estimate_system_message_tokens(&asst), 0);
|
||||
let tr = ConversationItem::tool_result("call-1", "x".repeat(4000).as_str());
|
||||
assert_eq!(estimate_system_message_tokens(&tr), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_tool_definition_tokens_counts_name_desc_params() {
|
||||
// Empty parameters serialize to "null" (4 bytes) in the JSON-string len
|
||||
let td = xai_grok_sampling_types::ToolDefinition::function(
|
||||
"search",
|
||||
Some("find a file"),
|
||||
serde_json::json!({}),
|
||||
);
|
||||
// name=6 + desc=11 + params=`{}`.len()=2 = 19, /4 = 4
|
||||
assert_eq!(estimate_tool_definition_tokens(&td), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_messages_tokens_excludes_system_and_sums_rest() {
|
||||
// 4000 bytes per item -> 1000 tokens each.
|
||||
let items = vec![
|
||||
ConversationItem::system("x".repeat(4000).as_str()),
|
||||
ConversationItem::user("y".repeat(4000).as_str()),
|
||||
ConversationItem::assistant("z".repeat(4000).as_str()),
|
||||
ConversationItem::tool_result("call-1", "w".repeat(4000).as_str()),
|
||||
];
|
||||
// Total = 4000 (4 items * 1000), system = 1000, messages = 3000.
|
||||
assert_eq!(estimate_conversation_tokens(&items), 4000);
|
||||
assert_eq!(estimate_messages_tokens(&items), 3000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_messages_tokens_zero_when_only_system() {
|
||||
let items = vec![ConversationItem::system("x".repeat(4000).as_str())];
|
||||
assert_eq!(estimate_messages_tokens(&items), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_messages_tokens_zero_for_empty() {
|
||||
assert_eq!(estimate_messages_tokens(&[]), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_tool_definitions_tokens_sums_across_slice() {
|
||||
let a = xai_grok_sampling_types::ToolDefinition::function(
|
||||
"a",
|
||||
None::<&str>,
|
||||
serde_json::json!({}),
|
||||
);
|
||||
let b = xai_grok_sampling_types::ToolDefinition::function(
|
||||
"b",
|
||||
None::<&str>,
|
||||
serde_json::json!({}),
|
||||
);
|
||||
let single = estimate_tool_definition_tokens(&a);
|
||||
assert_eq!(estimate_tool_definitions_tokens(&[a, b]), single * 2);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,495 @@
|
||||
//! Commands sent to the ChatStateActor.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use tokio::sync::oneshot;
|
||||
use xai_grok_sampling_types::{
|
||||
ConversationItem, ConversationRequest, DanglingToolCallReason, SamplingConfig, TokenUsage,
|
||||
ToolSpec, TraceContext,
|
||||
};
|
||||
|
||||
use crate::types::{
|
||||
AutoCompactTrigger, ChatStateSnapshot, ConversationCounts, Credentials, NotificationMeta,
|
||||
TurnCapture,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ModelMetadata {
|
||||
pub resolved_model_id: Option<String>,
|
||||
pub model_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
/// Refusal reply for [`ChatStateCommand::RepairHistory`]: a turn was in
|
||||
/// flight, and in-flight tool calls must not be treated as dangling.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RepairHistoryBlocked;
|
||||
|
||||
impl std::fmt::Display for RepairHistoryBlocked {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"cannot repair history while a turn is in flight; stop the turn first"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RepairHistoryBlocked {}
|
||||
|
||||
/// Commands sent to the ChatStateActor via mpsc channel.
|
||||
pub enum ChatStateCommand {
|
||||
// ═══ Mutations (fire-and-forget) ═══
|
||||
/// Push a user message into the conversation.
|
||||
PushUserMessage { item: ConversationItem },
|
||||
|
||||
/// Push a user message and acknowledge once the chat-state actor has
|
||||
/// accepted and processed it.
|
||||
PushUserMessageAndAck {
|
||||
item: ConversationItem,
|
||||
reply: oneshot::Sender<()>,
|
||||
},
|
||||
|
||||
/// Push a user message with an explicit dangling-repair reason.
|
||||
PushUserMessageWithRepairReason {
|
||||
item: ConversationItem,
|
||||
reason: DanglingToolCallReason,
|
||||
},
|
||||
|
||||
/// Record the assistant's response (text + tool calls).
|
||||
PushAssistantResponse { item: ConversationItem },
|
||||
|
||||
/// Record a tool result.
|
||||
PushToolResult { item: ConversationItem },
|
||||
|
||||
/// Record accumulated token usage from a streaming response.
|
||||
RecordTokenUsage { total_tokens: u64 },
|
||||
|
||||
/// Stash the per-turn `TokenUsage` from the most recent model response.
|
||||
/// Overwrites any previously stashed value.
|
||||
RecordLastTurnUsage { usage: TokenUsage },
|
||||
|
||||
RecordModelCallUsage {
|
||||
model_id: Option<String>,
|
||||
usage: TokenUsage,
|
||||
api_duration_ms: Option<u64>,
|
||||
cost_usd_ticks: Option<i64>,
|
||||
},
|
||||
|
||||
/// Subagent usage into session (and prompt when attributable). Replies when applied.
|
||||
RecordSubagentUsage {
|
||||
by_model: Vec<(String, crate::usage::UsageTotals)>,
|
||||
attribute_to_prompt: bool,
|
||||
/// Nested subagent bill may under-count.
|
||||
incomplete: bool,
|
||||
reply: oneshot::Sender<()>,
|
||||
},
|
||||
|
||||
/// Mark open prompt and/or session ledgers incomplete.
|
||||
MarkUsageIncomplete {
|
||||
prompt: bool,
|
||||
session: bool,
|
||||
reply: oneshot::Sender<()>,
|
||||
},
|
||||
|
||||
/// Increment prompt_index (called at start of each user turn).
|
||||
IncrementPromptIndex,
|
||||
|
||||
/// Update the sampling config (e.g., model switch).
|
||||
UpdateSamplingConfig { config: SamplingConfig },
|
||||
|
||||
/// Track that the agent edited a file path.
|
||||
RecordAgentEditedPath { path: String },
|
||||
|
||||
/// Record stream timing metadata.
|
||||
RecordStreamStart { timestamp_ms: i64 },
|
||||
|
||||
/// Record turn timing metadata.
|
||||
RecordTurnStart { timestamp_ms: i64 },
|
||||
|
||||
/// Replace conversation history.
|
||||
ReplaceConversation {
|
||||
items: Vec<ConversationItem>,
|
||||
is_compaction: bool,
|
||||
},
|
||||
|
||||
/// Out-of-band history repair (`x.ai/session/repair`): run
|
||||
/// [`crate::compaction_utils::repair_history`] and persist when changed;
|
||||
/// `dry_run` only reports.
|
||||
///
|
||||
/// `turn_active` (the session's shared flag, set at turn start BEFORE the
|
||||
/// turn pushes anything here) is re-checked inside the command handler:
|
||||
/// a caller-side check alone races turn start, whereas at processing time
|
||||
/// the command is either refused or runs on pre-turn state with the
|
||||
/// turn's pushes serialized after it.
|
||||
RepairHistory {
|
||||
dry_run: bool,
|
||||
turn_active: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||
reply: oneshot::Sender<
|
||||
Result<crate::compaction_utils::HistoryRepairReport, RepairHistoryBlocked>,
|
||||
>,
|
||||
},
|
||||
|
||||
/// Atomically align the leading `System` message with `prompt` (inserting
|
||||
/// one if absent), persisting the conversation. Executed inside the actor so
|
||||
/// it serializes with concurrent turn pushes (`PushAssistantResponse` /
|
||||
/// `PushToolResult`) — a mid-turn reconnect cannot lose those updates the
|
||||
/// way a read-modify-write via `GetConversation` + `ReplaceConversation`
|
||||
/// would. Replies `true` iff the conversation changed (no-op when the head
|
||||
/// already matches modulo trailing newlines). A changed head goes through
|
||||
/// `replace_conversation`, which re-bases `total_tokens` to a fresh static
|
||||
/// estimate — acceptable because a changed head invalidates the KV prefix
|
||||
/// anyway.
|
||||
ReplaceSystemHead {
|
||||
prompt: String,
|
||||
reply: oneshot::Sender<bool>,
|
||||
},
|
||||
|
||||
/// Cache prompt text for rewind preview.
|
||||
CachePromptText { text: String },
|
||||
|
||||
/// Record compaction boundary for rewind.
|
||||
RecordCompactionAt { prompt_index: usize },
|
||||
|
||||
/// Flush pending persistence writes to disk (end of turn).
|
||||
Flush,
|
||||
|
||||
/// Update opaque credential secrets held by the actor.
|
||||
UpdateCredentials { credentials: Credentials },
|
||||
|
||||
/// Restore from a snapshot.
|
||||
RestoreSnapshot(Box<ChatStateSnapshot>),
|
||||
|
||||
/// Start capturing turn messages. Clears any previous buffer.
|
||||
BeginTurnCapture,
|
||||
|
||||
/// Append synthetic `task` pairs for a harness-spawned subagent (goal
|
||||
/// planner / verifier skeptic) to the in-progress harness trace phase.
|
||||
/// Accumulated independently of the live `conversation` and of
|
||||
/// `turn_capture`; sealed into a standalone trace turn by
|
||||
/// `FlushHarnessTraceTurn`.
|
||||
AppendHarnessTraceItems { items: Vec<ConversationItem> },
|
||||
|
||||
/// Seal the harness items accumulated since the last flush into one
|
||||
/// standalone trace turn. Issued once per harness phase (after the planner,
|
||||
/// after each verifier panel). No-op when nothing was recorded.
|
||||
FlushHarnessTraceTurn,
|
||||
|
||||
/// Repair dangling tool calls after a harness-initiated halt.
|
||||
RepairDanglingAfterHarnessHalt { class: &'static str },
|
||||
|
||||
// ═══ Queries (request/response via oneshot) ═══
|
||||
/// Build a ConversationRequest ready to send to the API.
|
||||
/// Clones the conversation, prunes old tool results, repairs dangling
|
||||
/// tool calls, injects memory reminder, and assembles the request.
|
||||
BuildConversationRequest {
|
||||
tool_definitions: Vec<ToolSpec>,
|
||||
memory_reminder: Option<String>,
|
||||
persist_memory_reminder: bool,
|
||||
trace: Option<Box<dyn TraceContext>>,
|
||||
conv_id: String,
|
||||
req_id: String,
|
||||
reply: oneshot::Sender<ConversationRequest>,
|
||||
},
|
||||
|
||||
/// Get a clone of the full conversation.
|
||||
GetConversation {
|
||||
reply: oneshot::Sender<Vec<ConversationItem>>,
|
||||
},
|
||||
|
||||
/// Get current prompt index.
|
||||
GetPromptIndex { reply: oneshot::Sender<usize> },
|
||||
|
||||
/// Get the prompt index at which the last compaction occurred.
|
||||
/// `Some` means the context currently holds a compaction summary.
|
||||
GetLastCompactionPromptIndex {
|
||||
reply: oneshot::Sender<Option<usize>>,
|
||||
},
|
||||
|
||||
/// Get total accumulated tokens.
|
||||
GetTotalTokens { reply: oneshot::Sender<u64> },
|
||||
|
||||
/// Retrieve the most recent stashed per-turn `TokenUsage`. Returns
|
||||
/// `None` until at least one `RecordLastTurnUsage` has been processed.
|
||||
GetLastTurnUsage {
|
||||
reply: oneshot::Sender<Option<TokenUsage>>,
|
||||
},
|
||||
|
||||
GetPromptUsage {
|
||||
reply: oneshot::Sender<Option<crate::usage::UsageLedger>>,
|
||||
},
|
||||
|
||||
GetSessionUsage {
|
||||
reply: oneshot::Sender<crate::usage::UsageLedger>,
|
||||
},
|
||||
|
||||
/// `total_tokens` + bytes/4 delta from tool results since last model response.
|
||||
GetEstimatedTotalTokens { reply: oneshot::Sender<u64> },
|
||||
|
||||
/// Bytes/4 estimate of all non-system conversation items.
|
||||
GetEstimatedMessagesTokens { reply: oneshot::Sender<u64> },
|
||||
|
||||
/// Get sampling config.
|
||||
GetSamplingConfig {
|
||||
reply: oneshot::Sender<SamplingConfig>,
|
||||
},
|
||||
|
||||
/// Get the set of agent-edited file paths.
|
||||
GetAgentEditedPaths {
|
||||
reply: oneshot::Sender<BTreeSet<String>>,
|
||||
},
|
||||
|
||||
/// Get notification meta (timing info).
|
||||
GetNotificationMeta {
|
||||
reply: oneshot::Sender<NotificationMeta>,
|
||||
},
|
||||
|
||||
/// Snapshot state for forking or rewind.
|
||||
Snapshot {
|
||||
reply: oneshot::Sender<ChatStateSnapshot>,
|
||||
},
|
||||
|
||||
/// Truncate conversation to a target prompt index (for rewind).
|
||||
TruncateToPromptIndex {
|
||||
target_prompt_index: usize,
|
||||
reply: oneshot::Sender<()>,
|
||||
},
|
||||
|
||||
/// Check if auto-compact is needed (returns token info).
|
||||
CheckAutoCompactNeeded {
|
||||
threshold_percent: u8,
|
||||
reply: oneshot::Sender<Option<AutoCompactTrigger>>,
|
||||
},
|
||||
|
||||
/// Get credential secrets.
|
||||
GetCredentials { reply: oneshot::Sender<Credentials> },
|
||||
|
||||
GetLastModelMetadata {
|
||||
reply: oneshot::Sender<ModelMetadata>,
|
||||
},
|
||||
|
||||
/// Take the accumulated turn messages and end the capture.
|
||||
/// Returns `None` if no capture was active.
|
||||
TakeTurnMessages {
|
||||
reply: oneshot::Sender<Option<TurnCapture>>,
|
||||
},
|
||||
|
||||
/// Drain the sealed harness trace turns (goal planner + verifier panels).
|
||||
/// Each `Vec` is one turn's synthetic `task` pairs, uploaded by the agent
|
||||
/// as its own sibling `turn_{N}` artifact. Seals a trailing un-flushed
|
||||
/// accumulator before draining.
|
||||
TakeHarnessTraceTurns {
|
||||
reply: oneshot::Sender<Vec<Vec<ConversationItem>>>,
|
||||
},
|
||||
|
||||
// ═══ Narrow targeted queries (avoid full-conversation clone) ═══
|
||||
/// Get the number of items in the conversation.
|
||||
/// Cheaper than `GetConversation` when only the length is needed.
|
||||
GetConversationLen { reply: oneshot::Sender<usize> },
|
||||
|
||||
/// Whether any assistant tool call lacks a matching `ToolResult` (i.e. the
|
||||
/// dangling-tool-call repair would fire on the next request build).
|
||||
/// Cheaper than `GetConversation` when only this predicate is needed.
|
||||
HasDanglingToolCalls { reply: oneshot::Sender<bool> },
|
||||
|
||||
/// Get the text content of the last assistant message with non-empty text.
|
||||
/// Returns `None` if no such message exists.
|
||||
/// Cheaper than `GetConversation` when only the final assistant response is needed.
|
||||
GetLastAssistantText {
|
||||
reply: oneshot::Sender<Option<String>>,
|
||||
},
|
||||
|
||||
/// Like `GetLastAssistantText`, but bounded to the current prompt turn:
|
||||
/// returns `None` when the turn produced no assistant text (the walk stops
|
||||
/// at the first turn-starting user item).
|
||||
GetLastAssistantTextInTurn {
|
||||
reply: oneshot::Sender<Option<String>>,
|
||||
},
|
||||
|
||||
/// Get the text of the first `Text` content part in the first `User` message.
|
||||
/// Returns `None` if the conversation has no user messages or the first user
|
||||
/// message has no text content part.
|
||||
/// Cheaper than `GetConversation` when only the initial user query is needed.
|
||||
GetFirstUserText {
|
||||
reply: oneshot::Sender<Option<String>>,
|
||||
},
|
||||
|
||||
/// Get a single conversation item by index (0-based).
|
||||
/// Returns `None` if the index is out of bounds.
|
||||
/// Cheaper than `GetConversation` when only one item is needed.
|
||||
GetConversationItemAt {
|
||||
index: usize,
|
||||
reply: oneshot::Sender<Option<ConversationItem>>,
|
||||
},
|
||||
|
||||
/// Get the processed text of the last user query (metadata tags stripped).
|
||||
///
|
||||
/// Equivalent to `extract_last_user_query(&conversation)` but without
|
||||
/// cloning the full conversation on the caller side.
|
||||
GetLastUserQueryText {
|
||||
reply: oneshot::Sender<Option<String>>,
|
||||
},
|
||||
|
||||
/// Get item counts for the conversation by role.
|
||||
///
|
||||
/// Returns a `ConversationCounts` struct without cloning any items.
|
||||
/// Suitable for telemetry / logging that only needs totals.
|
||||
GetConversationCounts {
|
||||
reply: oneshot::Sender<ConversationCounts>,
|
||||
},
|
||||
|
||||
/// Get the first `System` message in the conversation, if any.
|
||||
///
|
||||
/// Cheaper than `GetConversation` when only the system prompt is needed
|
||||
/// (e.g. for compaction setup or error guards).
|
||||
GetSystemMessage {
|
||||
reply: oneshot::Sender<Option<ConversationItem>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Verify that every command variant is constructible (compile-time check).
|
||||
#[test]
|
||||
fn command_variants_are_constructible() {
|
||||
// Mutations
|
||||
let _ = ChatStateCommand::PushUserMessage {
|
||||
item: ConversationItem::user("hello"),
|
||||
};
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::PushUserMessageAndAck {
|
||||
item: ConversationItem::user("hello"),
|
||||
reply: tx,
|
||||
};
|
||||
let _ = ChatStateCommand::PushAssistantResponse {
|
||||
item: ConversationItem::assistant("hi"),
|
||||
};
|
||||
let _ = ChatStateCommand::PushToolResult {
|
||||
item: ConversationItem::tool_result("call-1", "result"),
|
||||
};
|
||||
let _ = ChatStateCommand::RecordTokenUsage { total_tokens: 100 };
|
||||
let _ = ChatStateCommand::IncrementPromptIndex;
|
||||
let _ = ChatStateCommand::UpdateSamplingConfig {
|
||||
config: SamplingConfig {
|
||||
base_url: String::new(),
|
||||
model: String::new(),
|
||||
max_completion_tokens: None,
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
api_backend: Default::default(),
|
||||
extra_headers: Default::default(),
|
||||
context_window: std::num::NonZeroU64::new(128_000).unwrap(),
|
||||
reasoning_effort: None,
|
||||
stream_tool_calls: None,
|
||||
},
|
||||
};
|
||||
let _ = ChatStateCommand::RecordAgentEditedPath {
|
||||
path: "src/main.rs".to_string(),
|
||||
};
|
||||
let _ = ChatStateCommand::RecordStreamStart {
|
||||
timestamp_ms: 12345,
|
||||
};
|
||||
let _ = ChatStateCommand::RecordTurnStart {
|
||||
timestamp_ms: 12345,
|
||||
};
|
||||
let _ = ChatStateCommand::ReplaceConversation {
|
||||
items: vec![],
|
||||
is_compaction: false,
|
||||
};
|
||||
let _ = ChatStateCommand::CachePromptText {
|
||||
text: "prompt".to_string(),
|
||||
};
|
||||
let _ = ChatStateCommand::RecordCompactionAt { prompt_index: 0 };
|
||||
let _ = ChatStateCommand::Flush;
|
||||
|
||||
// Queries
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetConversation { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetPromptIndex { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetLastCompactionPromptIndex { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetTotalTokens { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetEstimatedTotalTokens { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetSamplingConfig { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetAgentEditedPaths { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::BuildConversationRequest {
|
||||
tool_definitions: vec![],
|
||||
memory_reminder: None,
|
||||
persist_memory_reminder: false,
|
||||
trace: None,
|
||||
conv_id: String::new(),
|
||||
req_id: String::new(),
|
||||
reply: tx,
|
||||
};
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetNotificationMeta { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::Snapshot { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::TruncateToPromptIndex {
|
||||
target_prompt_index: 0,
|
||||
reply: tx,
|
||||
};
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::CheckAutoCompactNeeded {
|
||||
threshold_percent: 85,
|
||||
reply: tx,
|
||||
};
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetLastModelMetadata { reply: tx };
|
||||
|
||||
let _ = ChatStateCommand::BeginTurnCapture;
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::TakeTurnMessages { reply: tx };
|
||||
|
||||
// Narrow targeted queries
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetConversationLen { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetLastAssistantText { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetLastAssistantTextInTurn { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetFirstUserText { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetConversationItemAt {
|
||||
index: 0,
|
||||
reply: tx,
|
||||
};
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetLastUserQueryText { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetConversationCounts { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetSystemMessage { reply: tx };
|
||||
|
||||
let (tx, _rx) = oneshot::channel();
|
||||
let _ = ChatStateCommand::GetEstimatedMessagesTokens { reply: tx };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Compaction mode — how much structure the model gets to recover detail the
|
||||
//! lossy summary dropped. In `xai-chat-state` so flag resolution and the
|
||||
//! transcript-hint builder share one definition.
|
||||
|
||||
use crate::compaction_transcript::CompactionDetail;
|
||||
|
||||
/// How compaction exposes pre-compaction history to the model afterwards.
|
||||
/// `Segments` carries its verbatim detail level inline, since detail is
|
||||
/// meaningful only there.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, strum::Display)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum CompactionMode {
|
||||
/// Summary only — no pointer back to pre-compaction history. Default.
|
||||
#[default]
|
||||
Summary,
|
||||
/// Summary + pointer to the full raw `updates.jsonl`.
|
||||
Transcript,
|
||||
/// Summary + a `compaction/` folder of clean per-segment markdown.
|
||||
Segments(CompactionDetail),
|
||||
}
|
||||
|
||||
impl CompactionMode {
|
||||
/// Parse the mode word (case-insensitive); unknown → `None` so the caller
|
||||
/// falls back. `segments` gets the default detail — callers override it via
|
||||
/// [`CompactionMode::with_segment_detail`] once detail is resolved.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"summary" => Some(Self::Summary),
|
||||
"transcript" => Some(Self::Transcript),
|
||||
"segments" => Some(Self::Segments(CompactionDetail::default())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the detail level if this is `Segments`, else unchanged. Lets the
|
||||
/// resolver attach the separately-resolved `GROK_COMPACTION_DETAIL`.
|
||||
pub fn with_segment_detail(self, detail: CompactionDetail) -> Self {
|
||||
match self {
|
||||
Self::Segments(_) => Self::Segments(detail),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn segment_detail(self) -> Option<CompactionDetail> {
|
||||
match self {
|
||||
Self::Segments(d) => Some(d),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this mode persists the `compaction/` segment store.
|
||||
pub fn writes_segments(self) -> bool {
|
||||
matches!(self, Self::Segments(_))
|
||||
}
|
||||
|
||||
/// Transcript hint for the summary, given the one `location` this mode points
|
||||
/// at (raw transcript path or `compaction/` folder). `None` if the mode adds
|
||||
/// no pointer (`Summary`) or the location is absent.
|
||||
pub fn transcript_hint(self, location: Option<&str>) -> Option<String> {
|
||||
use crate::compaction_transcript::INDEX_FILE;
|
||||
let loc = location?;
|
||||
Some(match self {
|
||||
Self::Summary => return None,
|
||||
Self::Transcript => format!(
|
||||
"\n\nIf you need specific details from before compaction \
|
||||
(like exact code snippets, error messages, or content you \
|
||||
generated), read the full transcript at: {loc}"
|
||||
),
|
||||
// Wording mirrors the segment-store continuation note.
|
||||
Self::Segments(_) => format!(
|
||||
"\n\nFull verbatim rollouts of previous segments are available \
|
||||
at {loc}/segment_*.md. See {loc}/{INDEX_FILE} for a table of \
|
||||
contents. Use read_file or grep to recover specific details \
|
||||
(exact code, file paths, tool outputs) if this summary is \
|
||||
insufficient. Do NOT modify these files."
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `parse` is the public string contract (config + CLI): case-insensitive,
|
||||
/// unknown ⇒ `None` so the caller falls back.
|
||||
#[test]
|
||||
fn parse_maps_names_and_rejects_unknown() {
|
||||
assert_eq!(
|
||||
CompactionMode::parse("summary"),
|
||||
Some(CompactionMode::Summary)
|
||||
);
|
||||
assert_eq!(
|
||||
CompactionMode::parse("transcript"),
|
||||
Some(CompactionMode::Transcript)
|
||||
);
|
||||
// `segments` parses with the default detail; the resolver overrides it.
|
||||
assert_eq!(
|
||||
CompactionMode::parse(" SEGMENTS "),
|
||||
Some(CompactionMode::Segments(CompactionDetail::default()))
|
||||
);
|
||||
assert_eq!(CompactionMode::parse("nonsense"), None);
|
||||
assert_eq!(CompactionMode::default(), CompactionMode::Summary);
|
||||
}
|
||||
|
||||
/// Detail is only attached to `Segments`; other modes ignore the override.
|
||||
#[test]
|
||||
fn with_segment_detail_only_affects_segments() {
|
||||
assert_eq!(
|
||||
CompactionMode::Segments(CompactionDetail::Verbose)
|
||||
.with_segment_detail(CompactionDetail::Minimal),
|
||||
CompactionMode::Segments(CompactionDetail::Minimal)
|
||||
);
|
||||
assert_eq!(
|
||||
CompactionMode::Summary.with_segment_detail(CompactionDetail::Minimal),
|
||||
CompactionMode::Summary
|
||||
);
|
||||
assert_eq!(
|
||||
CompactionMode::Segments(CompactionDetail::Balanced).segment_detail(),
|
||||
Some(CompactionDetail::Balanced)
|
||||
);
|
||||
assert_eq!(CompactionMode::Transcript.segment_detail(), None);
|
||||
}
|
||||
|
||||
/// Contract: no hint for `Summary`, and never point the model at nothing.
|
||||
#[test]
|
||||
fn transcript_hint_needs_a_location() {
|
||||
let segments = CompactionMode::Segments(CompactionDetail::default());
|
||||
assert!(
|
||||
CompactionMode::Summary
|
||||
.transcript_hint(Some("/s/updates.jsonl"))
|
||||
.is_none()
|
||||
);
|
||||
assert!(CompactionMode::Transcript.transcript_hint(None).is_none());
|
||||
assert!(segments.transcript_hint(None).is_none());
|
||||
assert!(
|
||||
CompactionMode::Transcript
|
||||
.transcript_hint(Some("/s/updates.jsonl"))
|
||||
.unwrap()
|
||||
.contains("/s/updates.jsonl")
|
||||
);
|
||||
assert!(
|
||||
segments
|
||||
.transcript_hint(Some("/s/compaction"))
|
||||
.unwrap()
|
||||
.contains("/s/compaction")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,821 @@
|
||||
//! Pure rendering of a compacted segment into self-contained markdown, aligned
|
||||
//! with the Python compaction implementation (`render_segment_to_markdown` /
|
||||
//! `compute_turn_stats`; INDEX built incrementally via [`INDEX_HEADER`] +
|
||||
//! [`render_index_row`]). No I/O.
|
||||
//! Not byte-identical — the data models differ (Python `Turn`/channels vs our
|
||||
//! [`ConversationItem`]) — but headers, sections, detail levels, and INDEX
|
||||
//! columns match.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use regex::Regex;
|
||||
use xai_grok_sampling_types::ConversationItem;
|
||||
|
||||
/// Layout of the per-session segment store — single source of the path
|
||||
/// convention (writer, index parser, and transcript-hint builder all use these).
|
||||
pub const COMPACTION_DIR: &str = "compaction";
|
||||
pub const INDEX_FILE: &str = "INDEX.md";
|
||||
const SEGMENT_PREFIX: &str = "segment_";
|
||||
|
||||
/// Whole-turn-boundary truncation cap for one segment's verbatim section.
|
||||
const SEGMENT_MAX_BYTES: usize = 512 * 1024;
|
||||
const TRUNCATION_NOTICE: &str =
|
||||
"\n\n[... TRUNCATED at {limit} bytes, {omitted} turns omitted ...]\n";
|
||||
/// Per-turn text/arg caps for the `balanced` detail level (chars, like the Python implementation).
|
||||
const BALANCED_TEXT_CHARS: usize = 2000;
|
||||
const BALANCED_RESPONSE_CHARS: usize = 500;
|
||||
/// Trailing chars of the last assistant message kept for the stats excerpt.
|
||||
const LAST_RESPONSE_EXCERPT_CHARS: usize = 500;
|
||||
/// Approx markdown overhead charged per turn in the verbose-size estimate.
|
||||
const PER_TURN_OVERHEAD_BYTES: usize = 64;
|
||||
|
||||
/// How much per-turn detail lands in the verbatim section. Mirrors the Python
|
||||
/// `compaction_persist_detail`. `Verbose` is the default.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, strum::Display)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum CompactionDetail {
|
||||
/// Stats + summary only, no verbatim turns.
|
||||
None,
|
||||
/// One-line tool-call signature per turn.
|
||||
Minimal,
|
||||
/// Tool calls + truncated responses + full text.
|
||||
Balanced,
|
||||
/// Full verbatim turns.
|
||||
#[default]
|
||||
Verbose,
|
||||
}
|
||||
|
||||
impl CompactionDetail {
|
||||
/// Case-insensitive; unknown → `None` so the caller falls back to default.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"none" => Some(Self::None),
|
||||
"minimal" => Some(Self::Minimal),
|
||||
"balanced" => Some(Self::Balanced),
|
||||
"verbose" => Some(Self::Verbose),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Role label per item, mapped onto the Python `Turn` role vocabulary
|
||||
/// (`System`/`Human`/`Assistant`/`Function`). Model-side items with no Python
|
||||
/// analog (`BackendToolCall`, `Reasoning`) fold into `Assistant`.
|
||||
fn role_label(item: &ConversationItem) -> &'static str {
|
||||
match item {
|
||||
ConversationItem::System(_) => "System",
|
||||
ConversationItem::User(_) => "Human",
|
||||
ConversationItem::Assistant(_) => "Assistant",
|
||||
ConversationItem::ToolResult(_) => "Function",
|
||||
ConversationItem::BackendToolCall(_) => "Assistant",
|
||||
ConversationItem::Reasoning(_) => "Assistant",
|
||||
}
|
||||
}
|
||||
|
||||
/// INDEX.md title + table header, written once when the file is created.
|
||||
pub const INDEX_HEADER: &str = "# Compaction Segment Index\n\n\
|
||||
| Segment | File | Turns | Approx bytes | Keywords |\n\
|
||||
|---|---|---|---|---|\n";
|
||||
|
||||
/// Zero-padded segment number, e.g. `007`. The single source of the pad width.
|
||||
fn segment_label(index: u64) -> String {
|
||||
format!("{index:03}")
|
||||
}
|
||||
|
||||
/// Flat per-segment filename, e.g. `segment_007.md` (matches the Python implementation).
|
||||
pub fn segment_filename(index: u64) -> String {
|
||||
format!("{SEGMENT_PREFIX}{}.md", segment_label(index))
|
||||
}
|
||||
|
||||
/// Parse a segment index out of a `segment_NNN.md` filename, if it matches.
|
||||
pub fn parse_segment_index(filename: &str) -> Option<u64> {
|
||||
filename
|
||||
.strip_prefix(SEGMENT_PREFIX)?
|
||||
.strip_suffix(".md")?
|
||||
.parse()
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// A read of the `compaction/` store; `Display` (snake_case) is the telemetry
|
||||
/// label on `compaction.segment_read`.
|
||||
#[derive(Debug, PartialEq, Eq, strum::Display)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum CompactionArtifact {
|
||||
Segment(u64),
|
||||
Index,
|
||||
Dir,
|
||||
}
|
||||
|
||||
impl CompactionArtifact {
|
||||
pub fn segment_index(&self) -> Option<u64> {
|
||||
match self {
|
||||
Self::Segment(index) => Some(*index),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors on the `compaction/` component, not the session dir, so relative
|
||||
/// reads still match (a same-named file elsewhere is acceptable noise).
|
||||
pub fn classify_compaction_path(path: &str) -> Option<CompactionArtifact> {
|
||||
// Allocation-free: match the `compaction` component directly rather than
|
||||
// building `"compaction/"` / `"/compaction"` patterns each call.
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
if trimmed == COMPACTION_DIR
|
||||
|| trimmed
|
||||
.strip_suffix(COMPACTION_DIR)
|
||||
.is_some_and(|prefix| prefix.ends_with('/'))
|
||||
{
|
||||
return Some(CompactionArtifact::Dir);
|
||||
}
|
||||
let rest = path
|
||||
.rsplit_once(COMPACTION_DIR)
|
||||
.and_then(|(_, after)| after.strip_prefix('/'))?;
|
||||
if let Some(index) = parse_segment_index(rest) {
|
||||
Some(CompactionArtifact::Segment(index))
|
||||
} else if rest == INDEX_FILE {
|
||||
Some(CompactionArtifact::Index)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Truncate to ≤ `max` chars, appending `marker` if cut (char-based, like
|
||||
/// the Python `text[:n]`). Char boundaries are respected so we never panic.
|
||||
fn truncate_chars(s: &str, max: usize, marker: &str) -> String {
|
||||
match s.char_indices().nth(max) {
|
||||
Some((byte_idx, _)) => format!("{}{marker}", &s[..byte_idx]),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert thousands separators (mirrors Python's `{:,}`).
|
||||
fn with_thousands(n: usize) -> String {
|
||||
let digits = n.to_string();
|
||||
let bytes = digits.as_bytes();
|
||||
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
|
||||
for (i, b) in bytes.iter().enumerate() {
|
||||
if i > 0 && (bytes.len() - i).is_multiple_of(3) {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(*b as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One JSON tool-arg value rendered for a `- key: value` line.
|
||||
fn arg_value_plain(v: &serde_json::Value) -> String {
|
||||
match v {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_args(arguments: &str) -> serde_json::Map<String, serde_json::Value> {
|
||||
match serde_json::from_str::<serde_json::Value>(arguments) {
|
||||
Ok(serde_json::Value::Object(map)) => map,
|
||||
_ => serde_json::Map::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keys checked (in order) to attribute a tool call to a target file/dir.
|
||||
const FILE_ARG_KEYS: [&str; 4] = ["target_file", "file_path", "path", "target_directory"];
|
||||
|
||||
/// Walk-once statistics for the always-on `## Turn statistics` block.
|
||||
struct TurnStats {
|
||||
turn_count: usize,
|
||||
/// Role → count, kept sorted by role name.
|
||||
role_counts: Vec<(&'static str, usize)>,
|
||||
/// Tool name → count.
|
||||
tool_counts: Vec<(String, usize)>,
|
||||
unique_files: Vec<String>,
|
||||
tool_error_count: usize,
|
||||
verbose_byte_estimate: usize,
|
||||
last_assistant_excerpt: String,
|
||||
}
|
||||
|
||||
fn compute_turn_stats(items: &[ConversationItem]) -> TurnStats {
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
let mut role_counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
let mut tool_counts: BTreeMap<String, usize> = BTreeMap::new();
|
||||
let mut unique_files: BTreeSet<String> = BTreeSet::new();
|
||||
let mut tool_error_count = 0;
|
||||
let mut last_assistant = String::new();
|
||||
let mut verbose_byte_estimate = 0;
|
||||
|
||||
for item in items {
|
||||
*role_counts.entry(role_label(item)).or_insert(0) += 1;
|
||||
verbose_byte_estimate += PER_TURN_OVERHEAD_BYTES;
|
||||
|
||||
match item {
|
||||
ConversationItem::Assistant(a) => {
|
||||
verbose_byte_estimate += a.content.len();
|
||||
if !a.content.is_empty() {
|
||||
last_assistant = a.content.to_string();
|
||||
}
|
||||
for tc in &a.tool_calls {
|
||||
*tool_counts.entry(tc.name.clone()).or_insert(0) += 1;
|
||||
let args = tool_args(&tc.arguments);
|
||||
for key in FILE_ARG_KEYS {
|
||||
if let Some(serde_json::Value::String(v)) = args.get(key)
|
||||
&& !v.is_empty()
|
||||
{
|
||||
unique_files.insert(v.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
verbose_byte_estimate += args
|
||||
.iter()
|
||||
.map(|(k, v)| 32 + k.len() + arg_value_plain(v).len())
|
||||
.sum::<usize>();
|
||||
}
|
||||
}
|
||||
ConversationItem::ToolResult(t) => {
|
||||
verbose_byte_estimate += t.content.len();
|
||||
if t.content.starts_with("Error") || t.content.contains("Failed tool validation") {
|
||||
tool_error_count += 1;
|
||||
}
|
||||
}
|
||||
other => verbose_byte_estimate += other.text_content().len(),
|
||||
}
|
||||
}
|
||||
|
||||
let excerpt = {
|
||||
let n = last_assistant.chars().count();
|
||||
let tail: String = last_assistant
|
||||
.chars()
|
||||
.skip(n.saturating_sub(LAST_RESPONSE_EXCERPT_CHARS))
|
||||
.collect();
|
||||
tail.trim().to_string()
|
||||
};
|
||||
|
||||
let mut tool_counts: Vec<(String, usize)> = tool_counts.into_iter().collect();
|
||||
// Descending count for at-a-glance scanning; name breaks ties.
|
||||
tool_counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
|
||||
TurnStats {
|
||||
turn_count: items.len(),
|
||||
role_counts: role_counts.into_iter().collect(),
|
||||
tool_counts,
|
||||
unique_files: unique_files.into_iter().collect(),
|
||||
tool_error_count,
|
||||
verbose_byte_estimate,
|
||||
last_assistant_excerpt: excerpt,
|
||||
}
|
||||
}
|
||||
|
||||
fn render_stats_block(stats: &TurnStats) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let mut out = String::from("## Turn statistics\n\n");
|
||||
|
||||
let rc = stats
|
||||
.role_counts
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let _ = writeln!(out, "- Turns: {} ({rc})", stats.turn_count);
|
||||
|
||||
let tc = if stats.tool_counts.is_empty() {
|
||||
"(none)".to_string()
|
||||
} else {
|
||||
stats
|
||||
.tool_counts
|
||||
.iter()
|
||||
.map(|(name, n)| format!("{name} ({n})"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
};
|
||||
let _ = writeln!(out, "- Tools used: {tc}");
|
||||
|
||||
let uf = &stats.unique_files;
|
||||
let uf_str = if uf.is_empty() {
|
||||
"(none)".to_string()
|
||||
} else if uf.len() <= 8 {
|
||||
uf.join(", ")
|
||||
} else {
|
||||
format!("{}, ... and {} more", uf[..5].join(", "), uf.len() - 5)
|
||||
};
|
||||
let _ = writeln!(out, "- Unique target files ({}): {uf_str}", uf.len());
|
||||
let _ = writeln!(out, "- Tool errors: {}", stats.tool_error_count);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"- Verbose-render size estimate: {} B",
|
||||
with_thousands(stats.verbose_byte_estimate)
|
||||
);
|
||||
if !stats.last_assistant_excerpt.is_empty() {
|
||||
let oneline = truncate_chars(&stats.last_assistant_excerpt.replace('\n', " "), 300, "");
|
||||
let _ = writeln!(out, "- Last assistant response excerpt: \"{oneline}\"");
|
||||
}
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
/// One verbatim turn: role header, text, and `[tool_request: …]` arg lines.
|
||||
fn render_turn_verbose(item: &ConversationItem, index: usize) -> String {
|
||||
let mut parts = vec![format!("### Turn {index} ({})", role_label(item))];
|
||||
match item {
|
||||
ConversationItem::Assistant(a) => {
|
||||
if !a.content.is_empty() {
|
||||
parts.push(a.content.to_string());
|
||||
}
|
||||
for tc in &a.tool_calls {
|
||||
parts.push(format!("[tool_request: {}]", tc.name));
|
||||
for (k, v) in tool_args(&tc.arguments) {
|
||||
parts.push(format!("- {k}: {}", arg_value_plain(&v)));
|
||||
}
|
||||
}
|
||||
}
|
||||
ConversationItem::ToolResult(t) => {
|
||||
parts.push("[tool_response]".to_string());
|
||||
if !t.content.is_empty() {
|
||||
parts.push(t.content.to_string());
|
||||
}
|
||||
}
|
||||
other => {
|
||||
let txt = other.text_content();
|
||||
if !txt.is_empty() {
|
||||
parts.push(txt);
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.join("\n") + "\n"
|
||||
}
|
||||
|
||||
/// One balanced turn: full text (capped) + truncated tool-call args/responses.
|
||||
fn render_turn_balanced(item: &ConversationItem, index: usize) -> String {
|
||||
let mut parts = vec![format!("### Turn {index} ({})", role_label(item))];
|
||||
match item {
|
||||
ConversationItem::Assistant(a) => {
|
||||
if !a.content.is_empty() {
|
||||
parts.push(truncate_chars(
|
||||
&a.content,
|
||||
BALANCED_TEXT_CHARS,
|
||||
"... [truncated]",
|
||||
));
|
||||
}
|
||||
for tc in &a.tool_calls {
|
||||
parts.push(format!("[tool_request: {}]", tc.name));
|
||||
for (k, v) in tool_args(&tc.arguments) {
|
||||
let v = truncate_chars(
|
||||
&arg_value_plain(&v),
|
||||
BALANCED_RESPONSE_CHARS,
|
||||
"... [truncated]",
|
||||
);
|
||||
parts.push(format!("- {k}: {v}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
ConversationItem::ToolResult(t) => {
|
||||
parts.push("[tool_response]".to_string());
|
||||
if !t.content.is_empty() {
|
||||
parts.push(truncate_chars(
|
||||
&t.content,
|
||||
BALANCED_RESPONSE_CHARS,
|
||||
"... [truncated]",
|
||||
));
|
||||
}
|
||||
}
|
||||
other => {
|
||||
let txt = other.text_content();
|
||||
if !txt.is_empty() {
|
||||
parts.push(txt);
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.join("\n") + "\n"
|
||||
}
|
||||
|
||||
/// One-line tool-call signature per turn, no response bodies.
|
||||
fn render_turn_signature(item: &ConversationItem, index: usize) -> String {
|
||||
let role = role_label(item);
|
||||
match item {
|
||||
ConversationItem::Assistant(a) => {
|
||||
let sigs: Vec<String> = a
|
||||
.tool_calls
|
||||
.iter()
|
||||
.map(|tc| {
|
||||
let args = tool_args(&tc.arguments);
|
||||
let key_arg = [
|
||||
"target_file",
|
||||
"file_path",
|
||||
"path",
|
||||
"target_directory",
|
||||
"command",
|
||||
"pattern",
|
||||
]
|
||||
.iter()
|
||||
.find_map(|k| match args.get(*k) {
|
||||
Some(serde_json::Value::String(v)) if !v.is_empty() => {
|
||||
Some(format!("{k}={:?}", truncate_chars(v, 80, "...")))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
format!("{}({key_arg})", tc.name)
|
||||
})
|
||||
.collect();
|
||||
let sig_str = if sigs.is_empty() {
|
||||
"(text only)".to_string()
|
||||
} else {
|
||||
sigs.join(" ")
|
||||
};
|
||||
format!("### Turn {index} ({role}) {sig_str}\n")
|
||||
}
|
||||
ConversationItem::ToolResult(_) => format!("### Turn {index} ({role}) [tool_response]\n"),
|
||||
_ => format!("### Turn {index} ({role})\n"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render one segment: header, metadata, stats, curated summary, and (unless
|
||||
/// `detail == None`) verbatim turns truncated at a whole-turn boundary before
|
||||
/// [`SEGMENT_MAX_BYTES`]. `summary` must already be cleaned of analysis tags;
|
||||
/// `items` is the segment view — tool calls + results kept, images/reasoning
|
||||
/// stripped (see `compaction_utils::prepare_conversation_for_segment`).
|
||||
pub fn render_segment_md(
|
||||
items: &[ConversationItem],
|
||||
summary: &str,
|
||||
index: u64,
|
||||
detail: CompactionDetail,
|
||||
timestamp: &str,
|
||||
) -> String {
|
||||
let header = format!(
|
||||
"# HISTORICAL -- DO NOT EDIT\n\
|
||||
# Record of compaction segment {label} (detail={detail}) from this same task.\n\
|
||||
# Use read_file or grep to look up details, but do not modify.\n\n",
|
||||
label = segment_label(index),
|
||||
);
|
||||
let metadata = format!(
|
||||
"## Segment metadata\n- Index: {label}\n- Turn count: {count}\n- Timestamp: {timestamp}\n\n",
|
||||
label = segment_label(index),
|
||||
count = items.len(),
|
||||
);
|
||||
let stats_section = render_stats_block(&compute_turn_stats(items)) + "\n";
|
||||
let summary_body = summary.trim();
|
||||
let summary_section = format!(
|
||||
"## Summary (curated by compaction step)\n\n{}\n\n",
|
||||
if summary_body.is_empty() {
|
||||
"(empty)"
|
||||
} else {
|
||||
summary_body
|
||||
},
|
||||
);
|
||||
|
||||
let preamble_head = format!("{header}{metadata}{stats_section}{summary_section}");
|
||||
if detail == CompactionDetail::None {
|
||||
return preamble_head;
|
||||
}
|
||||
|
||||
let (turns_header, render_turn): (&str, fn(&ConversationItem, usize) -> String) = match detail {
|
||||
CompactionDetail::Minimal => ("## Turn signatures\n\n", render_turn_signature),
|
||||
CompactionDetail::Balanced => ("## Turns (balanced detail)\n\n", render_turn_balanced),
|
||||
CompactionDetail::Verbose => ("## Verbatim turns\n\n", render_turn_verbose),
|
||||
CompactionDetail::None => unreachable!("None returns above"),
|
||||
};
|
||||
|
||||
let preamble = format!("{preamble_head}{turns_header}");
|
||||
// Reserve the preamble, the notice, and slack for its `{limit}`/`{omitted}`
|
||||
// substitutions so the rendered doc stays under the cap.
|
||||
let budget = SEGMENT_MAX_BYTES
|
||||
.saturating_sub(preamble.len() + TRUNCATION_NOTICE.len() + PER_TURN_OVERHEAD_BYTES);
|
||||
|
||||
let mut blocks: Vec<String> = Vec::new();
|
||||
let mut used = 0;
|
||||
let mut truncated_at: Option<usize> = None;
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
let block = render_turn(item, i);
|
||||
if used + block.len() > budget {
|
||||
truncated_at = Some(i);
|
||||
break;
|
||||
}
|
||||
used += block.len();
|
||||
blocks.push(block);
|
||||
}
|
||||
|
||||
let mut body = blocks.join("\n");
|
||||
if let Some(at) = truncated_at {
|
||||
let omitted = items.len() - at;
|
||||
body.push_str(
|
||||
&TRUNCATION_NOTICE
|
||||
.replace("{limit}", &SEGMENT_MAX_BYTES.to_string())
|
||||
.replace("{omitted}", &omitted.to_string()),
|
||||
);
|
||||
}
|
||||
format!("{preamble}{body}")
|
||||
}
|
||||
|
||||
/// One INDEX.md row (with trailing newline). `keywords` are quoted and
|
||||
/// comma-joined; the columns match [`INDEX_HEADER`].
|
||||
pub fn render_index_row(
|
||||
index: u64,
|
||||
turn_count: usize,
|
||||
approx_bytes: usize,
|
||||
keywords: &[String],
|
||||
) -> String {
|
||||
let kw = keywords
|
||||
.iter()
|
||||
.map(|k| format!("\"{k}\""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!(
|
||||
"| {label} | {file} | {turn_count} | {approx_bytes} | {kw} |\n",
|
||||
label = segment_label(index),
|
||||
file = segment_filename(index),
|
||||
)
|
||||
}
|
||||
|
||||
static SECTION8_START_RE: OnceLock<Regex> = OnceLock::new();
|
||||
static SECTION_HEADER_RE: OnceLock<Regex> = OnceLock::new();
|
||||
static KEYWORD_RE: OnceLock<Regex> = OnceLock::new();
|
||||
|
||||
/// Stopwords dropped from INDEX keywords (mirrors the Python implementation).
|
||||
const KEYWORD_STOPWORDS: [&str; 28] = [
|
||||
"section",
|
||||
"summary",
|
||||
"current",
|
||||
"work",
|
||||
"errors",
|
||||
"analysis",
|
||||
"primary",
|
||||
"request",
|
||||
"intent",
|
||||
"technical",
|
||||
"concepts",
|
||||
"pending",
|
||||
"problem",
|
||||
"solving",
|
||||
"include",
|
||||
"outline",
|
||||
"describe",
|
||||
"specific",
|
||||
"messages",
|
||||
"feedback",
|
||||
"snippet",
|
||||
"snippets",
|
||||
"session",
|
||||
"explicit",
|
||||
"thorough",
|
||||
"language",
|
||||
"important",
|
||||
"convention",
|
||||
];
|
||||
|
||||
/// Best-effort INDEX keywords: identifier-shaped tokens from the summary's
|
||||
/// "8. Current Work" section (falling back to the whole summary), minus
|
||||
/// stopwords, deduped, capped at 8. Heuristic only — feeds the INDEX table.
|
||||
pub fn extract_keywords(summary: &str) -> Vec<String> {
|
||||
// Rust's regex has no look-ahead, so scope section 8 with two anchored
|
||||
// matches: its header, then the next `N. Capital` header (or end of text).
|
||||
// `#{0,6}` tolerates our `## 8. Current Work` markdown headers as well as
|
||||
// the Python implementation's bare `8. Current Work`.
|
||||
let start_re =
|
||||
SECTION8_START_RE.get_or_init(|| Regex::new(r"(?m)^#{0,6}\s*8\.\s+Current Work").unwrap());
|
||||
let header_re =
|
||||
SECTION_HEADER_RE.get_or_init(|| Regex::new(r"(?m)^#{0,6}\s*\d+\.\s+[A-Z]").unwrap());
|
||||
let kw_re =
|
||||
KEYWORD_RE.get_or_init(|| Regex::new(r"[A-Z][A-Za-z0-9_]{3,}|[a-z][a-z0-9_]{5,}").unwrap());
|
||||
|
||||
let text = match start_re.find(summary) {
|
||||
Some(m) => {
|
||||
let end = header_re
|
||||
.find_at(summary, m.end())
|
||||
.map(|h| h.start())
|
||||
.unwrap_or(summary.len());
|
||||
&summary[m.start()..end]
|
||||
}
|
||||
None => summary,
|
||||
};
|
||||
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
for m in kw_re.find_iter(text) {
|
||||
let kw = m.as_str();
|
||||
if KEYWORD_STOPWORDS.contains(&kw.to_ascii_lowercase().as_str()) {
|
||||
continue;
|
||||
}
|
||||
if seen.iter().any(|s| s == kw) {
|
||||
continue;
|
||||
}
|
||||
seen.push(kw.to_string());
|
||||
if seen.len() >= 8 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn user(text: &str) -> ConversationItem {
|
||||
ConversationItem::user(text)
|
||||
}
|
||||
|
||||
/// The segment doc carries the Python implementation's skeleton: banner, metadata, stats,
|
||||
/// curated summary, and a detail-specific verbatim section.
|
||||
#[test]
|
||||
fn segment_md_matches_skeleton() {
|
||||
let md = render_segment_md(
|
||||
&[user("hello world")],
|
||||
"Summary: did things.",
|
||||
7,
|
||||
CompactionDetail::Verbose,
|
||||
"2026-01-01T00:00:00Z",
|
||||
);
|
||||
assert!(md.starts_with("# HISTORICAL -- DO NOT EDIT\n"));
|
||||
assert!(
|
||||
md.contains("# Record of compaction segment 007 (detail=verbose) from this same task.")
|
||||
);
|
||||
assert!(md.contains("## Segment metadata\n- Index: 007\n- Turn count: 1\n"));
|
||||
assert!(md.contains("## Turn statistics"));
|
||||
assert!(md.contains("## Summary (curated by compaction step)\n\nSummary: did things."));
|
||||
}
|
||||
|
||||
/// Detail level selects the turns section (and `none` omits it entirely).
|
||||
#[test]
|
||||
fn detail_levels_select_turns_section() {
|
||||
let one = [user("hi")];
|
||||
let none = render_segment_md(&one, "s", 0, CompactionDetail::None, "t");
|
||||
assert!(!none.contains("## Verbatim turns") && !none.contains("## Turn signatures"));
|
||||
assert!(
|
||||
render_segment_md(&one, "s", 0, CompactionDetail::Minimal, "t")
|
||||
.contains("## Turn signatures")
|
||||
);
|
||||
assert!(
|
||||
render_segment_md(&one, "s", 0, CompactionDetail::Balanced, "t")
|
||||
.contains("## Turns (balanced detail)")
|
||||
);
|
||||
assert!(
|
||||
render_segment_md(&one, "s", 0, CompactionDetail::Verbose, "t")
|
||||
.contains("## Verbatim turns")
|
||||
);
|
||||
// Stats + summary survive at every level.
|
||||
for d in [
|
||||
CompactionDetail::None,
|
||||
CompactionDetail::Minimal,
|
||||
CompactionDetail::Balanced,
|
||||
CompactionDetail::Verbose,
|
||||
] {
|
||||
assert!(render_segment_md(&one, "s", 0, d, "t").contains("## Turn statistics"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Verbatim turns are dropped at a whole-turn boundary once the byte budget
|
||||
/// is exceeded, with a notice naming how many turns were omitted.
|
||||
#[test]
|
||||
fn verbatim_turns_truncate_at_turn_boundary() {
|
||||
// Each turn renders ~200 KB, so the 3rd turn blows the 512 KB budget.
|
||||
let big = "x".repeat(200 * 1024);
|
||||
let items = [user(&big), user(&big), user(&big), user(&big)];
|
||||
let md = render_segment_md(&items, "s", 0, CompactionDetail::Verbose, "t");
|
||||
assert!(md.contains("### Turn 0 (Human)"));
|
||||
assert!(md.contains(&format!("TRUNCATED at {SEGMENT_MAX_BYTES} bytes")));
|
||||
assert!(md.contains("turns omitted"));
|
||||
// A whole turn was dropped (4 items, not all rendered).
|
||||
assert!(md.matches("### Turn ").count() < items.len());
|
||||
}
|
||||
|
||||
/// INDEX header + row match the 5-column Python table; keywords are quoted.
|
||||
#[test]
|
||||
fn index_row_matches_columns() {
|
||||
assert!(INDEX_HEADER.starts_with(
|
||||
"# Compaction Segment Index\n\n| Segment | File | Turns | Approx bytes | Keywords |"
|
||||
));
|
||||
let row = render_index_row(2, 9, 1234, &["Foo".to_string(), "bar_baz".to_string()]);
|
||||
assert_eq!(
|
||||
row,
|
||||
"| 002 | segment_002.md | 9 | 1234 | \"Foo\", \"bar_baz\" |\n"
|
||||
);
|
||||
assert_eq!(row.matches('\n').count(), 1);
|
||||
}
|
||||
|
||||
/// Filename ⇄ index round-trips through the flat `segment_NNN.md` name.
|
||||
#[test]
|
||||
fn segment_filename_round_trips() {
|
||||
assert_eq!(segment_filename(5), "segment_005.md");
|
||||
assert_eq!(parse_segment_index("segment_005.md"), Some(5));
|
||||
assert_eq!(parse_segment_index("segment_005"), None);
|
||||
assert_eq!(parse_segment_index("notes.md"), None);
|
||||
}
|
||||
|
||||
/// Store artifacts map to their kind (relative reads included); non-artifacts
|
||||
/// — even other files under `compaction/` — don't.
|
||||
#[test]
|
||||
fn classify_compaction_path_maps_store_artifacts() {
|
||||
use CompactionArtifact::*;
|
||||
assert_eq!(
|
||||
classify_compaction_path("/u/abc/compaction/segment_007.md"),
|
||||
Some(Segment(7))
|
||||
);
|
||||
// Relative read still matches (the substring-anchor behavior).
|
||||
assert_eq!(
|
||||
classify_compaction_path("compaction/segment_012.md"),
|
||||
Some(Segment(12))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_compaction_path("/u/abc/compaction/INDEX.md"),
|
||||
Some(Index)
|
||||
);
|
||||
assert_eq!(classify_compaction_path("/u/abc/compaction"), Some(Dir));
|
||||
// Not store artifacts — including other files under `compaction/`.
|
||||
assert_eq!(classify_compaction_path("/repo/src/main.rs"), None);
|
||||
assert_eq!(classify_compaction_path("compaction/notes.md"), None);
|
||||
}
|
||||
|
||||
// --- Parity with the Python implementation's own test vectors (compaction_utils_test.py) ---
|
||||
|
||||
/// Keyword extraction: the Python `TestExtractKeywords` vectors (bare `8.`
|
||||
/// headers, stopword filtering, dedup, no-section-8 fallback) plus our
|
||||
/// `## 8.` markdown-header tolerance and out-of-section exclusion.
|
||||
#[test]
|
||||
fn extract_keywords_matches_python_vectors_and_markdown_headers() {
|
||||
let kw = extract_keywords(
|
||||
"1. Primary Request: ...\n8. Current Work: Just refactored AuthMiddleware in \
|
||||
handler.py and updated RedisCache integration.\n9. Next Step: ...\n",
|
||||
);
|
||||
assert!(kw.iter().any(|k| k == "AuthMiddleware") && kw.iter().any(|k| k == "RedisCache"));
|
||||
// No section 8 ⇒ fall back to the whole summary.
|
||||
let kw = extract_keywords("Worked on PostgresAdapter and JwtRefresh.");
|
||||
assert!(kw.iter().any(|k| k == "PostgresAdapter") && kw.iter().any(|k| k == "JwtRefresh"));
|
||||
// All-stopword section ⇒ empty; duplicates collapse to one.
|
||||
assert!(
|
||||
extract_keywords("8. Current Work: section summary technical concepts.\n").is_empty()
|
||||
);
|
||||
let kw = extract_keywords("8. Current Work: SameName SameName Other.\n");
|
||||
assert_eq!(kw.iter().filter(|k| *k == "SameName").count(), 1);
|
||||
// Our `## N.` markdown headers: scope to section 8, exclude outside words.
|
||||
let kw = extract_keywords(
|
||||
"## 1. Intro\nGenericWord\n\n## 8. Current Work\nEditing CompactionMode here.\n\n\
|
||||
## 9. Next\nUnrelatedThing",
|
||||
);
|
||||
assert!(kw.iter().any(|k| k == "CompactionMode"));
|
||||
assert!(
|
||||
!kw.iter()
|
||||
.any(|k| k == "GenericWord" || k == "UnrelatedThing")
|
||||
);
|
||||
}
|
||||
|
||||
/// Mirrors `TestComputeTurnStats::test_basic_counts` — same turns, same
|
||||
/// role/tool/file/error stats (roles mapped User→Human, ToolResult→Function).
|
||||
#[test]
|
||||
fn parity_turn_stats_matches_basic_counts() {
|
||||
use xai_grok_sampling_types::{AssistantItem, ToolCall};
|
||||
let tc = |name: &str, args: &str| ToolCall {
|
||||
id: "t".into(),
|
||||
name: name.to_string(),
|
||||
arguments: args.into(),
|
||||
};
|
||||
let items = vec![
|
||||
user("Fix the bug"),
|
||||
ConversationItem::Assistant(AssistantItem {
|
||||
content: "Done".into(),
|
||||
tool_calls: vec![
|
||||
tc("read_file", r#"{"target_file":"src/a.py"}"#),
|
||||
tc("read_file", r#"{"target_file":"src/b.py"}"#),
|
||||
tc("grep", r#"{"pattern":"x","path":"src/"}"#),
|
||||
],
|
||||
model_id: None,
|
||||
model_fingerprint: None,
|
||||
reasoning_effort: None,
|
||||
}),
|
||||
ConversationItem::tool_result("c", "file contents"),
|
||||
];
|
||||
let s = compute_turn_stats(&items);
|
||||
assert_eq!(s.turn_count, 3);
|
||||
assert_eq!(
|
||||
s.role_counts,
|
||||
vec![("Assistant", 1), ("Function", 1), ("Human", 1)]
|
||||
);
|
||||
// Descending count, name tie-break.
|
||||
assert_eq!(
|
||||
s.tool_counts,
|
||||
vec![("read_file".to_string(), 2), ("grep".to_string(), 1)]
|
||||
);
|
||||
assert_eq!(s.unique_files, vec!["src/", "src/a.py", "src/b.py"]);
|
||||
assert_eq!(s.tool_error_count, 0);
|
||||
}
|
||||
|
||||
/// Mirrors `test_error_counting` + `test_last_assistant_excerpt`.
|
||||
#[test]
|
||||
fn parity_turn_stats_errors_and_excerpt() {
|
||||
let errs = vec![
|
||||
ConversationItem::tool_result("a", "Error: not found"),
|
||||
ConversationItem::tool_result("c", "Failed tool validation: foo"),
|
||||
ConversationItem::tool_result("e", "success"),
|
||||
];
|
||||
assert_eq!(compute_turn_stats(&errs).tool_error_count, 2);
|
||||
|
||||
let conv = vec![
|
||||
ConversationItem::assistant("early"),
|
||||
user("middle"),
|
||||
ConversationItem::assistant("the final answer is 42"),
|
||||
];
|
||||
assert!(
|
||||
compute_turn_stats(&conv)
|
||||
.last_assistant_excerpt
|
||||
.contains("the final answer is 42")
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,117 @@
|
||||
//! Pure conversation-shape helpers, kept crate-neutral so both the session
|
||||
//! layer (`xai-grok-shell`) and the `ChatStateActor` can share one definition
|
||||
//! of "align the leading System message with a prompt".
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use xai_grok_sampling_types::conversation::ConversationItem;
|
||||
|
||||
/// Equal after trimming trailing `\n`/`\r` from both sides. Used for attach
|
||||
/// idempotency so a stored head that differs from a client override only by a
|
||||
/// trailing newline is treated as already matching (cache-friendly no-op).
|
||||
/// Interior and leading whitespace are significant.
|
||||
pub fn canonical_system_prompt_eq(a: &str, b: &str) -> bool {
|
||||
a.trim_end_matches(['\n', '\r']) == b.trim_end_matches(['\n', '\r'])
|
||||
}
|
||||
|
||||
/// Replace the leading `System` message with `prompt`, or insert one at the head
|
||||
/// if the conversation has no leading `System`. Returns whether the conversation
|
||||
/// changed; a head already equal to `prompt` (modulo trailing newlines) is left
|
||||
/// untouched for KV-cache-friendly idempotency.
|
||||
///
|
||||
/// Single source of truth for the "align System[0] with the client override"
|
||||
/// operation, shared by the cold-load pre-apply (on a loaded history `Vec`,
|
||||
/// before spawn persists it) and the atomic `ChatStateActor` head swap that
|
||||
/// backs the resident-reconnect path.
|
||||
#[must_use]
|
||||
pub fn replace_or_insert_system_head(
|
||||
conversation: &mut Vec<ConversationItem>,
|
||||
prompt: &str,
|
||||
) -> bool {
|
||||
match conversation.first_mut() {
|
||||
Some(ConversationItem::System(sys)) => {
|
||||
if canonical_system_prompt_eq(sys.content.as_ref(), prompt) {
|
||||
return false;
|
||||
}
|
||||
sys.content = Arc::from(prompt);
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
conversation.insert(0, ConversationItem::system(prompt));
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn system_prompt(conversation: &[ConversationItem]) -> Option<&str> {
|
||||
conversation.first().and_then(|item| match item {
|
||||
ConversationItem::System(s) => Some(s.content.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_system_prompt_eq_ignores_trailing_newlines() {
|
||||
assert!(canonical_system_prompt_eq("hello\n", "hello"));
|
||||
assert!(canonical_system_prompt_eq("hello\r\n", "hello"));
|
||||
assert!(!canonical_system_prompt_eq("hello", "world"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_system_prompt_eq_respects_interior_and_leading_whitespace() {
|
||||
assert!(canonical_system_prompt_eq("a\nb\n", "a\nb"));
|
||||
assert!(!canonical_system_prompt_eq("a\nb", "ab"));
|
||||
assert!(!canonical_system_prompt_eq(" hello", "hello"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_or_insert_system_head_replaces_stored_head() {
|
||||
let mut history = vec![
|
||||
ConversationItem::system("default system prompt"),
|
||||
ConversationItem::user("hi"),
|
||||
];
|
||||
assert!(replace_or_insert_system_head(
|
||||
&mut history,
|
||||
"client override"
|
||||
));
|
||||
assert_eq!(system_prompt(&history), Some("client override"));
|
||||
assert_eq!(history.len(), 2, "must not wipe user turns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_or_insert_system_head_noop_when_unchanged() {
|
||||
let mut history = vec![
|
||||
ConversationItem::system("same prompt"),
|
||||
ConversationItem::user("hi"),
|
||||
];
|
||||
assert!(!replace_or_insert_system_head(
|
||||
&mut history,
|
||||
"same prompt\n"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_or_insert_system_head_inserts_when_first_is_not_system() {
|
||||
let mut history = vec![ConversationItem::user("hi")];
|
||||
assert!(replace_or_insert_system_head(
|
||||
&mut history,
|
||||
"client override"
|
||||
));
|
||||
assert_eq!(system_prompt(&history), Some("client override"));
|
||||
assert_eq!(history.len(), 2, "inserts at head, keeps existing turns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_or_insert_system_head_inserts_into_empty() {
|
||||
let mut history: Vec<ConversationItem> = vec![];
|
||||
assert!(replace_or_insert_system_head(
|
||||
&mut history,
|
||||
"client override"
|
||||
));
|
||||
assert_eq!(system_prompt(&history), Some("client override"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Events emitted by the ChatStateActor.
|
||||
|
||||
/// Events emitted by the ChatStateActor to the session main loop.
|
||||
///
|
||||
/// Persistence is handled internally by the actor — these events are for
|
||||
/// session-level coordination only.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ChatStateEvent {
|
||||
/// Prompt index changed (session uses this to update hunk tracker attribution).
|
||||
PromptIndexChanged { new_index: usize },
|
||||
|
||||
/// Token count updated (session uses this for notification meta,
|
||||
/// auto-compact threshold checks).
|
||||
TokensUpdated { total_tokens: u64 },
|
||||
|
||||
/// Conversation was replaced (compaction/rewind) — session may need to
|
||||
/// reset idle-flush counters, memory injection flags, etc.
|
||||
ConversationReset { new_len: usize },
|
||||
|
||||
/// Image byte-budget record for a built request (observability only,
|
||||
/// emitted on image-bearing turns). The session consumer writes this to
|
||||
/// the local unified log for verification. `evicted == 0` means the body
|
||||
/// was under the trigger and every image was kept.
|
||||
ImageBudget {
|
||||
/// Exact serialized conversation body size measured for the gate.
|
||||
body_bytes: usize,
|
||||
/// Threshold at which eviction fires.
|
||||
trigger_bytes: usize,
|
||||
/// Low-water mark eviction reclaims down to once it fires.
|
||||
reclaim_target_bytes: usize,
|
||||
/// Inline images present before eviction.
|
||||
inline_images: usize,
|
||||
/// Whether the body crossed the trigger this turn.
|
||||
needs_image_compaction: bool,
|
||||
/// Images replaced with a placeholder this turn.
|
||||
evicted: usize,
|
||||
/// Estimated body size after eviction (== `body_bytes` when none).
|
||||
body_bytes_after: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn event_variants_are_constructible() {
|
||||
let _ = ChatStateEvent::PromptIndexChanged { new_index: 1 };
|
||||
let _ = ChatStateEvent::TokensUpdated { total_tokens: 500 };
|
||||
let _ = ChatStateEvent::ConversationReset { new_len: 3 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Handle to communicate with ChatStateActor.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use xai_grok_sampling_types::{
|
||||
ConversationItem, ConversationRequest, DanglingToolCallReason, SamplingConfig, TokenUsage,
|
||||
ToolSpec, TraceContext,
|
||||
};
|
||||
|
||||
use crate::commands::{ChatStateCommand, RepairHistoryBlocked};
|
||||
use crate::types::{
|
||||
AutoCompactTrigger, ChatStateSnapshot, ConversationCounts, Credentials, NotificationMeta,
|
||||
TurnCapture,
|
||||
};
|
||||
|
||||
/// Handle to communicate with ChatStateActor.
|
||||
/// This is cheap to clone and can be shared across tasks.
|
||||
#[derive(Clone)]
|
||||
pub struct ChatStateHandle {
|
||||
cmd_tx: mpsc::UnboundedSender<ChatStateCommand>,
|
||||
}
|
||||
|
||||
impl ChatStateHandle {
|
||||
/// Create a new handle with the given command sender.
|
||||
pub(crate) fn new(cmd_tx: mpsc::UnboundedSender<ChatStateCommand>) -> Self {
|
||||
Self { cmd_tx }
|
||||
}
|
||||
|
||||
/// Create a no-op handle that discards all commands.
|
||||
/// Useful for tests and situations where chat state tracking is not needed.
|
||||
pub fn noop() -> Self {
|
||||
let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
|
||||
Self { cmd_tx }
|
||||
}
|
||||
|
||||
// ═══ Fire-and-forget mutations ═══
|
||||
|
||||
/// Push a user message into the conversation.
|
||||
pub fn push_user_message(&self, item: ConversationItem) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::PushUserMessage { item });
|
||||
}
|
||||
|
||||
/// Push a user message and await acknowledgement that the chat-state actor
|
||||
/// has accepted and processed it.
|
||||
pub async fn push_user_message_and_ack(&self, item: ConversationItem) -> Option<()> {
|
||||
self.query("PushUserMessageAndAck", |reply| {
|
||||
ChatStateCommand::PushUserMessageAndAck { item, reply }
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Push a user message with an explicit dangling-repair reason.
|
||||
pub fn push_user_message_with_repair_reason(
|
||||
&self,
|
||||
item: ConversationItem,
|
||||
reason: DanglingToolCallReason,
|
||||
) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::PushUserMessageWithRepairReason { item, reason });
|
||||
}
|
||||
|
||||
/// Record the assistant's response.
|
||||
pub fn push_assistant_response(&self, item: ConversationItem) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::PushAssistantResponse { item });
|
||||
}
|
||||
|
||||
/// Record a tool result.
|
||||
pub fn push_tool_result(&self, item: ConversationItem) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::PushToolResult { item });
|
||||
}
|
||||
|
||||
/// Record accumulated token usage.
|
||||
pub fn record_token_usage(&self, total_tokens: u64) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RecordTokenUsage { total_tokens });
|
||||
}
|
||||
|
||||
/// Stash the per-turn `TokenUsage` from the most recent model response.
|
||||
/// Fire-and-forget — no ack returned.
|
||||
pub fn record_last_turn_usage(&self, usage: TokenUsage) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RecordLastTurnUsage { usage });
|
||||
}
|
||||
|
||||
pub fn record_model_call_usage(
|
||||
&self,
|
||||
model_id: Option<String>,
|
||||
usage: TokenUsage,
|
||||
api_duration_ms: Option<u64>,
|
||||
cost_usd_ticks: Option<i64>,
|
||||
) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::RecordModelCallUsage {
|
||||
model_id,
|
||||
usage,
|
||||
api_duration_ms,
|
||||
cost_usd_ticks,
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply subagent usage; returns false if the actor did not acknowledge.
|
||||
pub async fn record_subagent_usage(
|
||||
&self,
|
||||
by_model: Vec<(String, crate::usage::UsageTotals)>,
|
||||
attribute_to_prompt: bool,
|
||||
incomplete: bool,
|
||||
) -> bool {
|
||||
self.query("RecordSubagentUsage", |reply| {
|
||||
ChatStateCommand::RecordSubagentUsage {
|
||||
by_model,
|
||||
attribute_to_prompt,
|
||||
incomplete,
|
||||
reply,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Mark open prompt and/or session ledgers incomplete.
|
||||
pub async fn mark_usage_incomplete(&self, prompt: bool, session: bool) -> bool {
|
||||
self.query("MarkUsageIncomplete", |reply| {
|
||||
ChatStateCommand::MarkUsageIncomplete {
|
||||
prompt,
|
||||
session,
|
||||
reply,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Increment prompt index (called at start of each user turn).
|
||||
pub fn increment_prompt_index(&self) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::IncrementPromptIndex);
|
||||
}
|
||||
|
||||
/// Update the sampling config (e.g., model switch).
|
||||
pub fn update_sampling_config(&self, config: SamplingConfig) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::UpdateSamplingConfig { config });
|
||||
}
|
||||
|
||||
/// Track that the agent edited a file path.
|
||||
pub fn record_agent_edited_path(&self, path: String) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RecordAgentEditedPath { path });
|
||||
}
|
||||
|
||||
/// Record stream timing metadata.
|
||||
pub fn record_stream_start(&self, timestamp_ms: i64) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RecordStreamStart { timestamp_ms });
|
||||
}
|
||||
|
||||
/// Record turn timing metadata.
|
||||
pub fn record_turn_start(&self, timestamp_ms: i64) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RecordTurnStart { timestamp_ms });
|
||||
}
|
||||
|
||||
/// Replace conversation history.
|
||||
pub fn replace_conversation(&self, items: Vec<ConversationItem>) {
|
||||
self.send_replace(items, false);
|
||||
}
|
||||
|
||||
/// Replace conversation history for compaction.
|
||||
/// Sets `compaction_occurred` on the active turn capture.
|
||||
pub fn replace_conversation_for_compaction(&self, items: Vec<ConversationItem>) {
|
||||
self.send_replace(items, true);
|
||||
}
|
||||
|
||||
fn send_replace(&self, items: Vec<ConversationItem>, is_compaction: bool) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::ReplaceConversation {
|
||||
items,
|
||||
is_compaction,
|
||||
});
|
||||
}
|
||||
|
||||
/// Out-of-band history repair (`x.ai/session/repair`); see
|
||||
/// [`ChatStateCommand::RepairHistory`]. Returns `None` if the actor is
|
||||
/// dead, `Some(Err(_))` if a turn was in flight at processing time.
|
||||
pub async fn repair_history(
|
||||
&self,
|
||||
dry_run: bool,
|
||||
turn_active: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||
) -> Option<Result<crate::compaction_utils::HistoryRepairReport, RepairHistoryBlocked>> {
|
||||
self.query("RepairHistory", |reply| ChatStateCommand::RepairHistory {
|
||||
dry_run,
|
||||
turn_active,
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Atomically align the leading `System` message with `prompt` (insert one
|
||||
/// if absent), persisting when changed. Serializes with turn pushes inside
|
||||
/// the actor, so a mid-turn reconnect can't drop concurrent updates.
|
||||
/// Returns `Some(changed)`, or `None` if the actor is dead.
|
||||
pub async fn replace_system_head(&self, prompt: &str) -> Option<bool> {
|
||||
let prompt = prompt.to_owned();
|
||||
self.query("ReplaceSystemHead", |reply| {
|
||||
ChatStateCommand::ReplaceSystemHead { prompt, reply }
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Cache prompt text for rewind preview.
|
||||
pub fn cache_prompt_text(&self, text: String) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::CachePromptText { text });
|
||||
}
|
||||
|
||||
/// Record compaction boundary for rewind.
|
||||
pub fn record_compaction_at(&self, prompt_index: usize) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RecordCompactionAt { prompt_index });
|
||||
}
|
||||
|
||||
/// Flush pending persistence writes to disk.
|
||||
pub fn flush(&self) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::Flush);
|
||||
}
|
||||
|
||||
/// Update opaque credential secrets held by the actor.
|
||||
pub fn update_credentials(&self, credentials: Credentials) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::UpdateCredentials { credentials });
|
||||
}
|
||||
|
||||
/// Restore from a snapshot.
|
||||
pub fn restore_snapshot(&self, snapshot: ChatStateSnapshot) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RestoreSnapshot(Box::new(snapshot)));
|
||||
}
|
||||
|
||||
/// Begin capturing turn messages. Call at the start of a real user turn
|
||||
/// (in `handle_prompt`), before `push_user_message`.
|
||||
pub fn begin_turn_capture(&self) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::BeginTurnCapture);
|
||||
}
|
||||
|
||||
/// Append synthetic `task` pairs for a harness-spawned subagent (goal
|
||||
/// planner / verifier skeptic) to the in-progress harness trace phase. They
|
||||
/// are sealed into a standalone trace turn by [`Self::flush_harness_trace_turn`]
|
||||
/// and never enter the live `conversation` sent to the model. No-op on
|
||||
/// empty input.
|
||||
pub fn append_harness_trace_items(&self, items: Vec<ConversationItem>) {
|
||||
if items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::AppendHarnessTraceItems { items });
|
||||
}
|
||||
|
||||
/// Seal the harness items accumulated since the last flush into one trace
|
||||
/// turn. Call once per harness phase (after the planner, after a verifier
|
||||
/// panel) so each phase becomes its own uploaded `turn_{N}` artifact. No-op
|
||||
/// when nothing was recorded since the last flush.
|
||||
pub fn flush_harness_trace_turn(&self) {
|
||||
let _ = self.cmd_tx.send(ChatStateCommand::FlushHarnessTraceTurn);
|
||||
}
|
||||
|
||||
/// Repair dangling tool calls after a harness-initiated halt.
|
||||
pub fn repair_dangling_after_harness_halt(&self, class: &'static str) {
|
||||
let _ = self
|
||||
.cmd_tx
|
||||
.send(ChatStateCommand::RepairDanglingAfterHarnessHalt { class });
|
||||
}
|
||||
|
||||
// ═══ Async queries (via oneshot) ═══
|
||||
|
||||
/// Send a query to the actor and await the reply.
|
||||
///
|
||||
/// Returns `None` when the actor is dead (channel send failure or reply
|
||||
/// dropped due to panic/cancellation). Both failure modes are logged at
|
||||
/// `error` level with `cmd_name` for post-mortem diagnostics.
|
||||
async fn query<T>(
|
||||
&self,
|
||||
cmd_name: &str,
|
||||
make_cmd: impl FnOnce(oneshot::Sender<T>) -> ChatStateCommand,
|
||||
) -> Option<T> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if self.cmd_tx.send(make_cmd(tx)).is_err() {
|
||||
tracing::error!(cmd_name, "ChatStateActor dead: send failed");
|
||||
return None;
|
||||
}
|
||||
match rx.await {
|
||||
Ok(v) => Some(v),
|
||||
Err(_) => {
|
||||
tracing::error!(cmd_name, "ChatStateActor dead: reply dropped");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a ConversationRequest from the current state.
|
||||
/// Prunes, repairs, injects memory, and returns a ready-to-send request.
|
||||
pub async fn build_request(
|
||||
&self,
|
||||
tool_definitions: Vec<ToolSpec>,
|
||||
memory_reminder: Option<String>,
|
||||
persist_memory_reminder: bool,
|
||||
trace: Option<Box<dyn TraceContext>>,
|
||||
conv_id: String,
|
||||
req_id: String,
|
||||
) -> Option<ConversationRequest> {
|
||||
self.query("BuildConversationRequest", |reply| {
|
||||
ChatStateCommand::BuildConversationRequest {
|
||||
tool_definitions,
|
||||
memory_reminder,
|
||||
persist_memory_reminder,
|
||||
trace,
|
||||
conv_id,
|
||||
req_id,
|
||||
reply,
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get a clone of the full conversation.
|
||||
pub async fn get_conversation(&self) -> Vec<ConversationItem> {
|
||||
self.query("GetConversation", |reply| {
|
||||
ChatStateCommand::GetConversation { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get current prompt index.
|
||||
pub async fn get_prompt_index(&self) -> usize {
|
||||
self.query("GetPromptIndex", |reply| ChatStateCommand::GetPromptIndex {
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Get the prompt index at which the last compaction occurred.
|
||||
/// `Some` means the context currently holds a compaction summary.
|
||||
pub async fn get_last_compaction_prompt_index(&self) -> Option<usize> {
|
||||
self.query("GetLastCompactionPromptIndex", |reply| {
|
||||
ChatStateCommand::GetLastCompactionPromptIndex { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Get total accumulated tokens.
|
||||
pub async fn get_total_tokens(&self) -> u64 {
|
||||
self.query("GetTotalTokens", |reply| ChatStateCommand::GetTotalTokens {
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Retrieve the most recent stashed per-turn `TokenUsage`. Returns
|
||||
/// `None` if no model turn has completed in this session yet, or if
|
||||
/// the actor channel is closed.
|
||||
pub async fn get_last_turn_usage(&self) -> Option<TokenUsage> {
|
||||
self.query("GetLastTurnUsage", |reply| {
|
||||
ChatStateCommand::GetLastTurnUsage { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Fail-closed prompt bill read.
|
||||
/// `Ok(None)` means the actor answered "no ledger"; `Err(())` means it did
|
||||
/// not answer at all. Never collapse `Err` to `None`: an unreadable bill
|
||||
/// must not be mistaken for a free prompt.
|
||||
pub async fn try_get_prompt_usage(&self) -> Result<Option<crate::usage::UsageLedger>, ()> {
|
||||
self.query("GetPromptUsage", |reply| ChatStateCommand::GetPromptUsage {
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.ok_or(())
|
||||
}
|
||||
|
||||
/// Fail-closed session bill read. `Err(())` if the actor is dead.
|
||||
pub async fn try_get_session_usage(&self) -> Result<crate::usage::UsageLedger, ()> {
|
||||
self.query("GetSessionUsage", |reply| {
|
||||
ChatStateCommand::GetSessionUsage { reply }
|
||||
})
|
||||
.await
|
||||
.ok_or(())
|
||||
}
|
||||
|
||||
/// `total_tokens` plus bytes/4 estimate of tool results pushed since the
|
||||
/// last model response. Used by `check_preflight_overflow`.
|
||||
pub async fn get_estimated_total_tokens(&self) -> u64 {
|
||||
self.query("GetEstimatedTotalTokens", |reply| {
|
||||
ChatStateCommand::GetEstimatedTotalTokens { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Bytes/4 estimate of all non-system conversation items.
|
||||
pub async fn get_estimated_messages_tokens(&self) -> u64 {
|
||||
self.query("GetEstimatedMessagesTokens", |reply| {
|
||||
ChatStateCommand::GetEstimatedMessagesTokens { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Get sampling config.
|
||||
pub async fn get_sampling_config(&self) -> Option<SamplingConfig> {
|
||||
self.query("GetSamplingConfig", |reply| {
|
||||
ChatStateCommand::GetSamplingConfig { reply }
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get the set of agent-edited file paths.
|
||||
pub async fn get_agent_edited_paths(&self) -> BTreeSet<String> {
|
||||
self.query("GetAgentEditedPaths", |reply| {
|
||||
ChatStateCommand::GetAgentEditedPaths { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get notification meta (timing info).
|
||||
pub async fn get_notification_meta(&self) -> Option<NotificationMeta> {
|
||||
self.query("GetNotificationMeta", |reply| {
|
||||
ChatStateCommand::GetNotificationMeta { reply }
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Snapshot state for forking or rewind.
|
||||
pub async fn snapshot(&self) -> Option<ChatStateSnapshot> {
|
||||
self.query("Snapshot", |reply| ChatStateCommand::Snapshot { reply })
|
||||
.await
|
||||
}
|
||||
|
||||
/// Truncate conversation to a target prompt index (for rewind).
|
||||
pub async fn truncate_to_prompt_index(&self, target: usize) {
|
||||
self.query("TruncateToPromptIndex", |reply| {
|
||||
ChatStateCommand::TruncateToPromptIndex {
|
||||
target_prompt_index: target,
|
||||
reply,
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Get credential secrets.
|
||||
pub async fn get_credentials(&self) -> Credentials {
|
||||
self.query("GetCredentials", |reply| ChatStateCommand::GetCredentials {
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub async fn get_last_model_metadata(&self) -> crate::commands::ModelMetadata {
|
||||
self.query("GetLastModelMetadata", |reply| {
|
||||
ChatStateCommand::GetLastModelMetadata { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Take the accumulated turn messages and end the capture.
|
||||
/// Returns `None` if no capture was active.
|
||||
pub async fn take_turn_messages(&self) -> Option<TurnCapture> {
|
||||
self.query("TakeTurnMessages", |reply| {
|
||||
ChatStateCommand::TakeTurnMessages { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Drain the sealed harness trace turns (goal planner + verifier panels).
|
||||
/// Each returned `Vec` is one turn's worth of synthetic `task` pairs,
|
||||
/// destined to be uploaded as its own sibling `turn_{N}` artifact. A
|
||||
/// trailing un-flushed accumulator is sealed defensively before draining.
|
||||
/// Returns empty when nothing was recorded (the common, non-goal case).
|
||||
pub async fn take_harness_trace_turns(&self) -> Vec<Vec<ConversationItem>> {
|
||||
self.query("TakeHarnessTraceTurns", |reply| {
|
||||
ChatStateCommand::TakeHarnessTraceTurns { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Check if auto-compact is needed.
|
||||
pub async fn check_auto_compact_needed(
|
||||
&self,
|
||||
threshold_percent: u8,
|
||||
) -> Option<AutoCompactTrigger> {
|
||||
self.query("CheckAutoCompactNeeded", |reply| {
|
||||
ChatStateCommand::CheckAutoCompactNeeded {
|
||||
threshold_percent,
|
||||
reply,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
// ═══ Narrow targeted queries ═══
|
||||
|
||||
/// Get the number of items in the conversation.
|
||||
///
|
||||
/// Cheaper than [`get_conversation`] when only the length is needed —
|
||||
/// the actor returns a single `usize` without cloning any items.
|
||||
pub async fn get_conversation_len(&self) -> usize {
|
||||
self.query("GetConversationLen", |reply| {
|
||||
ChatStateCommand::GetConversationLen { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Whether any assistant tool call lacks a matching `ToolResult` (the
|
||||
/// dangling-tool-call repair would fire on the next request build).
|
||||
///
|
||||
/// Returns `false` if the actor is dead. Cheaper than [`get_conversation`]
|
||||
/// — the actor scans in place and returns a single `bool`.
|
||||
pub async fn has_dangling_tool_calls(&self) -> bool {
|
||||
self.query("HasDanglingToolCalls", |reply| {
|
||||
ChatStateCommand::HasDanglingToolCalls { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Get the text content of the last assistant message with non-empty text.
|
||||
///
|
||||
/// Returns `None` if no such message exists or the actor is dead.
|
||||
/// Cheaper than [`get_conversation`] when only the final assistant
|
||||
/// response text is needed.
|
||||
pub async fn get_last_assistant_text(&self) -> Option<String> {
|
||||
self.query("GetLastAssistantText", |reply| {
|
||||
ChatStateCommand::GetLastAssistantText { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Get the current turn's last assistant message text, or `None` when the
|
||||
/// turn produced none (or the actor is dead). Turn-scoped, unlike
|
||||
/// [`get_last_assistant_text`], and cheaper than [`get_conversation`].
|
||||
///
|
||||
/// [`get_conversation`]: Self::get_conversation
|
||||
/// [`get_last_assistant_text`]: Self::get_last_assistant_text
|
||||
pub async fn get_last_assistant_text_in_turn(&self) -> Option<String> {
|
||||
self.query("GetLastAssistantTextInTurn", |reply| {
|
||||
ChatStateCommand::GetLastAssistantTextInTurn { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Get the text of the first `Text` content part in the first `User` message.
|
||||
///
|
||||
/// Returns `None` if no user message with text content exists or the actor
|
||||
/// is dead. Cheaper than [`get_conversation`] when only the initial user
|
||||
/// query text is needed (e.g. for memory context search).
|
||||
pub async fn get_first_user_text(&self) -> Option<String> {
|
||||
self.query("GetFirstUserText", |reply| {
|
||||
ChatStateCommand::GetFirstUserText { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Get a single conversation item by index (0-based).
|
||||
///
|
||||
/// Returns `None` if the index is out of bounds or the actor is dead.
|
||||
/// Cheaper than [`get_conversation`] when only one specific item is needed
|
||||
/// (e.g. item[1] for the original user-info block after compaction).
|
||||
pub async fn get_conversation_item_at(&self, index: usize) -> Option<ConversationItem> {
|
||||
self.query("GetConversationItemAt", |reply| {
|
||||
ChatStateCommand::GetConversationItemAt { index, reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Get the processed text of the last user query (metadata tags stripped).
|
||||
///
|
||||
/// Equivalent to `extract_last_user_query(&full_conv)` but without cloning
|
||||
/// the full conversation. Returns `None` if there are no user messages or
|
||||
/// the last user message is empty after processing.
|
||||
pub async fn get_last_user_query_text(&self) -> Option<String> {
|
||||
self.query("GetLastUserQueryText", |reply| {
|
||||
ChatStateCommand::GetLastUserQueryText { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Get item counts for the conversation by role.
|
||||
///
|
||||
/// Returns a [`ConversationCounts`] struct without cloning any items.
|
||||
/// Suitable for telemetry / logging that only needs totals.
|
||||
pub async fn get_conversation_counts(&self) -> ConversationCounts {
|
||||
self.query("GetConversationCounts", |reply| {
|
||||
ChatStateCommand::GetConversationCounts { reply }
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get the first `System` message in the conversation, if any.
|
||||
///
|
||||
/// Cheaper than [`get_conversation`] when only the system prompt is needed
|
||||
/// (e.g. for compaction setup or error validation).
|
||||
pub async fn get_system_message(&self) -> Option<ConversationItem> {
|
||||
self.query("GetSystemMessage", |reply| {
|
||||
ChatStateCommand::GetSystemMessage { reply }
|
||||
})
|
||||
.await
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn noop_handle_does_not_panic() {
|
||||
let handle = ChatStateHandle::noop();
|
||||
handle.push_user_message(ConversationItem::user("test"));
|
||||
handle.flush();
|
||||
drop(handle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_is_clone() {
|
||||
let handle = ChatStateHandle::noop();
|
||||
let clone = handle.clone();
|
||||
clone.push_user_message(ConversationItem::user("from clone"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! xai-chat-state — Actor-based chat state management for xAI agents.
|
||||
//!
|
||||
//! This crate extracts conversation state management from `xai-grok-shell`'s
|
||||
//! `acp_session.rs` into a standalone actor. It follows the same actor pattern
|
||||
//! as `xai-hunk-tracker`:
|
||||
//!
|
||||
//! ```text
|
||||
//! ┌────────────────┐ ┌──────────────────────────────────────┐
|
||||
//! │ SessionActor │ ─── Command ───▶ │ ChatStateActor │
|
||||
//! │ (push_user, │ │ (runs in dedicated tokio task) │
|
||||
//! │ build_req) │ │ │
|
||||
//! └────────────────┘ │ State (no locks needed): │
|
||||
//! │ - conversation: Vec<ConversationItem>│
|
||||
//! ┌────────────────┐ │ - sampling_config: SamplingConfig │
|
||||
//! │ Query (e.g. │ ── Cmd+Oneshot ─▶│ - prompt_index: usize │
|
||||
//! │ get_conv) │ ◀── Response ────│ - total_tokens: u64 │
|
||||
//! └────────────────┘ │ │
|
||||
//! │ │ ChatStateEvent │
|
||||
//! │ ▼ │
|
||||
//! │ ┌──────────────────┐ │
|
||||
//! │ │ event_tx │───▶ Session │
|
||||
//! │ └──────────────────┘ │
|
||||
//! └──────────────────────────────────────┘
|
||||
//! ```
|
||||
|
||||
pub mod actor;
|
||||
pub mod commands;
|
||||
pub mod compaction_mode;
|
||||
pub mod compaction_transcript;
|
||||
pub mod compaction_utils;
|
||||
pub mod conversation_util;
|
||||
pub mod events;
|
||||
pub mod handle;
|
||||
pub mod persistence;
|
||||
pub mod types;
|
||||
pub mod usage;
|
||||
|
||||
// Re-export main types for convenience
|
||||
pub use actor::ChatStateActor;
|
||||
pub use actor::state::{
|
||||
estimate_conversation_tokens, estimate_item_tokens, estimate_messages_tokens,
|
||||
estimate_system_message_tokens, estimate_tool_definition_tokens,
|
||||
estimate_tool_definitions_tokens,
|
||||
};
|
||||
pub use commands::ModelMetadata;
|
||||
pub use compaction_mode::CompactionMode;
|
||||
pub use compaction_transcript::CompactionDetail;
|
||||
pub use events::ChatStateEvent;
|
||||
pub use handle::ChatStateHandle;
|
||||
pub use persistence::{
|
||||
ChatPersistence, MockChatPersistence, MockPersistenceReceiver, NullChatPersistence,
|
||||
PersistenceRecord,
|
||||
};
|
||||
pub use types::*;
|
||||
pub use usage::{UsageLedger, UsageTotals};
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Chat persistence trait and mock implementation.
|
||||
//!
|
||||
//! The actor owns persistence exclusively (`Box<dyn ChatPersistence>`), so the
|
||||
//! trait uses `&mut self` — no locks, no atomics, no shared state.
|
||||
//! The mock uses a channel to report records to the test, keeping everything
|
||||
//! in the actor / message-passing paradigm.
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use xai_grok_sampling_types::ConversationItem;
|
||||
|
||||
/// Abstraction over chat-specific persistence operations.
|
||||
///
|
||||
/// The actor owns this exclusively via `Box<dyn ChatPersistence>`, so all
|
||||
/// methods take `&mut self` — no interior mutability needed.
|
||||
///
|
||||
/// The real implementation wraps an `mpsc::UnboundedSender<PersistenceMsg>`
|
||||
/// (which only needs `&self` to send, but `&mut self` is still correct
|
||||
/// because the actor is the sole owner).
|
||||
pub trait ChatPersistence: Send + 'static {
|
||||
/// Persist a single conversation item (append to chat_history.jsonl).
|
||||
fn persist_message(&mut self, item: &ConversationItem);
|
||||
|
||||
/// Replace the entire chat history (compaction / rewind).
|
||||
fn replace_history(&mut self, items: &[ConversationItem]);
|
||||
|
||||
/// Flush pending writes to disk.
|
||||
fn flush(&mut self);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Mock (test double) — channel-based, no locks, no atomics
|
||||
// ============================================================================
|
||||
|
||||
/// A record of a persistence call, sent over a channel to the test.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum PersistenceRecord {
|
||||
/// A single message was persisted.
|
||||
Message(ConversationItem),
|
||||
/// The full history was replaced.
|
||||
ReplaceHistory(Vec<ConversationItem>),
|
||||
/// A flush was requested.
|
||||
Flush,
|
||||
}
|
||||
|
||||
/// Test implementation: sends every call as a [`PersistenceRecord`] over a
|
||||
/// channel. The test holds the [`MockPersistenceReceiver`] to inspect what
|
||||
/// the actor did. No locks, no atomics — just message passing.
|
||||
pub struct MockChatPersistence {
|
||||
tx: mpsc::UnboundedSender<PersistenceRecord>,
|
||||
}
|
||||
|
||||
/// Receiver side of the mock. Held by the test to drain and inspect records.
|
||||
pub struct MockPersistenceReceiver {
|
||||
rx: mpsc::UnboundedReceiver<PersistenceRecord>,
|
||||
}
|
||||
|
||||
impl MockChatPersistence {
|
||||
/// Create a paired (mock, receiver). Give the mock to the actor, keep the
|
||||
/// receiver in the test.
|
||||
pub fn new() -> (Self, MockPersistenceReceiver) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
(Self { tx }, MockPersistenceReceiver { rx })
|
||||
}
|
||||
}
|
||||
|
||||
impl MockPersistenceReceiver {
|
||||
/// Drain all pending records from the channel.
|
||||
pub fn drain(&mut self) -> Vec<PersistenceRecord> {
|
||||
let mut records = Vec::new();
|
||||
while let Ok(record) = self.rx.try_recv() {
|
||||
records.push(record);
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// Collect all `Message` items received so far (drains the channel).
|
||||
pub fn messages(&mut self) -> Vec<ConversationItem> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|r| match r {
|
||||
PersistenceRecord::Message(item) => Some(item),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatPersistence for MockChatPersistence {
|
||||
fn persist_message(&mut self, item: &ConversationItem) {
|
||||
let _ = self.tx.send(PersistenceRecord::Message(item.clone()));
|
||||
}
|
||||
|
||||
fn replace_history(&mut self, items: &[ConversationItem]) {
|
||||
let _ = self
|
||||
.tx
|
||||
.send(PersistenceRecord::ReplaceHistory(items.to_vec()));
|
||||
}
|
||||
|
||||
fn flush(&mut self) {
|
||||
let _ = self.tx.send(PersistenceRecord::Flush);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Null (noop) — for benchmarks / scenarios where persistence is unwanted
|
||||
// ============================================================================
|
||||
|
||||
/// No-op implementation: discards everything (for benchmarks / noop scenarios).
|
||||
pub struct NullChatPersistence;
|
||||
|
||||
impl ChatPersistence for NullChatPersistence {
|
||||
fn persist_message(&mut self, _item: &ConversationItem) {}
|
||||
fn replace_history(&mut self, _items: &[ConversationItem]) {}
|
||||
fn flush(&mut self) {}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mock_persistence_records_messages() {
|
||||
let (mut mock, mut rx) = MockChatPersistence::new();
|
||||
let item = ConversationItem::system("test");
|
||||
mock.persist_message(&item);
|
||||
let records = rx.drain();
|
||||
assert_eq!(records.len(), 1);
|
||||
assert!(matches!(&records[0], PersistenceRecord::Message(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mock_persistence_records_multiple_messages() {
|
||||
let (mut mock, mut rx) = MockChatPersistence::new();
|
||||
mock.persist_message(&ConversationItem::system("a"));
|
||||
mock.persist_message(&ConversationItem::user("b"));
|
||||
mock.persist_message(&ConversationItem::assistant("c"));
|
||||
assert_eq!(rx.messages().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mock_persistence_records_replace_history() {
|
||||
let (mut mock, mut rx) = MockChatPersistence::new();
|
||||
mock.replace_history(&[ConversationItem::system("a"), ConversationItem::system("b")]);
|
||||
let records = rx.drain();
|
||||
assert_eq!(records.len(), 1);
|
||||
match &records[0] {
|
||||
PersistenceRecord::ReplaceHistory(items) => assert_eq!(items.len(), 2),
|
||||
other => panic!("expected ReplaceHistory, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mock_persistence_records_flush() {
|
||||
let (mut mock, mut rx) = MockChatPersistence::new();
|
||||
mock.flush();
|
||||
mock.flush();
|
||||
let records = rx.drain();
|
||||
assert_eq!(records.len(), 2);
|
||||
assert!(
|
||||
records
|
||||
.iter()
|
||||
.all(|r| matches!(r, PersistenceRecord::Flush))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_persistence_does_not_panic() {
|
||||
let mut null = NullChatPersistence;
|
||||
null.persist_message(&ConversationItem::system("test"));
|
||||
null.replace_history(&[ConversationItem::user("a")]);
|
||||
null.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! Shared domain types for the chat state actor.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use xai_grok_sampling_types::{ConversationItem, SamplingConfig};
|
||||
|
||||
/// Canonical marker for an injected memory-context block. Shared by the
|
||||
/// emitter in `xai-grok-shell` and the upsert/detection here — a drift would
|
||||
/// silently break dedup and let blocks accumulate in the prompt prefix.
|
||||
/// Detection assumes the literal never appears in a system prompt except as
|
||||
/// an injected block.
|
||||
pub const MEMORY_CONTEXT_OPEN_TAG: &str = "<memory-context>";
|
||||
|
||||
/// Closing tag paired with [`MEMORY_CONTEXT_OPEN_TAG`].
|
||||
pub const MEMORY_CONTEXT_CLOSE_TAG: &str = "</memory-context>";
|
||||
|
||||
/// Configuration for the ChatStateActor at spawn time.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChatStateConfig {
|
||||
/// Initial conversation items to populate the state with.
|
||||
pub initial_conversation: Vec<ConversationItem>,
|
||||
/// Sampling configuration (model, context window, etc.).
|
||||
pub sampling_config: SamplingConfig,
|
||||
}
|
||||
|
||||
/// Immutable snapshot of the actor's state (for forking, rewind).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChatStateSnapshot {
|
||||
/// The full conversation history.
|
||||
pub conversation: Vec<ConversationItem>,
|
||||
/// Current sampling configuration.
|
||||
pub sampling_config: SamplingConfig,
|
||||
/// Current prompt index (incremented per user turn).
|
||||
pub prompt_index: usize,
|
||||
/// Accumulated token usage.
|
||||
pub total_tokens: u64,
|
||||
/// Bytes/4 estimate of the conversation as of the last `record_token_usage`.
|
||||
/// `0` means unknown (pre-field snapshot); restore re-estimates instead.
|
||||
#[serde(default)]
|
||||
pub estimate_at_last_response: u64,
|
||||
/// File paths the agent has edited.
|
||||
pub agent_edited_paths: BTreeSet<String>,
|
||||
/// Cached prompt texts for rewind preview.
|
||||
pub prompt_texts: Vec<String>,
|
||||
/// Timestamp when the current stream started (epoch ms).
|
||||
pub stream_start_ms: Option<i64>,
|
||||
/// Timestamp when the current turn started (epoch ms).
|
||||
pub turn_start_ms: Option<i64>,
|
||||
/// Prompt index at which the last compaction occurred.
|
||||
pub last_compaction_prompt_index: Option<usize>,
|
||||
/// Opaque credential secrets (API key, optional extra auth, client version).
|
||||
#[serde(default)]
|
||||
pub credentials: Credentials,
|
||||
}
|
||||
|
||||
/// Metadata for session notifications (timing info).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NotificationMeta {
|
||||
/// Timestamp when the current stream started (epoch ms).
|
||||
pub stream_start_ms: Option<i64>,
|
||||
/// Timestamp when the current turn started (epoch ms).
|
||||
pub turn_start_ms: Option<i64>,
|
||||
}
|
||||
|
||||
/// Configuration for tool-result pruning.
|
||||
///
|
||||
/// Prunes old, large tool results from the conversation to reclaim context space.
|
||||
/// Two modes: soft trim (keep head + tail) and hard clear (replace entirely).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PruningConfig {
|
||||
/// Whether pruning is enabled.
|
||||
pub enabled: bool,
|
||||
/// Number of recent turns whose tool results are never pruned.
|
||||
pub keep_last_n_turns: usize,
|
||||
/// Character threshold above which old tool results are soft-trimmed.
|
||||
pub soft_trim_threshold: usize,
|
||||
/// Characters to keep from the start of a soft-trimmed result.
|
||||
pub soft_trim_head: usize,
|
||||
/// Characters to keep from the end of a soft-trimmed result.
|
||||
pub soft_trim_tail: usize,
|
||||
/// Turn age after which tool results are hard-cleared (replaced with placeholder).
|
||||
pub hard_clear_age_turns: usize,
|
||||
}
|
||||
|
||||
impl Default for PruningConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
keep_last_n_turns: 3,
|
||||
soft_trim_threshold: 4000,
|
||||
soft_trim_head: 1500,
|
||||
soft_trim_tail: 1500,
|
||||
hard_clear_age_turns: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the session's current api_key came from.
|
||||
/// Determines whether the key can be refreshed.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AuthType {
|
||||
/// From AuthManager (grok login, OIDC, external binary). Refreshable.
|
||||
#[default]
|
||||
SessionToken,
|
||||
/// From user config ([model.*] api_key, env_key, XAI_API_KEY). Not refreshable.
|
||||
ApiKey,
|
||||
}
|
||||
|
||||
/// Credential/secret fields that the actor stores opaquely.
|
||||
///
|
||||
/// These are fields from the shell's full `Config` that aren't part of
|
||||
/// `xai_grok_sampling_types::SamplingConfig` (which is secret-free).
|
||||
/// The actor just stores and returns them — it never interprets them.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Credentials {
|
||||
/// API key for authentication.
|
||||
pub api_key: Option<String>,
|
||||
/// Whether this is a session token (refreshable) or user-provided api key.
|
||||
#[serde(default)]
|
||||
pub auth_type: AuthType,
|
||||
/// Optional extra auth material forwarded with requests when present.
|
||||
pub alpha_test_key: Option<String>,
|
||||
/// Client version string.
|
||||
pub client_version: Option<String>,
|
||||
}
|
||||
|
||||
/// The messages captured during a single conversation turn.
|
||||
///
|
||||
/// Produced by `TakeTurnMessages` after a `BeginTurnCapture`/message-push cycle.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TurnCapture {
|
||||
/// The ordered sequence of messages appended during this turn.
|
||||
pub messages: Vec<ConversationItem>,
|
||||
/// Whether compaction (conversation replacement) occurred mid-turn.
|
||||
pub compaction_occurred: bool,
|
||||
}
|
||||
|
||||
/// Item counts for a conversation, broken down by role.
|
||||
///
|
||||
/// Returned by `get_conversation_counts()` — avoids cloning the conversation
|
||||
/// when only role counts and total length are needed (e.g. for telemetry).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ConversationCounts {
|
||||
/// Total number of items in the conversation.
|
||||
pub total: usize,
|
||||
/// Number of `User` items.
|
||||
pub user: usize,
|
||||
/// Number of `Assistant` items.
|
||||
pub assistant: usize,
|
||||
/// Number of `ToolResult` items.
|
||||
pub tool_result: usize,
|
||||
}
|
||||
|
||||
/// Info returned when auto-compact threshold is exceeded.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AutoCompactTrigger {
|
||||
/// Current total token count.
|
||||
pub total_tokens: u64,
|
||||
/// Model's context window size.
|
||||
pub context_window: NonZeroU64,
|
||||
/// Current utilization as a percentage (0–100).
|
||||
pub utilization_percent: u8,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn snapshot_round_trips_through_serde_json() {
|
||||
let snapshot = ChatStateSnapshot {
|
||||
conversation: vec![],
|
||||
sampling_config: SamplingConfig {
|
||||
base_url: "https://api.example.com".to_string(),
|
||||
model: "test-model".to_string(),
|
||||
max_completion_tokens: None,
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
api_backend: Default::default(),
|
||||
extra_headers: Default::default(),
|
||||
context_window: NonZeroU64::new(128_000).unwrap(),
|
||||
reasoning_effort: None,
|
||||
stream_tool_calls: None,
|
||||
},
|
||||
prompt_index: 0,
|
||||
total_tokens: 0,
|
||||
estimate_at_last_response: 0,
|
||||
agent_edited_paths: BTreeSet::new(),
|
||||
prompt_texts: vec![],
|
||||
stream_start_ms: None,
|
||||
turn_start_ms: None,
|
||||
last_compaction_prompt_index: None,
|
||||
credentials: Credentials::default(),
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&snapshot).expect("serialize");
|
||||
let deserialized: ChatStateSnapshot = serde_json::from_str(&json).expect("deserialize");
|
||||
|
||||
assert_eq!(deserialized.prompt_index, 0);
|
||||
assert_eq!(deserialized.total_tokens, 0);
|
||||
assert!(deserialized.conversation.is_empty());
|
||||
assert!(deserialized.agent_edited_paths.is_empty());
|
||||
assert!(deserialized.last_compaction_prompt_index.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_round_trips_with_data() {
|
||||
use xai_grok_sampling_types::ConversationItem;
|
||||
|
||||
let snapshot = ChatStateSnapshot {
|
||||
conversation: vec![
|
||||
ConversationItem::system("You are a helpful assistant."),
|
||||
ConversationItem::user("Hello!"),
|
||||
ConversationItem::assistant("Hi there!"),
|
||||
],
|
||||
sampling_config: SamplingConfig {
|
||||
base_url: "https://api.example.com".to_string(),
|
||||
model: "grok-3".to_string(),
|
||||
max_completion_tokens: Some(4096),
|
||||
temperature: Some(0.7),
|
||||
top_p: None,
|
||||
api_backend: Default::default(),
|
||||
extra_headers: Default::default(),
|
||||
context_window: NonZeroU64::new(128_000).unwrap(),
|
||||
reasoning_effort: None,
|
||||
stream_tool_calls: None,
|
||||
},
|
||||
prompt_index: 5,
|
||||
total_tokens: 1234,
|
||||
estimate_at_last_response: 900,
|
||||
agent_edited_paths: BTreeSet::from([
|
||||
"src/main.rs".to_string(),
|
||||
"src/lib.rs".to_string(),
|
||||
]),
|
||||
prompt_texts: vec!["first prompt".to_string(), "second prompt".to_string()],
|
||||
stream_start_ms: Some(1234567890),
|
||||
turn_start_ms: Some(1234567800),
|
||||
last_compaction_prompt_index: Some(2),
|
||||
credentials: Credentials::default(),
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&snapshot).expect("serialize");
|
||||
let deserialized: ChatStateSnapshot = serde_json::from_str(&json).expect("deserialize");
|
||||
|
||||
assert_eq!(deserialized.prompt_index, 5);
|
||||
assert_eq!(deserialized.total_tokens, 1234);
|
||||
assert_eq!(deserialized.conversation.len(), 3);
|
||||
assert_eq!(deserialized.agent_edited_paths.len(), 2);
|
||||
assert_eq!(deserialized.prompt_texts.len(), 2);
|
||||
assert_eq!(deserialized.stream_start_ms, Some(1234567890));
|
||||
assert_eq!(deserialized.turn_start_ms, Some(1234567800));
|
||||
assert_eq!(deserialized.last_compaction_prompt_index, Some(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Per-prompt and per-session billing ledgers (not serialized).
|
||||
//!
|
||||
//! `total_tokens()` is input + output: Responses wire `total` is live context
|
||||
//! length. Compaction and other side calls never call `record_main_loop_call`.
|
||||
//!
|
||||
//! # Completeness ownership
|
||||
//!
|
||||
//! Wire incomplete is the OR of these stores (each has a distinct role):
|
||||
//!
|
||||
//! - **`UsageLedger.incomplete`** — durable on the bill snapshot. Set by nested
|
||||
//! subagent incomplete fold, drain timeout, true apply-miss, and
|
||||
//! `mark_usage_incomplete`. Monotonic for a ledger instance.
|
||||
//! - **Sticky (`subagent_usage_not_applied` on the coordinator)** — pin-scoped
|
||||
//! **report** signal (session-only attribution or apply-miss report). Not a
|
||||
//! second token sink; does not stain ledgers by itself.
|
||||
//! - **Foreground live IDs** — fold may still land; freeze drains ≤120s or fails
|
||||
//! closed. Cancel skips multi-second drain (actor-loop safety).
|
||||
//! - **Background live** — never waits; prompt report incomplete immediately;
|
||||
//! spend still folds into the session ledger at completion (no session-ledger
|
||||
//! incomplete).
|
||||
//!
|
||||
//! Freeze and cancel share one outcome policy: ledger marks only on fail-closed;
|
||||
//! sticky and background_live are report-level only.
|
||||
//!
|
||||
//! Projection (`PromptUsage`) never invents tokens; it only ORs completeness
|
||||
//! and scrubs costs when partial or incomplete.
|
||||
|
||||
use indexmap::IndexMap;
|
||||
use xai_grok_sampling_types::TokenUsage;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct UsageTotals {
|
||||
pub input_tokens: u64,
|
||||
pub output_tokens: u64,
|
||||
pub cached_read_tokens: u64,
|
||||
pub reasoning_tokens: u64,
|
||||
pub model_calls: u64,
|
||||
pub api_duration_ms: u64,
|
||||
/// USD ticks (1e10 per USD). Absent when no call reported cost.
|
||||
pub cost_usd_ticks: Option<i64>,
|
||||
pub cost_missing_calls: u64,
|
||||
}
|
||||
|
||||
impl UsageTotals {
|
||||
fn from_call(
|
||||
usage: &TokenUsage,
|
||||
api_duration_ms: Option<u64>,
|
||||
cost_usd_ticks: Option<i64>,
|
||||
) -> Self {
|
||||
let cost_usd_ticks = xai_grok_sampling_types::reported_cost_ticks(cost_usd_ticks);
|
||||
Self {
|
||||
input_tokens: u64::from(usage.prompt_tokens),
|
||||
output_tokens: u64::from(usage.completion_tokens),
|
||||
cached_read_tokens: u64::from(usage.cached_prompt_tokens),
|
||||
reasoning_tokens: u64::from(usage.reasoning_tokens),
|
||||
model_calls: 1,
|
||||
api_duration_ms: api_duration_ms.unwrap_or(0),
|
||||
cost_usd_ticks,
|
||||
cost_missing_calls: u64::from(cost_usd_ticks.is_none()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn total_tokens(&self) -> u64 {
|
||||
self.input_tokens.saturating_add(self.output_tokens)
|
||||
}
|
||||
|
||||
pub fn cost_is_partial(&self) -> bool {
|
||||
self.cost_usd_ticks.is_some() && self.cost_missing_calls > 0
|
||||
}
|
||||
|
||||
fn fold_totals(&mut self, other: &UsageTotals) {
|
||||
let Self {
|
||||
input_tokens,
|
||||
output_tokens,
|
||||
cached_read_tokens,
|
||||
reasoning_tokens,
|
||||
model_calls,
|
||||
api_duration_ms,
|
||||
cost_usd_ticks,
|
||||
cost_missing_calls,
|
||||
} = other;
|
||||
self.input_tokens = self.input_tokens.saturating_add(*input_tokens);
|
||||
self.output_tokens = self.output_tokens.saturating_add(*output_tokens);
|
||||
self.cached_read_tokens = self.cached_read_tokens.saturating_add(*cached_read_tokens);
|
||||
self.reasoning_tokens = self.reasoning_tokens.saturating_add(*reasoning_tokens);
|
||||
self.model_calls = self.model_calls.saturating_add(*model_calls);
|
||||
self.api_duration_ms = self.api_duration_ms.saturating_add(*api_duration_ms);
|
||||
self.cost_missing_calls = self.cost_missing_calls.saturating_add(*cost_missing_calls);
|
||||
self.cost_usd_ticks = merge_cost_ticks(self.cost_usd_ticks, *cost_usd_ticks);
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_cost_ticks(a: Option<i64>, b: Option<i64>) -> Option<i64> {
|
||||
match (a, b) {
|
||||
(None, None) => None,
|
||||
(a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct UsageLedger {
|
||||
pub totals: UsageTotals,
|
||||
pub by_model: IndexMap<String, UsageTotals>,
|
||||
/// Main-agent loop rounds for `num_turns` (subagents excluded).
|
||||
pub main_loop_model_calls: u64,
|
||||
/// Bill may under-count (drain timeout, nested subagent incomplete, apply failure).
|
||||
pub incomplete: bool,
|
||||
}
|
||||
|
||||
impl UsageLedger {
|
||||
/// Fold one main-agent-loop model call. This is the only writer of
|
||||
/// `main_loop_model_calls` (the wire `numTurns`); side calls such as
|
||||
/// compaction must not use it.
|
||||
pub fn record_main_loop_call(
|
||||
&mut self,
|
||||
model_id: &str,
|
||||
usage: &TokenUsage,
|
||||
api_duration_ms: Option<u64>,
|
||||
cost_usd_ticks: Option<i64>,
|
||||
) {
|
||||
let call = UsageTotals::from_call(usage, api_duration_ms, cost_usd_ticks);
|
||||
self.main_loop_model_calls = self.main_loop_model_calls.saturating_add(1);
|
||||
self.fold_entry(model_id, &call);
|
||||
}
|
||||
|
||||
/// Fold subagent usage without incrementing `main_loop_model_calls`.
|
||||
pub fn record_subagent(&mut self, by_model: &[(String, UsageTotals)], incomplete: bool) {
|
||||
for (model_id, totals) in by_model {
|
||||
self.fold_entry(model_id, totals);
|
||||
}
|
||||
if incomplete {
|
||||
self.incomplete = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mark_incomplete(&mut self) {
|
||||
self.incomplete = true;
|
||||
}
|
||||
|
||||
fn fold_entry(&mut self, model_id: &str, totals: &UsageTotals) {
|
||||
self.totals.fold_totals(totals);
|
||||
self.by_model
|
||||
.entry(model_id.to_owned())
|
||||
.or_default()
|
||||
.fold_totals(totals);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tu(prompt: u32, completion: u32) -> TokenUsage {
|
||||
TokenUsage {
|
||||
prompt_tokens: prompt,
|
||||
completion_tokens: completion,
|
||||
total_tokens: 999_999,
|
||||
reasoning_tokens: 0,
|
||||
cached_prompt_tokens: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ledger_sums_partial_subagent_and_zero_cost() {
|
||||
let mut ledger = UsageLedger::default();
|
||||
ledger.record_main_loop_call("m", &tu(1, 1), None, Some(0));
|
||||
assert_eq!(ledger.totals.cost_usd_ticks, None);
|
||||
assert_eq!(ledger.totals.cost_missing_calls, 1);
|
||||
|
||||
ledger.record_main_loop_call("a", &tu(100, 10), Some(100), None);
|
||||
ledger.record_main_loop_call("a", &tu(50, 5), Some(50), Some(70));
|
||||
assert_eq!(ledger.totals.cost_usd_ticks, Some(70));
|
||||
assert!(ledger.totals.cost_is_partial());
|
||||
assert_eq!(ledger.main_loop_model_calls, 3);
|
||||
|
||||
ledger.record_subagent(
|
||||
&[(
|
||||
"b".into(),
|
||||
UsageTotals {
|
||||
input_tokens: 5,
|
||||
model_calls: 1,
|
||||
..Default::default()
|
||||
},
|
||||
)],
|
||||
false,
|
||||
);
|
||||
assert_eq!(ledger.by_model["b"].input_tokens, 5);
|
||||
assert_eq!(ledger.main_loop_model_calls, 3);
|
||||
assert_eq!(ledger.totals.model_calls, 4);
|
||||
assert!(!ledger.incomplete);
|
||||
|
||||
ledger.record_subagent(&[], true);
|
||||
assert!(ledger.incomplete);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
[package]
|
||||
license = "Apache-2.0"
|
||||
name = "xai-codebase-graph"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
description = "High-performance code graph generation using tree-sitter queries"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
[[bin]]
|
||||
name = "code-graph"
|
||||
path = "src/bin/code_graph.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "bench_index"
|
||||
path = "src/bin/bench_index.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "bench_file_listing"
|
||||
path = "src/bin/bench_file_listing.rs"
|
||||
|
||||
[dependencies]
|
||||
# Path utilities
|
||||
dunce = { workspace = true }
|
||||
xai-grok-paths = { path = "../xai-grok-paths" }
|
||||
# Graph generation
|
||||
petgraph = { workspace = true }
|
||||
serde = { workspace = true, features = ["rc"] }
|
||||
serde_json = { workspace = true, features = ["preserve_order"] }
|
||||
# Parallel processing
|
||||
rayon = { workspace = true }
|
||||
crossbeam = { workspace = true }
|
||||
num_cpus = { workspace = true }
|
||||
# Directory walking with gitignore support
|
||||
ignore = { workspace = true }
|
||||
# Git repository access
|
||||
git2 = { version = "0.20", default-features = false }
|
||||
# Fast allocators for multi-threaded workloads
|
||||
mimalloc = "0.1"
|
||||
# Fast hash for better HashMap performance
|
||||
ahash = { version = "0.8", features = ["serde"] }
|
||||
# Additional hash utilities for StringInterner
|
||||
hashbrown = "0.15"
|
||||
nohash-hasher = "0.2"
|
||||
rustc-hash = { workspace = true }
|
||||
smallvec = { workspace = true }
|
||||
# CLI argument parsing
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
# Async runtime (for oneshot channels, sync feature for blocking_recv)
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
# Logging
|
||||
tracing = { workspace = true }
|
||||
# Lazy static initialization
|
||||
once_cell = { workspace = true }
|
||||
# Concurrent hash map for deduplication registries
|
||||
dashmap = { workspace = true }
|
||||
# Parsing, keeping it here to avoid pollution
|
||||
tree-sitter = "0.25.10"
|
||||
tree-sitter-rust = "0.24.0"
|
||||
tree-sitter-typescript = "0.23.2"
|
||||
tree-sitter-python = "0.25.0"
|
||||
tree-sitter-go = "0.25.0"
|
||||
tree-sitter-javascript = "0.25.0"
|
||||
|
||||
# Unix process checking for lock staleness detection
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Benchmark for comparing git CLI vs git2 file listing.
|
||||
//!
|
||||
//! Usage: cargo run --bin bench_file_listing --release -- [path] [cli|git2|git2-index|both]
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Instant;
|
||||
|
||||
use git2::{Repository, StatusOptions};
|
||||
use xai_codebase_graph::LanguageRegistry;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let path_str = if let Some(p) = args.get(1) {
|
||||
p.clone()
|
||||
} else if let Ok(p) = std::env::var("BENCH_REPO_ROOT").or_else(|_| std::env::var("XAI_ROOT")) {
|
||||
p
|
||||
} else {
|
||||
eprintln!("Usage: bench_file_listing <path> [cli|git2|git2-index|both]");
|
||||
eprintln!("Or set BENCH_REPO_ROOT to a large checkout to bench against");
|
||||
std::process::exit(1);
|
||||
};
|
||||
let mode = args.get(2).map(|s| s.as_str()).unwrap_or("both");
|
||||
|
||||
let root_path = Path::new(&path_str);
|
||||
let registry = LanguageRegistry::new();
|
||||
|
||||
match mode {
|
||||
"cli" => {
|
||||
let start = Instant::now();
|
||||
let files = collect_files_cli(root_path, ®istry);
|
||||
let elapsed = start.elapsed();
|
||||
println!("CLI: {} files in {:?}", files.len(), elapsed);
|
||||
}
|
||||
"git2" => {
|
||||
let start = Instant::now();
|
||||
let files = collect_files_git2(root_path, ®istry);
|
||||
let elapsed = start.elapsed();
|
||||
println!("git2: {} files in {:?}", files.len(), elapsed);
|
||||
}
|
||||
"git2-index" => {
|
||||
let start = Instant::now();
|
||||
let files = collect_files_git2_index_only(root_path, ®istry);
|
||||
let elapsed = start.elapsed();
|
||||
println!("git2 (index only): {} files in {:?}", files.len(), elapsed);
|
||||
}
|
||||
_ => {
|
||||
// Run all three methods multiple times for comparison
|
||||
println!("Benchmarking file listing for: {}", root_path.display());
|
||||
println!();
|
||||
|
||||
let iterations = 5;
|
||||
|
||||
// Warm up
|
||||
let _ = collect_files_cli(root_path, ®istry);
|
||||
let _ = collect_files_git2(root_path, ®istry);
|
||||
let _ = collect_files_git2_index_only(root_path, ®istry);
|
||||
|
||||
// CLI benchmark
|
||||
let mut cli_times = Vec::with_capacity(iterations);
|
||||
let mut cli_count = 0;
|
||||
for _ in 0..iterations {
|
||||
let start = Instant::now();
|
||||
let files = collect_files_cli(root_path, ®istry);
|
||||
cli_times.push(start.elapsed());
|
||||
cli_count = files.len();
|
||||
}
|
||||
|
||||
// git2 benchmark (with untracked)
|
||||
let mut git2_times = Vec::with_capacity(iterations);
|
||||
let mut git2_count = 0;
|
||||
for _ in 0..iterations {
|
||||
let start = Instant::now();
|
||||
let files = collect_files_git2(root_path, ®istry);
|
||||
git2_times.push(start.elapsed());
|
||||
git2_count = files.len();
|
||||
}
|
||||
|
||||
// git2 index-only benchmark
|
||||
let mut git2_index_times = Vec::with_capacity(iterations);
|
||||
let mut git2_index_count = 0;
|
||||
for _ in 0..iterations {
|
||||
let start = Instant::now();
|
||||
let files = collect_files_git2_index_only(root_path, ®istry);
|
||||
git2_index_times.push(start.elapsed());
|
||||
git2_index_count = files.len();
|
||||
}
|
||||
|
||||
// Print results
|
||||
let cli_avg = cli_times.iter().sum::<std::time::Duration>() / iterations as u32;
|
||||
let git2_avg = git2_times.iter().sum::<std::time::Duration>() / iterations as u32;
|
||||
let git2_index_avg =
|
||||
git2_index_times.iter().sum::<std::time::Duration>() / iterations as u32;
|
||||
|
||||
println!("Results ({} iterations):", iterations);
|
||||
println!(
|
||||
" CLI: {} files, avg {:?}",
|
||||
cli_count, cli_avg
|
||||
);
|
||||
println!(
|
||||
" git2 (+ untracked): {} files, avg {:?}",
|
||||
git2_count, git2_avg
|
||||
);
|
||||
println!(
|
||||
" git2 (index only): {} files, avg {:?}",
|
||||
git2_index_count, git2_index_avg
|
||||
);
|
||||
println!();
|
||||
|
||||
let speedup = cli_avg.as_secs_f64() / git2_index_avg.as_secs_f64();
|
||||
if speedup > 1.0 {
|
||||
println!("git2 (index only) is {:.2}x faster than CLI", speedup);
|
||||
} else {
|
||||
println!("CLI is {:.2}x faster than git2 (index only)", 1.0 / speedup);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect files using git CLI (original approach)
|
||||
fn collect_files_cli(root_path: &Path, registry: &LanguageRegistry) -> Vec<std::path::PathBuf> {
|
||||
// Get tracked files
|
||||
let tracked_output = Command::new("git")
|
||||
.args(["ls-files"])
|
||||
.current_dir(root_path)
|
||||
.output();
|
||||
|
||||
let tracked_output = match tracked_output {
|
||||
Ok(o) if o.status.success() => o,
|
||||
_ => return vec![],
|
||||
};
|
||||
|
||||
// Get untracked files
|
||||
let untracked_output = Command::new("git")
|
||||
.args(["ls-files", "--others", "--exclude-standard"])
|
||||
.current_dir(root_path)
|
||||
.output()
|
||||
.ok();
|
||||
|
||||
let tracked_str = String::from_utf8_lossy(&tracked_output.stdout);
|
||||
let mut files: Vec<std::path::PathBuf> = tracked_str
|
||||
.lines()
|
||||
.filter(|line| registry.is_supported(Path::new(line)))
|
||||
.map(|line| root_path.join(line))
|
||||
.collect();
|
||||
|
||||
if let Some(output) = untracked_output
|
||||
&& output.status.success()
|
||||
{
|
||||
let untracked_str = String::from_utf8_lossy(&output.stdout);
|
||||
let untracked_files: Vec<std::path::PathBuf> = untracked_str
|
||||
.lines()
|
||||
.filter(|line| registry.is_supported(Path::new(line)))
|
||||
.map(|line| root_path.join(line))
|
||||
.collect();
|
||||
files.extend(untracked_files);
|
||||
}
|
||||
|
||||
files
|
||||
}
|
||||
|
||||
/// Collect files using git2 (new approach)
|
||||
fn collect_files_git2(root_path: &Path, registry: &LanguageRegistry) -> Vec<std::path::PathBuf> {
|
||||
let repo = match Repository::open(root_path) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return vec![],
|
||||
};
|
||||
|
||||
let index = match repo.index() {
|
||||
Ok(i) => i,
|
||||
Err(_) => return vec![],
|
||||
};
|
||||
|
||||
let mut files: Vec<std::path::PathBuf> = index
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let path_str = std::str::from_utf8(&entry.path).ok()?;
|
||||
if registry.is_supported(Path::new(path_str)) {
|
||||
Some(root_path.join(path_str))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Get untracked files
|
||||
let mut status_opts = StatusOptions::new();
|
||||
status_opts
|
||||
.include_untracked(true)
|
||||
.recurse_untracked_dirs(true)
|
||||
.exclude_submodules(true);
|
||||
|
||||
if let Ok(statuses) = repo.statuses(Some(&mut status_opts)) {
|
||||
for status_entry in statuses.iter() {
|
||||
if status_entry.status().is_wt_new()
|
||||
&& let Some(path_str) = status_entry.path()
|
||||
&& registry.is_supported(Path::new(path_str))
|
||||
{
|
||||
files.push(root_path.join(path_str));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
files
|
||||
}
|
||||
|
||||
/// Collect files using git2 index only (tracked files only, no untracked)
|
||||
fn collect_files_git2_index_only(
|
||||
root_path: &Path,
|
||||
registry: &LanguageRegistry,
|
||||
) -> Vec<std::path::PathBuf> {
|
||||
let repo = match Repository::open(root_path) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return vec![],
|
||||
};
|
||||
|
||||
let index = match repo.index() {
|
||||
Ok(i) => i,
|
||||
Err(_) => return vec![],
|
||||
};
|
||||
|
||||
index
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let path_str = std::str::from_utf8(&entry.path).ok()?;
|
||||
if registry.is_supported(Path::new(path_str)) {
|
||||
Some(root_path.join(path_str))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Benchmark binary for index building.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
|
||||
use xai_codebase_graph::{IndexBuilder, LanguageRegistry};
|
||||
|
||||
// Use mimalloc for faster allocation in multi-threaded workloads
|
||||
#[global_allocator]
|
||||
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let path = if let Some(p) = args.get(1) {
|
||||
p.clone()
|
||||
} else if let Ok(p) = std::env::var("BENCH_REPO_ROOT").or_else(|_| std::env::var("XAI_ROOT")) {
|
||||
p
|
||||
} else {
|
||||
eprintln!("Usage: bench_index <path>");
|
||||
eprintln!("Or set BENCH_REPO_ROOT to a large checkout to bench against");
|
||||
std::process::exit(1);
|
||||
};
|
||||
|
||||
// First, verify all queries compile
|
||||
println!("Verifying query compilation...");
|
||||
let registry = LanguageRegistry::new();
|
||||
for ext in &["ts", "tsx", "js", "jsx", "rs", "go", "py"] {
|
||||
match registry.for_extension(ext) {
|
||||
Some(config) => match config.compile_query() {
|
||||
Ok(query) => {
|
||||
println!(" .{}: OK ({} patterns)", ext, query.pattern_count());
|
||||
}
|
||||
Err(e) => {
|
||||
println!(" .{}: FAILED - {:?}", ext, e);
|
||||
}
|
||||
},
|
||||
None => println!(" .{}: NOT SUPPORTED", ext),
|
||||
}
|
||||
}
|
||||
println!();
|
||||
|
||||
let root_path = Path::new(&path);
|
||||
|
||||
println!("Building index for: {}", root_path.display());
|
||||
let start = Instant::now();
|
||||
|
||||
let index = IndexBuilder::new()
|
||||
.build(root_path)
|
||||
.expect("Failed to build index");
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
let (file_count, defs, refs) = index.stats();
|
||||
|
||||
println!("Files indexed: {}", file_count);
|
||||
println!(
|
||||
"Indexed {} definitions, {} references in {:?}",
|
||||
defs, refs, elapsed
|
||||
);
|
||||
println!("Aliases: {}", index.alias_count());
|
||||
println!(
|
||||
"Files/sec: {:.0}",
|
||||
file_count as f64 / elapsed.as_secs_f64()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
//! CLI tool for code graph navigation.
|
||||
//!
|
||||
//! Provides go-to-definition and go-to-references functionality.
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! ```bash
|
||||
//! # Build the index for a repository
|
||||
//! code-graph index /path/to/repo
|
||||
//!
|
||||
//! # Build the index with custom cache location
|
||||
//! code-graph index /path/to/repo --cache /path/to/cache.bin
|
||||
//!
|
||||
//! # Go to definition (by position)
|
||||
//! code-graph definition /path/to/repo --file src/main.rs --row 10 --col 15
|
||||
//!
|
||||
//! # Go to definition (by symbol name)
|
||||
//! code-graph definition /path/to/repo --symbol MyStruct
|
||||
//!
|
||||
//! # Go to references (by position)
|
||||
//! code-graph references /path/to/repo --file src/main.rs --row 10 --col 15
|
||||
//!
|
||||
//! # Go to references (by symbol name)
|
||||
//! code-graph references /path/to/repo --symbol MyStruct
|
||||
//!
|
||||
//! # Show index statistics
|
||||
//! code-graph stats /path/to/repo
|
||||
//! ```
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use xai_codebase_graph::{
|
||||
IndexBuilder, Navigator, ScopeGraphIndex, get_cache_path, load_index, save_index,
|
||||
};
|
||||
|
||||
// Use mimalloc for faster allocation
|
||||
#[global_allocator]
|
||||
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "code-graph")]
|
||||
#[command(author, version, about = "High-performance code navigation tool", long_about = None)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Build or rebuild the index for a repository
|
||||
Index {
|
||||
/// Path to the repository
|
||||
path: PathBuf,
|
||||
/// Custom cache file path (default: <repo>/.goto_index.bin)
|
||||
#[arg(short, long)]
|
||||
cache: Option<PathBuf>,
|
||||
/// Force rebuild even if cache exists
|
||||
#[arg(short, long)]
|
||||
force: bool,
|
||||
/// Number of threads to use
|
||||
#[arg(short, long)]
|
||||
threads: Option<usize>,
|
||||
},
|
||||
|
||||
/// Go to definition for a symbol
|
||||
Definition {
|
||||
/// Path to the repository
|
||||
path: PathBuf,
|
||||
/// Custom cache file path (default: <repo>/.goto_index.bin)
|
||||
#[arg(long)]
|
||||
cache: Option<PathBuf>,
|
||||
/// File path (for position-based lookup)
|
||||
#[arg(short, long)]
|
||||
file: Option<PathBuf>,
|
||||
/// Row number (1-indexed, for position-based lookup)
|
||||
#[arg(short, long)]
|
||||
row: Option<usize>,
|
||||
/// Column number (1-indexed, for position-based lookup)
|
||||
#[arg(short, long)]
|
||||
col: Option<usize>,
|
||||
/// Symbol name (for direct lookup)
|
||||
#[arg(short, long)]
|
||||
symbol: Option<String>,
|
||||
/// Output as JSON
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
|
||||
/// Go to references for a symbol
|
||||
References {
|
||||
/// Path to the repository
|
||||
path: PathBuf,
|
||||
/// Custom cache file path (default: <repo>/.goto_index.bin)
|
||||
#[arg(long)]
|
||||
cache: Option<PathBuf>,
|
||||
/// File path (for position-based lookup)
|
||||
#[arg(short, long)]
|
||||
file: Option<PathBuf>,
|
||||
/// Row number (1-indexed, for position-based lookup)
|
||||
#[arg(short, long)]
|
||||
row: Option<usize>,
|
||||
/// Column number (1-indexed, for position-based lookup)
|
||||
#[arg(short, long)]
|
||||
col: Option<usize>,
|
||||
/// Symbol name (for direct lookup)
|
||||
#[arg(short, long)]
|
||||
symbol: Option<String>,
|
||||
/// Include definition in results
|
||||
#[arg(long)]
|
||||
include_definition: bool,
|
||||
/// Output as JSON
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
|
||||
/// Show index statistics
|
||||
Stats {
|
||||
/// Path to the repository
|
||||
path: PathBuf,
|
||||
/// Custom cache file path (default: <repo>/.goto_index.bin)
|
||||
#[arg(long)]
|
||||
cache: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
match cli.command {
|
||||
Commands::Index {
|
||||
path,
|
||||
cache,
|
||||
force,
|
||||
threads,
|
||||
} => {
|
||||
cmd_index(&path, cache.as_deref(), force, threads);
|
||||
}
|
||||
Commands::Definition {
|
||||
path,
|
||||
cache,
|
||||
file,
|
||||
row,
|
||||
col,
|
||||
symbol,
|
||||
json,
|
||||
} => {
|
||||
cmd_definition(&path, cache.as_deref(), file, row, col, symbol, json);
|
||||
}
|
||||
Commands::References {
|
||||
path,
|
||||
cache,
|
||||
file,
|
||||
row,
|
||||
col,
|
||||
symbol,
|
||||
include_definition,
|
||||
json,
|
||||
} => {
|
||||
cmd_references(
|
||||
&path,
|
||||
cache.as_deref(),
|
||||
file,
|
||||
row,
|
||||
col,
|
||||
symbol,
|
||||
include_definition,
|
||||
json,
|
||||
);
|
||||
}
|
||||
Commands::Stats { path, cache } => {
|
||||
cmd_stats(&path, cache.as_deref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the effective cache path - use custom if provided, otherwise default.
|
||||
fn effective_cache_path(repo_path: &Path, custom_cache: Option<&Path>) -> PathBuf {
|
||||
custom_cache
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| get_cache_path(repo_path))
|
||||
}
|
||||
|
||||
/// Load index from cache or build if necessary.
|
||||
fn load_or_build_index(repo_path: &Path, cache_path: &Path) -> ScopeGraphIndex {
|
||||
if let Ok(index) = load_index(cache_path) {
|
||||
println!("Loaded index from cache: {}", cache_path.display());
|
||||
return index;
|
||||
}
|
||||
|
||||
println!("Building index for: {}", repo_path.display());
|
||||
let start = Instant::now();
|
||||
|
||||
let index = IndexBuilder::new()
|
||||
.build(repo_path)
|
||||
.expect("Failed to build index");
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
let (files, defs, refs) = index.stats();
|
||||
println!(
|
||||
"Built index: {} files, {} defs, {} refs in {:?}",
|
||||
files, defs, refs, elapsed
|
||||
);
|
||||
|
||||
// Save to cache
|
||||
if let Err(e) = save_index(cache_path, &index) {
|
||||
println!("Warning: Failed to save cache: {}", e);
|
||||
} else {
|
||||
println!("Saved cache to: {}", cache_path.display());
|
||||
}
|
||||
|
||||
index
|
||||
}
|
||||
|
||||
fn cmd_index(path: &Path, custom_cache: Option<&Path>, _force: bool, threads: Option<usize>) {
|
||||
let cache_path = effective_cache_path(path, custom_cache);
|
||||
|
||||
println!("Building index for: {}", path.display());
|
||||
let start = Instant::now();
|
||||
|
||||
let mut builder = IndexBuilder::new();
|
||||
if let Some(t) = threads {
|
||||
builder = builder.with_threads(t);
|
||||
}
|
||||
|
||||
let index = builder.build(path).expect("Failed to build index");
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
let (files, defs, refs) = index.stats();
|
||||
|
||||
println!("Index built successfully!");
|
||||
println!(" Files indexed: {}", files);
|
||||
println!(" Definitions: {}", defs);
|
||||
println!(" References: {}", refs);
|
||||
println!(" Aliases: {}", index.alias_count());
|
||||
println!(" Time: {:?}", elapsed);
|
||||
|
||||
// Always save when explicitly indexing
|
||||
if let Err(e) = save_index(&cache_path, &index) {
|
||||
println!("Error saving cache: {}", e);
|
||||
std::process::exit(1);
|
||||
} else {
|
||||
println!(" Cache saved: {}", cache_path.display());
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_definition(
|
||||
repo_path: &Path,
|
||||
custom_cache: Option<&Path>,
|
||||
file: Option<PathBuf>,
|
||||
row: Option<usize>,
|
||||
col: Option<usize>,
|
||||
symbol: Option<String>,
|
||||
json: bool,
|
||||
) {
|
||||
let cache_path = effective_cache_path(repo_path, custom_cache);
|
||||
let index = load_or_build_index(repo_path, &cache_path);
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
let result = match (file, row, col, symbol) {
|
||||
// Position-based lookup
|
||||
(Some(file_path), Some(r), Some(c), _) => {
|
||||
let abs_path = if file_path.is_absolute() {
|
||||
file_path
|
||||
} else {
|
||||
repo_path.join(&file_path)
|
||||
};
|
||||
|
||||
match navigator.goto_definition(&abs_path, r, c) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
println!("Error: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Symbol-based lookup
|
||||
(_, _, _, Some(sym)) => navigator.goto_definition_by_name(&sym, None),
|
||||
_ => {
|
||||
println!("Error: Must provide either --file, --row, --col OR --symbol");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
if json {
|
||||
print_json(&result);
|
||||
} else {
|
||||
println!("Symbol: {}", result.symbol);
|
||||
println!("Definitions ({}):", result.locations.len());
|
||||
for loc in &result.locations {
|
||||
println!(" {}:{}", loc.path, loc.line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_references(
|
||||
repo_path: &Path,
|
||||
custom_cache: Option<&Path>,
|
||||
file: Option<PathBuf>,
|
||||
row: Option<usize>,
|
||||
col: Option<usize>,
|
||||
symbol: Option<String>,
|
||||
include_definition: bool,
|
||||
json: bool,
|
||||
) {
|
||||
let cache_path = effective_cache_path(repo_path, custom_cache);
|
||||
let index = load_or_build_index(repo_path, &cache_path);
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
let result = match (file, row, col, symbol) {
|
||||
// Position-based lookup
|
||||
(Some(file_path), Some(r), Some(c), _) => {
|
||||
let abs_path = if file_path.is_absolute() {
|
||||
file_path
|
||||
} else {
|
||||
repo_path.join(&file_path)
|
||||
};
|
||||
|
||||
match navigator.goto_references(&abs_path, r, c, include_definition) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
println!("Error: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Symbol-based lookup
|
||||
(_, _, _, Some(sym)) => navigator.goto_references_by_name(&sym, None, include_definition),
|
||||
_ => {
|
||||
println!("Error: Must provide either --file, --row, --col OR --symbol");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
if json {
|
||||
print_json(&result);
|
||||
} else {
|
||||
println!("Symbol: {}", result.symbol);
|
||||
println!("References ({}):", result.locations.len());
|
||||
for loc in &result.locations {
|
||||
if let Some(sym) = &loc.symbol {
|
||||
println!(" {}:{} (as {})", loc.path, loc.line, sym);
|
||||
} else {
|
||||
println!(" {}:{}", loc.path, loc.line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_stats(path: &Path, custom_cache: Option<&Path>) {
|
||||
let cache_path = effective_cache_path(path, custom_cache);
|
||||
let index = load_or_build_index(path, &cache_path);
|
||||
let (files, defs, refs) = index.stats();
|
||||
|
||||
println!("Index Statistics for: {}", path.display());
|
||||
println!(" Cache location: {}", cache_path.display());
|
||||
println!(" Files indexed: {}", files);
|
||||
println!(" Definitions: {}", defs);
|
||||
println!(" References: {}", refs);
|
||||
println!(" Aliases: {}", index.alias_count());
|
||||
|
||||
// Top symbols by reference count
|
||||
let ref_counts = index.top_referenced_symbols(10);
|
||||
|
||||
println!("\nTop 10 most referenced symbols:");
|
||||
for (name, count) in &ref_counts {
|
||||
println!(" {:6} {}", count, name);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_json(result: &xai_codebase_graph::NavigationResult) {
|
||||
use serde_json::json;
|
||||
|
||||
let locations: Vec<_> = result
|
||||
.locations
|
||||
.iter()
|
||||
.map(|loc| {
|
||||
json!({
|
||||
"path": &loc.path,
|
||||
"line": loc.line,
|
||||
"symbol": loc.symbol,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let output = json!({
|
||||
"symbol": result.symbol,
|
||||
"locations": locations,
|
||||
});
|
||||
|
||||
println!("{}", serde_json::to_string_pretty(&output).unwrap());
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,413 @@
|
||||
//! Arena-based string interner for memory-efficient string deduplication.
|
||||
//!
|
||||
//! This module provides a string interner that stores all strings in a single
|
||||
//! contiguous buffer, minimizing allocations and improving cache locality.
|
||||
//! It uses hash-based lookup for O(1) interning operations.
|
||||
//!
|
||||
//! # Design
|
||||
//!
|
||||
//! The interner uses a two-level lookup approach:
|
||||
//! 1. **Primary lookup**: HashMap from 64-bit hash -> list of StringIds with that hash
|
||||
//! 2. **Collision resolution**: When hashes collide, actual string content is compared
|
||||
//!
|
||||
//! This gives O(1) average case for both `intern()` and `get_id()` operations.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```
|
||||
//! use xai_codebase_graph::interner::StringInterner;
|
||||
//!
|
||||
//! let mut interner = StringInterner::new();
|
||||
//!
|
||||
//! let id1 = interner.intern("hello");
|
||||
//! let id2 = interner.intern("world");
|
||||
//! let id3 = interner.intern("hello"); // Returns same id as id1
|
||||
//!
|
||||
//! assert_eq!(id1, id3);
|
||||
//! assert_ne!(id1, id2);
|
||||
//! assert_eq!(interner.get(id1), Some("hello"));
|
||||
//! ```
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use hashbrown::HashMap;
|
||||
use nohash_hasher::BuildNoHashHasher;
|
||||
use rustc_hash::FxHasher;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
/// Type alias for HashMap with u64 keys that are already hashed.
|
||||
/// Uses NoHashHasher since keys don't need re-hashing.
|
||||
type U64NoHashMap<V> = HashMap<u64, V, BuildNoHashHasher<u64>>;
|
||||
|
||||
/// A compact identifier for an interned string.
|
||||
/// Using u32 allows up to 4 billion unique strings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct StringId(u32);
|
||||
|
||||
impl StringId {
|
||||
/// Create a new StringId from a raw u32 value.
|
||||
#[inline]
|
||||
pub const fn new(id: u32) -> Self {
|
||||
Self(id)
|
||||
}
|
||||
|
||||
/// Get the raw u32 value.
|
||||
#[inline]
|
||||
pub const fn as_u32(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Arena-based string interner for efficient string deduplication.
|
||||
///
|
||||
/// Stores all strings in a single contiguous buffer to minimize allocations
|
||||
/// and improve cache locality. Uses a hash-based lookup for O(1) interning.
|
||||
///
|
||||
/// The interner stores arbitrary byte sequences, supporting paths and strings
|
||||
/// that may not be valid UTF-8.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StringInterner {
|
||||
/// Contiguous storage for all interned byte strings
|
||||
arena: Vec<u8>,
|
||||
/// Maps hash -> StringId(s). Most buckets have exactly one entry.
|
||||
/// Using SmallVec<[StringId; 1]> optimizes for the common case of no collisions.
|
||||
/// Uses NoHashHasher since keys are already hashed.
|
||||
lookup: U64NoHashMap<SmallVec<[StringId; 1]>>,
|
||||
/// Maps StringId to (start, len) in arena
|
||||
offsets: Vec<(u32, u16)>,
|
||||
}
|
||||
|
||||
impl Default for StringInterner {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl StringInterner {
|
||||
/// Create a new empty interner.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
arena: Vec::new(),
|
||||
lookup: U64NoHashMap::default(),
|
||||
offsets: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an interner with pre-allocated capacity.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `string_bytes` - Estimated total bytes for all strings
|
||||
/// * `num_strings` - Estimated number of unique strings
|
||||
pub fn with_capacity(string_bytes: usize, num_strings: usize) -> Self {
|
||||
Self {
|
||||
arena: Vec::with_capacity(string_bytes),
|
||||
lookup: U64NoHashMap::with_capacity_and_hasher(
|
||||
num_strings,
|
||||
BuildNoHashHasher::default(),
|
||||
),
|
||||
offsets: Vec::with_capacity(num_strings),
|
||||
}
|
||||
}
|
||||
|
||||
/// Intern a byte string, returning its StringId.
|
||||
/// If the string is already interned, returns the existing id.
|
||||
///
|
||||
/// # Complexity
|
||||
/// O(1) average case, O(k) worst case where k is the number of
|
||||
/// hash collisions (typically 0 or 1).
|
||||
pub fn intern_bytes(&mut self, s: &[u8]) -> StringId {
|
||||
let hash = Self::hash_bytes(s);
|
||||
|
||||
// Check if already interned
|
||||
if let Some(ids) = self.lookup.get(&hash) {
|
||||
for &id in ids {
|
||||
if self.get_bytes(id) == Some(s) {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Not found, add new
|
||||
let start = self.arena.len() as u32;
|
||||
let len = s.len() as u16;
|
||||
|
||||
self.arena.extend_from_slice(s);
|
||||
|
||||
let id = StringId::new(self.offsets.len() as u32);
|
||||
self.offsets.push((start, len));
|
||||
|
||||
// Add to lookup
|
||||
self.lookup.entry(hash).or_default().push(id);
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Intern a UTF-8 string. Convenience wrapper around `intern_bytes`.
|
||||
#[inline]
|
||||
pub fn intern(&mut self, s: &str) -> StringId {
|
||||
self.intern_bytes(s.as_bytes())
|
||||
}
|
||||
|
||||
/// Get the StringId for a byte string without interning it.
|
||||
/// Returns None if the string is not in the interner.
|
||||
///
|
||||
/// # Complexity
|
||||
/// O(1) average case.
|
||||
pub fn get_bytes_id(&self, s: &[u8]) -> Option<StringId> {
|
||||
let hash = Self::hash_bytes(s);
|
||||
|
||||
if let Some(ids) = self.lookup.get(&hash) {
|
||||
for &id in ids {
|
||||
if self.get_bytes(id) == Some(s) {
|
||||
return Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Get the StringId for a UTF-8 string without interning it.
|
||||
#[inline]
|
||||
pub fn get_id(&self, s: &str) -> Option<StringId> {
|
||||
self.get_bytes_id(s.as_bytes())
|
||||
}
|
||||
|
||||
/// Get the raw bytes for a StringId.
|
||||
///
|
||||
/// # Complexity
|
||||
/// O(1)
|
||||
pub fn get_bytes(&self, id: StringId) -> Option<&[u8]> {
|
||||
let (start, len) = *self.offsets.get(id.0 as usize)?;
|
||||
self.arena
|
||||
.get(start as usize..(start as usize + len as usize))
|
||||
}
|
||||
|
||||
/// Get the string for a StringId, if it's valid UTF-8.
|
||||
///
|
||||
/// # Complexity
|
||||
/// O(1)
|
||||
pub fn get(&self, id: StringId) -> Option<&str> {
|
||||
self.get_bytes(id).and_then(|b| std::str::from_utf8(b).ok())
|
||||
}
|
||||
|
||||
/// Get the string for a StringId, with lossy UTF-8 conversion.
|
||||
/// Invalid UTF-8 sequences are replaced with the replacement character.
|
||||
pub fn get_lossy(&self, id: StringId) -> Option<std::borrow::Cow<'_, str>> {
|
||||
self.get_bytes(id).map(String::from_utf8_lossy)
|
||||
}
|
||||
|
||||
/// Number of interned strings.
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize {
|
||||
self.offsets.len()
|
||||
}
|
||||
|
||||
/// Check if the interner is empty.
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.offsets.is_empty()
|
||||
}
|
||||
|
||||
/// Total bytes used by the arena.
|
||||
#[inline]
|
||||
pub fn arena_bytes(&self) -> usize {
|
||||
self.arena.len()
|
||||
}
|
||||
|
||||
/// Compute FxHash of a byte slice.
|
||||
#[inline]
|
||||
fn hash_bytes(s: &[u8]) -> u64 {
|
||||
let mut hasher = FxHasher::default();
|
||||
s.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Iterate over all strings with their IDs (only valid UTF-8).
|
||||
pub fn iter(&self) -> impl Iterator<Item = (StringId, &str)> {
|
||||
self.offsets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, &(start, len))| {
|
||||
let bytes = self
|
||||
.arena
|
||||
.get(start as usize..(start as usize + len as usize))?;
|
||||
let s = std::str::from_utf8(bytes).ok()?;
|
||||
Some((StringId::new(idx as u32), s))
|
||||
})
|
||||
}
|
||||
|
||||
/// Iterate over all byte strings with their IDs.
|
||||
pub fn iter_bytes(&self) -> impl Iterator<Item = (StringId, &[u8])> {
|
||||
self.offsets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, &(start, len))| {
|
||||
let bytes = self
|
||||
.arena
|
||||
.get(start as usize..(start as usize + len as usize))?;
|
||||
Some((StringId::new(idx as u32), bytes))
|
||||
})
|
||||
}
|
||||
|
||||
/// Clear the interner, removing all strings but keeping allocated capacity.
|
||||
pub fn clear(&mut self) {
|
||||
self.arena.clear();
|
||||
self.lookup.clear();
|
||||
self.offsets.clear();
|
||||
}
|
||||
|
||||
/// Get the internal arena for serialization purposes.
|
||||
pub fn arena(&self) -> &[u8] {
|
||||
&self.arena
|
||||
}
|
||||
|
||||
/// Get the internal offsets for serialization purposes.
|
||||
pub fn offsets(&self) -> &[(u32, u16)] {
|
||||
&self.offsets
|
||||
}
|
||||
|
||||
/// Release over-allocated capacity in the arena and offsets buffers.
|
||||
///
|
||||
/// After a bulk build the arena and offsets Vecs may hold up to 2× their
|
||||
/// actual content due to doubling growth. Calling this reclaims that
|
||||
/// wasted heap. The lookup table is intentionally left unshrunk because
|
||||
/// it benefits from load-factor headroom.
|
||||
///
|
||||
/// This is an internal maintenance hook called by `ScopeGraphIndex::compact()`.
|
||||
pub(crate) fn shrink_to_fit(&mut self) {
|
||||
self.arena.shrink_to_fit();
|
||||
self.offsets.shrink_to_fit();
|
||||
}
|
||||
|
||||
/// Reconstruct an interner from serialized data.
|
||||
///
|
||||
/// This rebuilds the lookup table from the arena and offsets.
|
||||
pub fn from_parts(arena: Vec<u8>, offsets: Vec<(u32, u16)>) -> Self {
|
||||
let mut lookup: U64NoHashMap<SmallVec<[StringId; 1]>> =
|
||||
U64NoHashMap::with_capacity_and_hasher(offsets.len(), BuildNoHashHasher::default());
|
||||
|
||||
for (idx, &(start, len)) in offsets.iter().enumerate() {
|
||||
if let Some(bytes) = arena.get(start as usize..(start as usize + len as usize)) {
|
||||
let hash = Self::hash_bytes(bytes);
|
||||
let id = StringId::new(idx as u32);
|
||||
lookup.entry(hash).or_default().push(id);
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
arena,
|
||||
lookup,
|
||||
offsets,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_basic_interning() {
|
||||
let mut interner = StringInterner::new();
|
||||
|
||||
let id1 = interner.intern("src");
|
||||
let id2 = interner.intern("lib");
|
||||
let id3 = interner.intern("src"); // duplicate
|
||||
|
||||
assert_eq!(id1, id3);
|
||||
assert_ne!(id1, id2);
|
||||
assert_eq!(interner.get(id1), Some("src"));
|
||||
assert_eq!(interner.get(id2), Some("lib"));
|
||||
assert_eq!(interner.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_id() {
|
||||
let mut interner = StringInterner::new();
|
||||
|
||||
let id_src = interner.intern("src");
|
||||
let id_lib = interner.intern("lib");
|
||||
|
||||
assert_eq!(interner.get_id("src"), Some(id_src));
|
||||
assert_eq!(interner.get_id("lib"), Some(id_lib));
|
||||
assert_eq!(interner.get_id("nonexistent"), None);
|
||||
|
||||
// get_id should not modify the interner
|
||||
assert_eq!(interner.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bytes_interning() {
|
||||
let mut interner = StringInterner::new();
|
||||
|
||||
// Valid UTF-8
|
||||
let id1 = interner.intern_bytes(b"hello");
|
||||
assert_eq!(interner.get(id1), Some("hello"));
|
||||
|
||||
// Invalid UTF-8
|
||||
let invalid_utf8: &[u8] = &[0x80, 0x81, 0x82];
|
||||
let id2 = interner.intern_bytes(invalid_utf8);
|
||||
assert_eq!(interner.get(id2), None); // Not valid UTF-8
|
||||
assert_eq!(interner.get_bytes(id2), Some(invalid_utf8));
|
||||
|
||||
// Duplicate bytes return same ID
|
||||
let id3 = interner.intern_bytes(invalid_utf8);
|
||||
assert_eq!(id2, id3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_many_strings() {
|
||||
let mut interner = StringInterner::new();
|
||||
|
||||
let count = 10_000;
|
||||
let mut ids = Vec::with_capacity(count);
|
||||
|
||||
for i in 0..count {
|
||||
let s = format!("string_{}", i);
|
||||
ids.push(interner.intern(&s));
|
||||
}
|
||||
|
||||
assert_eq!(interner.len(), count);
|
||||
|
||||
// Verify all strings can be looked up
|
||||
for (i, &id) in ids.iter().enumerate() {
|
||||
let s = format!("string_{}", i);
|
||||
assert_eq!(interner.get_id(&s), Some(id));
|
||||
assert_eq!(interner.get(id), Some(s.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_parts() {
|
||||
let mut interner = StringInterner::new();
|
||||
interner.intern("hello");
|
||||
interner.intern("world");
|
||||
interner.intern("foo");
|
||||
|
||||
let arena = interner.arena().to_vec();
|
||||
let offsets = interner.offsets().to_vec();
|
||||
|
||||
let restored = StringInterner::from_parts(arena, offsets);
|
||||
|
||||
assert_eq!(restored.len(), 3);
|
||||
assert_eq!(restored.get_id("hello"), Some(StringId::new(0)));
|
||||
assert_eq!(restored.get_id("world"), Some(StringId::new(1)));
|
||||
assert_eq!(restored.get_id("foo"), Some(StringId::new(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clear() {
|
||||
let mut interner = StringInterner::new();
|
||||
interner.intern("hello");
|
||||
interner.intern("world");
|
||||
|
||||
assert_eq!(interner.len(), 2);
|
||||
|
||||
interner.clear();
|
||||
|
||||
assert_eq!(interner.len(), 0);
|
||||
assert!(interner.is_empty());
|
||||
assert_eq!(interner.get_id("hello"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use crate::languages::types::TSLanguageConfig;
|
||||
|
||||
pub fn golang() -> TSLanguageConfig {
|
||||
TSLanguageConfig::new(
|
||||
vec!["Go".to_owned(), "go".to_owned()],
|
||||
vec!["go".to_owned()],
|
||||
vec![vec![
|
||||
"function".to_owned(),
|
||||
"type".to_owned(),
|
||||
"struct".to_owned(),
|
||||
"interface".to_owned(),
|
||||
"const".to_owned(),
|
||||
"var".to_owned(),
|
||||
"package".to_owned(),
|
||||
]],
|
||||
r#"
|
||||
; Function definitions
|
||||
(function_declaration
|
||||
name: (identifier) @name.definition.function) @definition.function
|
||||
|
||||
; Method definitions
|
||||
(method_declaration
|
||||
name: (field_identifier) @name.definition.method) @definition.method
|
||||
|
||||
; Type definitions (struct, interface, etc.)
|
||||
(type_declaration
|
||||
(type_spec
|
||||
name: (type_identifier) @name.definition.type)) @definition.type
|
||||
|
||||
; Const declarations
|
||||
(const_declaration
|
||||
(const_spec
|
||||
name: (identifier) @name.definition.const)) @definition.const
|
||||
|
||||
; Var declarations
|
||||
(var_declaration
|
||||
(var_spec
|
||||
name: (identifier) @name.definition.var)) @definition.var
|
||||
|
||||
; ============ REFERENCES ============
|
||||
|
||||
; Function calls
|
||||
(call_expression
|
||||
function: (identifier) @name.reference.call) @reference.call
|
||||
|
||||
; Method calls
|
||||
(call_expression
|
||||
function: (selector_expression
|
||||
field: (field_identifier) @name.reference.call)) @reference.call
|
||||
|
||||
; Type references
|
||||
(type_identifier) @name.reference.type
|
||||
|
||||
; Package references in qualified names
|
||||
(qualified_type
|
||||
package: (package_identifier) @name.reference.package
|
||||
name: (type_identifier) @name.reference.type)
|
||||
|
||||
; ============ IMPORTS ============
|
||||
|
||||
; import "package"
|
||||
(import_spec
|
||||
path: (interpreted_string_literal) @name.reference.import)
|
||||
|
||||
; import alias "package"
|
||||
(import_spec
|
||||
name: (package_identifier) @alias.name
|
||||
path: (interpreted_string_literal) @alias.original)
|
||||
"#
|
||||
.to_owned(),
|
||||
|| tree_sitter_go::LANGUAGE.into(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! JavaScript/JSX language configuration.
|
||||
|
||||
use crate::languages::types::TSLanguageConfig;
|
||||
|
||||
pub fn js_lang() -> TSLanguageConfig {
|
||||
TSLanguageConfig::new(
|
||||
vec![
|
||||
"JavaScript".to_owned(),
|
||||
"javascript".to_owned(),
|
||||
"js".to_owned(),
|
||||
"jsx".to_owned(),
|
||||
],
|
||||
vec!["js".to_owned(), "jsx".to_owned()],
|
||||
vec![vec![
|
||||
"function".to_owned(),
|
||||
"class".to_owned(),
|
||||
"variable".to_owned(),
|
||||
"const".to_owned(),
|
||||
"let".to_owned(),
|
||||
]],
|
||||
r#"
|
||||
; Class definitions
|
||||
(class_declaration
|
||||
name: (identifier) @name.definition.class) @definition.class
|
||||
|
||||
; Function definitions
|
||||
(function_declaration
|
||||
name: (identifier) @name.definition.function) @definition.function
|
||||
|
||||
; Arrow function with variable
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.function
|
||||
value: (arrow_function))) @definition.function
|
||||
|
||||
; Method definitions
|
||||
(method_definition
|
||||
name: (property_identifier) @name.definition.method) @definition.method
|
||||
|
||||
; Variable declarations
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.variable)) @definition.variable
|
||||
|
||||
; Var declarations
|
||||
(variable_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.variable)) @definition.variable
|
||||
|
||||
; ============ REFERENCES ============
|
||||
|
||||
; Function calls
|
||||
(call_expression
|
||||
function: (identifier) @name.reference.call) @reference.call
|
||||
|
||||
; Method calls
|
||||
(call_expression
|
||||
function: (member_expression
|
||||
property: (property_identifier) @name.reference.call)) @reference.call
|
||||
|
||||
; JSX element names
|
||||
(jsx_opening_element
|
||||
name: (identifier) @name.reference.jsx)
|
||||
|
||||
(jsx_self_closing_element
|
||||
name: (identifier) @name.reference.jsx)
|
||||
|
||||
; ============ IMPORTS ============
|
||||
|
||||
; Named imports: import { Foo } from 'bar'
|
||||
(import_specifier
|
||||
name: (identifier) @name.reference.import)
|
||||
|
||||
; Default import: import Foo from 'bar'
|
||||
(import_clause
|
||||
(identifier) @name.reference.import)
|
||||
|
||||
; Import alias: import { Foo as Bar } from 'bar'
|
||||
(import_specifier
|
||||
name: (identifier) @alias.original
|
||||
alias: (identifier) @alias.name)
|
||||
|
||||
; Named exports: export { Foo }
|
||||
(export_specifier
|
||||
name: (identifier) @name.reference.export)
|
||||
|
||||
; Array element identifiers: [foo, bar] (e.g., React useCallback/useEffect dependency arrays)
|
||||
(array
|
||||
(identifier) @name.reference.variable)
|
||||
"#
|
||||
.to_owned(),
|
||||
|| tree_sitter_javascript::LANGUAGE.into(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
mod golang;
|
||||
mod javascript;
|
||||
mod python;
|
||||
mod rust;
|
||||
mod ts;
|
||||
pub mod types;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use golang::golang;
|
||||
pub use javascript::js_lang;
|
||||
pub use python::python_lang;
|
||||
pub use rust::rust_lang;
|
||||
pub use ts::ts_lang;
|
||||
pub use types::TSLanguageConfig;
|
||||
|
||||
/// Registry of all supported languages.
|
||||
///
|
||||
/// Provides lookup by extension and language ID, and can check if two
|
||||
/// extensions belong to the same language family.
|
||||
pub struct LanguageRegistry {
|
||||
/// All registered language configs.
|
||||
configs: Vec<Arc<TSLanguageConfig>>,
|
||||
/// Mapping from file extension to language config.
|
||||
by_extension: HashMap<String, Arc<TSLanguageConfig>>,
|
||||
/// Mapping from language ID to language config.
|
||||
by_id: HashMap<String, Arc<TSLanguageConfig>>,
|
||||
}
|
||||
|
||||
impl LanguageRegistry {
|
||||
/// Create a new language registry with all supported languages.
|
||||
pub fn new() -> Self {
|
||||
let configs: Vec<Arc<TSLanguageConfig>> = vec![
|
||||
Arc::new(rust_lang()),
|
||||
Arc::new(ts_lang()),
|
||||
Arc::new(js_lang()),
|
||||
Arc::new(golang()),
|
||||
Arc::new(python_lang()),
|
||||
];
|
||||
|
||||
let mut by_extension = HashMap::new();
|
||||
let mut by_id = HashMap::new();
|
||||
|
||||
for config in &configs {
|
||||
for ext in config.file_extensions() {
|
||||
by_extension.insert(ext.clone(), Arc::clone(config));
|
||||
}
|
||||
for id in config.language_ids() {
|
||||
by_id.insert(id.clone(), Arc::clone(config));
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
configs,
|
||||
by_extension,
|
||||
by_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a language config by file extension.
|
||||
pub fn for_extension(&self, ext: &str) -> Option<Arc<TSLanguageConfig>> {
|
||||
self.by_extension.get(ext).cloned()
|
||||
}
|
||||
|
||||
/// Get a language config by language ID.
|
||||
pub fn for_id(&self, id: &str) -> Option<Arc<TSLanguageConfig>> {
|
||||
self.by_id.get(id).cloned()
|
||||
}
|
||||
|
||||
/// Get a language config for a file path.
|
||||
///
|
||||
/// Extracts the extension from the path and looks up the config.
|
||||
pub fn for_file_path(&self, path: impl AsRef<Path>) -> Option<Arc<TSLanguageConfig>> {
|
||||
let path = path.as_ref();
|
||||
let ext = path.extension()?.to_str()?;
|
||||
self.for_extension(ext)
|
||||
}
|
||||
|
||||
/// Check if a file path is supported (has a supported extension).
|
||||
pub fn is_supported(&self, path: impl AsRef<Path>) -> bool {
|
||||
self.for_file_path(path).is_some()
|
||||
}
|
||||
|
||||
/// Get all supported file extensions.
|
||||
pub fn supported_extensions(&self) -> Vec<&str> {
|
||||
self.by_extension.keys().map(|s| s.as_str()).collect()
|
||||
}
|
||||
|
||||
/// Get all language configs.
|
||||
pub fn all_configs(&self) -> &[Arc<TSLanguageConfig>] {
|
||||
&self.configs
|
||||
}
|
||||
|
||||
/// Check if two file extensions belong to the same language.
|
||||
///
|
||||
/// Returns true if both extensions are registered under the same language config.
|
||||
pub fn extensions_same_language(&self, ext1: &str, ext2: &str) -> bool {
|
||||
if ext1 == ext2 {
|
||||
return true;
|
||||
}
|
||||
|
||||
match (self.by_extension.get(ext1), self.by_extension.get(ext2)) {
|
||||
(Some(config1), Some(config2)) => {
|
||||
// Compare by primary language ID (they point to the same config)
|
||||
config1.primary_language_id() == config2.primary_language_id()
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute a hash of all tree-sitter queries across all languages.
|
||||
///
|
||||
/// This is used to detect when queries change, which should trigger
|
||||
/// a rebuild of the index even if file contents haven't changed.
|
||||
///
|
||||
/// The hash is computed by:
|
||||
/// 1. Sorting languages by their primary ID for deterministic ordering
|
||||
/// 2. Hashing each language's query string in order
|
||||
/// 3. Combining into a single u64 hash
|
||||
pub fn compute_query_hash(&self) -> u64 {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
|
||||
// Sort configs by primary language ID for deterministic ordering
|
||||
let mut sorted_configs: Vec<_> = self.configs.iter().collect();
|
||||
sorted_configs.sort_by_key(|c| c.primary_language_id());
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
|
||||
for config in sorted_configs {
|
||||
// Hash the language ID and query together
|
||||
config.primary_language_id().hash(&mut hasher);
|
||||
config.file_definition_queries().hash(&mut hasher);
|
||||
}
|
||||
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LanguageRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Python language configuration.
|
||||
|
||||
use crate::languages::types::TSLanguageConfig;
|
||||
|
||||
pub fn python_lang() -> TSLanguageConfig {
|
||||
TSLanguageConfig::new(
|
||||
vec!["Python".to_owned(), "python".to_owned(), "py".to_owned()],
|
||||
vec!["py".to_owned()],
|
||||
vec![vec![
|
||||
"function".to_owned(),
|
||||
"class".to_owned(),
|
||||
"variable".to_owned(),
|
||||
"module".to_owned(),
|
||||
]],
|
||||
// Python definitions query
|
||||
r#"
|
||||
; Class definitions
|
||||
(class_definition
|
||||
name: (identifier) @name.definition.class) @definition.class
|
||||
|
||||
; Function definitions
|
||||
(function_definition
|
||||
name: (identifier) @name.definition.function) @definition.function
|
||||
|
||||
; ============ REFERENCES ============
|
||||
|
||||
; Function calls (direct and method calls)
|
||||
(call
|
||||
function: [
|
||||
(identifier) @name.reference.call
|
||||
(attribute
|
||||
attribute: (identifier) @name.reference.call)
|
||||
]) @reference.call
|
||||
"#
|
||||
.to_owned(),
|
||||
|| tree_sitter_python::LANGUAGE.into(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use crate::languages::types::TSLanguageConfig;
|
||||
|
||||
pub fn rust_lang() -> TSLanguageConfig {
|
||||
TSLanguageConfig::new(
|
||||
vec!["Rust".to_owned(), "rust".to_owned(), "rs".to_owned()],
|
||||
vec!["rs".to_owned()],
|
||||
vec![vec![
|
||||
"const".to_owned(),
|
||||
"function".to_owned(),
|
||||
"variable".to_owned(),
|
||||
"struct".to_owned(),
|
||||
"enum".to_owned(),
|
||||
"union".to_owned(),
|
||||
"typedef".to_owned(),
|
||||
"interface".to_owned(),
|
||||
"field".to_owned(),
|
||||
"enumerator".to_owned(),
|
||||
"module".to_owned(),
|
||||
"label".to_owned(),
|
||||
"lifetime".to_owned(),
|
||||
]],
|
||||
r#"; ADT definitions
|
||||
|
||||
(struct_item
|
||||
name: (type_identifier) @name.definition.class) @definition.class
|
||||
|
||||
(enum_item
|
||||
name: (type_identifier) @name.definition.class) @definition.class
|
||||
|
||||
(union_item
|
||||
name: (type_identifier) @name.definition.class) @definition.class
|
||||
|
||||
; type aliases
|
||||
|
||||
(type_item
|
||||
name: (type_identifier) @name.definition.class) @definition.class
|
||||
|
||||
; method definitions
|
||||
|
||||
(declaration_list
|
||||
(function_item
|
||||
name: (identifier) @name.definition.method)) @definition.method
|
||||
|
||||
; function definitions
|
||||
|
||||
(function_item
|
||||
name: (identifier) @name.definition.function) @definition.function
|
||||
|
||||
; trait definitions
|
||||
(trait_item
|
||||
name: (type_identifier) @name.definition.interface) @definition.interface
|
||||
|
||||
; module definitions
|
||||
(mod_item
|
||||
name: (identifier) @name.definition.module) @definition.module
|
||||
|
||||
; macro definitions
|
||||
|
||||
(macro_definition
|
||||
name: (identifier) @name.definition.macro) @definition.macro
|
||||
|
||||
; const and static definitions
|
||||
(const_item
|
||||
name: (identifier) @name.definition.variable) @definition.variable
|
||||
|
||||
(static_item
|
||||
name: (identifier) @name.definition.variable) @definition.variable
|
||||
|
||||
; ============ REFERENCES ============
|
||||
|
||||
; Function and method calls
|
||||
(call_expression
|
||||
function: (identifier) @name.reference.call) @reference.call
|
||||
|
||||
(call_expression
|
||||
function: (field_expression
|
||||
field: (field_identifier) @name.reference.call)) @reference.call
|
||||
|
||||
(macro_invocation
|
||||
macro: (identifier) @name.reference.call) @reference.call
|
||||
|
||||
; implementations
|
||||
|
||||
(impl_item
|
||||
trait: (type_identifier) @name.reference.implementation) @reference.implementation
|
||||
|
||||
(impl_item
|
||||
type: (type_identifier) @name.reference.implementation
|
||||
!trait) @reference.implementation
|
||||
|
||||
; ============ USE/IMPORT REFERENCES ============
|
||||
|
||||
; Simple use: use Foo;
|
||||
(use_declaration
|
||||
argument: (identifier) @name.reference.import) @reference.import
|
||||
|
||||
; Scoped use: use foo::Bar;
|
||||
(use_declaration
|
||||
argument: (scoped_identifier
|
||||
name: (identifier) @name.reference.import)) @reference.import
|
||||
|
||||
; Use list: use foo::{Bar, Baz};
|
||||
(use_declaration
|
||||
argument: (scoped_use_list
|
||||
list: (use_list
|
||||
(identifier) @name.reference.import)))
|
||||
|
||||
; Nested scoped use: use foo::bar::{Baz, Qux};
|
||||
(use_declaration
|
||||
argument: (scoped_use_list
|
||||
list: (use_list
|
||||
(scoped_identifier
|
||||
name: (identifier) @name.reference.import))))
|
||||
|
||||
; Use with alias: use Foo as Bar;
|
||||
(use_declaration
|
||||
argument: (use_as_clause
|
||||
path: (identifier) @name.reference.import))
|
||||
|
||||
(use_declaration
|
||||
argument: (use_as_clause
|
||||
path: (scoped_identifier
|
||||
name: (identifier) @name.reference.import)))
|
||||
|
||||
; ============ ALIAS TRACKING ============
|
||||
; These patterns capture alias relationships for unified lookups
|
||||
|
||||
; use Foo as Bar - captures original and alias
|
||||
(use_declaration
|
||||
argument: (use_as_clause
|
||||
path: (identifier) @alias.original
|
||||
alias: (identifier) @alias.name))
|
||||
|
||||
; use foo::Bar as Baz - scoped version
|
||||
(use_declaration
|
||||
argument: (use_as_clause
|
||||
path: (scoped_identifier
|
||||
name: (identifier) @alias.original)
|
||||
alias: (identifier) @alias.name))
|
||||
|
||||
; ============ TYPE REFERENCES ============
|
||||
|
||||
; Type identifiers in function parameters
|
||||
(parameter
|
||||
type: (type_identifier) @name.reference.type)
|
||||
|
||||
; Return types
|
||||
(function_item
|
||||
return_type: (type_identifier) @name.reference.type)
|
||||
|
||||
; Struct fields
|
||||
(field_declaration
|
||||
type: (type_identifier) @name.reference.type)
|
||||
|
||||
; Let bindings with type annotation
|
||||
(let_declaration
|
||||
type: (type_identifier) @name.reference.type)
|
||||
|
||||
; Generic type arguments: Vec<Foo>
|
||||
(type_arguments
|
||||
(type_identifier) @name.reference.type)
|
||||
|
||||
; Scoped type identifier: foo::Bar
|
||||
(scoped_type_identifier
|
||||
name: (type_identifier) @name.reference.type)
|
||||
|
||||
; Reference types: &Foo
|
||||
(reference_type
|
||||
type: (type_identifier) @name.reference.type)
|
||||
|
||||
; Tuple struct patterns
|
||||
(tuple_struct_pattern
|
||||
type: (identifier) @name.reference.type)
|
||||
|
||||
; Struct expressions: Foo { ... }
|
||||
(struct_expression
|
||||
name: (type_identifier) @name.reference.type)
|
||||
|
||||
; Tuple struct expressions: Foo(...)
|
||||
(call_expression
|
||||
function: (scoped_identifier
|
||||
name: (identifier) @name.reference.call))
|
||||
|
||||
; Path segments in scoped identifiers: foo::Bar::baz()
|
||||
; This captures types used in paths like SomeType::method()
|
||||
(scoped_identifier
|
||||
path: (scoped_identifier
|
||||
name: (identifier) @name.reference.type))
|
||||
|
||||
; Direct scoped calls with type in path: Foo::bar()
|
||||
(scoped_identifier
|
||||
path: (identifier) @name.reference.type
|
||||
name: (identifier))
|
||||
"#
|
||||
.to_owned(),
|
||||
|| tree_sitter_rust::LANGUAGE.into(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
use crate::languages::types::TSLanguageConfig;
|
||||
|
||||
pub fn ts_lang() -> TSLanguageConfig {
|
||||
TSLanguageConfig::new(
|
||||
vec![
|
||||
"Typescript".to_owned(),
|
||||
"TSX".to_owned(),
|
||||
"typescript".to_owned(),
|
||||
"tsx".to_owned(),
|
||||
],
|
||||
vec!["ts".to_owned(), "tsx".to_owned()],
|
||||
vec![vec![
|
||||
"function".to_owned(),
|
||||
"class".to_owned(),
|
||||
"interface".to_owned(),
|
||||
"type".to_owned(),
|
||||
"enum".to_owned(),
|
||||
"variable".to_owned(),
|
||||
"const".to_owned(),
|
||||
"let".to_owned(),
|
||||
]],
|
||||
// Comprehensive TypeScript query with full type coverage
|
||||
r#"
|
||||
;; === DEFINITIONS ===
|
||||
|
||||
(function_signature
|
||||
name: (identifier) @name.definition.function) @definition.function
|
||||
|
||||
(method_signature
|
||||
name: (property_identifier) @name.definition.method) @definition.method
|
||||
|
||||
(abstract_method_signature
|
||||
name: (property_identifier) @name.definition.method) @definition.method
|
||||
|
||||
(abstract_class_declaration
|
||||
name: (type_identifier) @name.definition.class) @definition.class
|
||||
|
||||
(module
|
||||
name: (identifier) @name.definition.module) @definition.module
|
||||
|
||||
(interface_declaration
|
||||
name: (type_identifier) @name.definition.interface) @definition.interface
|
||||
|
||||
(function_declaration
|
||||
name: (identifier) @name.definition.function) @definition.function
|
||||
|
||||
(method_definition
|
||||
name: (property_identifier) @name.definition.method) @definition.method
|
||||
|
||||
(class_declaration
|
||||
name: (type_identifier) @name.definition.class) @definition.class
|
||||
|
||||
(type_alias_declaration
|
||||
name: (type_identifier) @name.definition.type) @definition.type
|
||||
|
||||
(enum_declaration
|
||||
name: (identifier) @name.definition.enum) @definition.enum
|
||||
|
||||
;; Arrow function assigned to variable: const foo = () => {}
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.function
|
||||
value: (arrow_function))) @definition.function
|
||||
|
||||
;; React component patterns: const Foo = React.forwardRef(...), React.memo(...)
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.function
|
||||
value: (call_expression))) @definition.function
|
||||
|
||||
;; Variable declarations (const/let)
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.variable)) @definition.variable
|
||||
|
||||
;; Var declarations
|
||||
(variable_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.variable)) @definition.variable
|
||||
|
||||
;; Exported variable declarations: export const foo = ...
|
||||
(export_statement
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @name.definition.variable))) @definition.variable
|
||||
|
||||
;; === DESTRUCTURING DEFINITIONS ===
|
||||
|
||||
;; For-of/for-in loop with array destructuring: for (const [a, b] of items)
|
||||
(for_in_statement
|
||||
left: (array_pattern
|
||||
(identifier) @name.definition.variable))
|
||||
|
||||
;; For-of/for-in loop with object destructuring: for (const { a, b } of items)
|
||||
(for_in_statement
|
||||
left: (object_pattern
|
||||
(shorthand_property_identifier_pattern) @name.definition.variable))
|
||||
|
||||
;; For-of/for-in loop with object destructuring (aliased): for (const { a: b } of items)
|
||||
(for_in_statement
|
||||
left: (object_pattern
|
||||
(pair_pattern
|
||||
value: (identifier) @name.definition.variable)))
|
||||
|
||||
;; Regular array destructuring: const [a, b] = someArray
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (array_pattern
|
||||
(identifier) @name.definition.variable)))
|
||||
|
||||
;; Regular object destructuring (shorthand): const { a, b } = someObject
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (object_pattern
|
||||
(shorthand_property_identifier_pattern) @name.definition.variable)))
|
||||
|
||||
;; Regular object destructuring (aliased): const { a: b } = someObject
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (object_pattern
|
||||
(pair_pattern
|
||||
value: (identifier) @name.definition.variable))))
|
||||
|
||||
;; Var array destructuring: var [a, b] = someArray
|
||||
(variable_declaration
|
||||
(variable_declarator
|
||||
name: (array_pattern
|
||||
(identifier) @name.definition.variable)))
|
||||
|
||||
;; Var object destructuring (shorthand): var { a, b } = someObject
|
||||
(variable_declaration
|
||||
(variable_declarator
|
||||
name: (object_pattern
|
||||
(shorthand_property_identifier_pattern) @name.definition.variable)))
|
||||
|
||||
;; Var object destructuring (aliased): var { a: b } = someObject
|
||||
(variable_declaration
|
||||
(variable_declarator
|
||||
name: (object_pattern
|
||||
(pair_pattern
|
||||
value: (identifier) @name.definition.variable))))
|
||||
|
||||
;; Function parameters with array destructuring: function foo([a, b]) {}
|
||||
(formal_parameters
|
||||
(required_parameter
|
||||
pattern: (array_pattern
|
||||
(identifier) @name.definition.variable)))
|
||||
|
||||
;; Function parameters with object destructuring (shorthand): function foo({ a, b }) {}
|
||||
(formal_parameters
|
||||
(required_parameter
|
||||
pattern: (object_pattern
|
||||
(shorthand_property_identifier_pattern) @name.definition.variable)))
|
||||
|
||||
;; Function parameters with object destructuring (aliased): function foo({ a: b }) {}
|
||||
(formal_parameters
|
||||
(required_parameter
|
||||
pattern: (object_pattern
|
||||
(pair_pattern
|
||||
value: (identifier) @name.definition.variable))))
|
||||
|
||||
;; Function parameters (simple): function foo(a, b) {}
|
||||
(formal_parameters
|
||||
(required_parameter
|
||||
pattern: (identifier) @name.definition.variable))
|
||||
|
||||
;; === REFERENCES ===
|
||||
|
||||
;; Member expression object: foo.bar (capture foo as reference)
|
||||
(member_expression
|
||||
object: (identifier) @name.reference.variable)
|
||||
|
||||
;; Capture ALL type identifiers as references (comprehensive)
|
||||
(type_identifier) @name.reference.type
|
||||
|
||||
;; new expressions: new SomeClass()
|
||||
(new_expression
|
||||
constructor: (identifier) @name.reference.class) @reference.class
|
||||
|
||||
;; Named imports (simple): import { DiffViewer } from './code-viewer'
|
||||
(import_specifier
|
||||
name: (identifier) @name.reference.variable
|
||||
!alias) @reference.import
|
||||
|
||||
;; Named imports with alias: import { Foo as Bar } from './module'
|
||||
(import_specifier
|
||||
name: (identifier) @alias.original
|
||||
alias: (identifier) @alias.name) @reference.import.alias
|
||||
|
||||
;; Default imports: import Foo from 'bar'
|
||||
(import_clause
|
||||
(identifier) @name.reference.import)
|
||||
|
||||
;; JSX opening element: <DiffViewer ...>
|
||||
(jsx_opening_element
|
||||
name: (identifier) @name.reference.class)
|
||||
|
||||
;; JSX self-closing element: <DiffViewer ... />
|
||||
(jsx_self_closing_element
|
||||
name: (identifier) @name.reference.class)
|
||||
|
||||
;; JSX member expression element: <Foo.Bar />
|
||||
(jsx_opening_element
|
||||
name: (member_expression
|
||||
object: (identifier) @name.reference.variable))
|
||||
|
||||
(jsx_self_closing_element
|
||||
name: (member_expression
|
||||
object: (identifier) @name.reference.variable))
|
||||
|
||||
;; Function calls: someFunction()
|
||||
(call_expression
|
||||
function: (identifier) @name.reference.call)
|
||||
|
||||
;; Method calls on objects: object.method()
|
||||
(call_expression
|
||||
function: (member_expression
|
||||
object: (identifier) @name.reference.variable))
|
||||
|
||||
;; Extends clause in class: class Foo extends Bar
|
||||
(class_heritage
|
||||
(extends_clause
|
||||
value: (identifier) @name.reference.class))
|
||||
|
||||
;; Implements clause: class Foo implements Bar
|
||||
(class_heritage
|
||||
(implements_clause
|
||||
(type_identifier) @name.reference.interface))
|
||||
|
||||
;; Named exports: export { Foo }
|
||||
(export_specifier
|
||||
name: (identifier) @name.reference.export)
|
||||
|
||||
;; Array element identifiers: [foo, bar] (e.g., React useCallback/useEffect dependency arrays)
|
||||
(array
|
||||
(identifier) @name.reference.variable)
|
||||
"#
|
||||
.to_owned(),
|
||||
|| tree_sitter_typescript::LANGUAGE_TSX.into(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use crate::scope_graph::nodes::SymbolId;
|
||||
|
||||
/// Function type for getting a tree-sitter language grammar.
|
||||
pub type GrammarFn = fn() -> tree_sitter::Language;
|
||||
|
||||
/// Contains information about the language and extra information which we would need
|
||||
/// per language
|
||||
pub struct TSLanguageConfig {
|
||||
language_ids: Vec<String>,
|
||||
file_extensions: Vec<String>,
|
||||
namespaces: Vec<Vec<String>>,
|
||||
file_definition_queries: String,
|
||||
grammar: GrammarFn,
|
||||
}
|
||||
|
||||
impl TSLanguageConfig {
|
||||
pub fn new(
|
||||
language_ids: Vec<String>,
|
||||
file_extensions: Vec<String>,
|
||||
namespaces: Vec<Vec<String>>,
|
||||
file_definition_queries: String,
|
||||
grammar: GrammarFn,
|
||||
) -> Self {
|
||||
Self {
|
||||
language_ids,
|
||||
file_extensions,
|
||||
namespaces,
|
||||
file_definition_queries,
|
||||
grammar,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the language IDs.
|
||||
pub fn language_ids(&self) -> &[String] {
|
||||
&self.language_ids
|
||||
}
|
||||
|
||||
/// Get the first language ID, or "unknown" if none.
|
||||
pub fn primary_language_id(&self) -> &str {
|
||||
self.language_ids
|
||||
.first()
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("unknown")
|
||||
}
|
||||
|
||||
/// Get the file extensions.
|
||||
pub fn file_extensions(&self) -> &[String] {
|
||||
&self.file_extensions
|
||||
}
|
||||
|
||||
/// Get the namespaces.
|
||||
pub fn namespaces(&self) -> &[Vec<String>] {
|
||||
&self.namespaces
|
||||
}
|
||||
|
||||
/// Get the file definition queries.
|
||||
pub fn file_definition_queries(&self) -> &str {
|
||||
&self.file_definition_queries
|
||||
}
|
||||
|
||||
/// Get the tree-sitter language.
|
||||
pub fn language(&self) -> tree_sitter::Language {
|
||||
(self.grammar)()
|
||||
}
|
||||
|
||||
/// Compile the definitions query for this language.
|
||||
pub fn compile_query(&self) -> Result<tree_sitter::Query, tree_sitter::QueryError> {
|
||||
tree_sitter::Query::new(&self.language(), &self.file_definition_queries)
|
||||
}
|
||||
|
||||
/// Find a SymbolId for a given symbol type name.
|
||||
pub fn symbol_id_of(&self, symbol_type: &str) -> Option<SymbolId> {
|
||||
for (ns_idx, namespace) in self.namespaces.iter().enumerate() {
|
||||
for (sym_idx, sym) in namespace.iter().enumerate() {
|
||||
if sym == symbol_type {
|
||||
return Some(SymbolId::new(ns_idx, sym_idx));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! # xai-codebase-graph
|
||||
//!
|
||||
//! High-performance code graph generation using tree-sitter queries.
|
||||
//!
|
||||
//! This crate provides:
|
||||
//! - **Go-to-definitions**: Find where symbols are defined
|
||||
//! - **Go-to-references**: Find where symbols are used
|
||||
//! - **Initial repository indexing**: Build the full index from scratch
|
||||
//! - **Incremental reindexing**: Update the index based on file system events
|
||||
//! - **Parallel processing**: Uses rayon for fast parallel parsing
|
||||
//! - **Memory-mapped I/O**: Zero-copy file reading and fast index caching
|
||||
//!
|
||||
//! ## Quick Start
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! use std::path::Path;
|
||||
//! use xai_codebase_graph::{IndexBuilder, load_index, save_index, get_cache_path, Navigator};
|
||||
//!
|
||||
//! let repo_path = Path::new("/path/to/repo");
|
||||
//! let cache_path = get_cache_path(repo_path);
|
||||
//!
|
||||
//! // Try loading from cache first, otherwise build fresh
|
||||
//! let index = match load_index(&cache_path) {
|
||||
//! Ok(index) => index,
|
||||
//! Err(_) => {
|
||||
//! let index = IndexBuilder::new()
|
||||
//! .with_threads(8)
|
||||
//! .build(repo_path)?;
|
||||
//! save_index(&cache_path, &index)?;
|
||||
//! index
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! // Create a navigator for location-based operations
|
||||
//! let navigator = Navigator::new(index);
|
||||
//!
|
||||
//! // Go to definition at a specific position (row and col are 1-indexed)
|
||||
//! let result = navigator.goto_definition(Path::new("src/main.rs"), 10, 15)?;
|
||||
//! for loc in result.locations {
|
||||
//! println!("{}:{}", loc.path.display(), loc.line);
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Channel-Based Incremental Updates
|
||||
//!
|
||||
//! `IndexManagerHandle` exposes direct query commands that answer in-place
|
||||
//! without cloning the full index. Prefer these over `get_snapshot()` in
|
||||
//! hot paths.
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! use std::path::PathBuf;
|
||||
//! use xai_codebase_graph::{IndexManager, IndexManagerConfig, FileEvent};
|
||||
//!
|
||||
//! // Create the manager with config
|
||||
//! let config = IndexManagerConfig::new("/path/to/repo".into())
|
||||
//! .with_cache_path("/tmp/index.bin".into());
|
||||
//!
|
||||
//! let handle = IndexManager::spawn(config);
|
||||
//!
|
||||
//! // Send file events as they come from FSNotify
|
||||
//! handle.send_event(FileEvent::modified("src/main.rs".into()))?;
|
||||
//!
|
||||
//! // Query directly — no full-index clone needed
|
||||
//! let file = PathBuf::from("src/main.rs");
|
||||
//! let result = handle.goto_definition_blocking(file, 10, 15)??;
|
||||
//! for loc in result.locations {
|
||||
//! println!("{}:{}", loc.path, loc.line);
|
||||
//! }
|
||||
//!
|
||||
//! // Lightweight stats — also no clone
|
||||
//! let file_count = handle.get_file_count();
|
||||
//! let exists = handle.has_definition_blocking("MyStruct");
|
||||
//! ```
|
||||
|
||||
pub mod index_manager;
|
||||
pub mod interner;
|
||||
pub mod languages;
|
||||
pub mod manager;
|
||||
pub mod navigation;
|
||||
pub mod scope_graph;
|
||||
pub mod types;
|
||||
|
||||
// Re-exports for convenient access
|
||||
pub use index_manager::{
|
||||
FileEvent, FileEventKind, IndexCommand, IndexManager, IndexManagerConfig, IndexManagerHandle,
|
||||
MAX_INDEXABLE_FILE_SIZE, QueryError, QueryResult, SymbolLocation, is_binary_content,
|
||||
};
|
||||
pub use languages::{LanguageRegistry, TSLanguageConfig};
|
||||
pub use manager::{
|
||||
CACHE_FILE_NAME, CacheError, IndexBuilder, IndexError, IndexOperation, LockResult,
|
||||
WorkspaceLockGuard, cache_exists, cache_size, get_cache_path, is_operation_in_progress,
|
||||
load_index, save_index, save_index_async, try_lock,
|
||||
};
|
||||
pub use navigation::{Location, NavigationError, NavigationResult, Navigator};
|
||||
pub use scope_graph::{
|
||||
LocalDef, LocalImport, LocalScope, NodeKind, QueryVersion, Reference, ScopeGraph,
|
||||
ScopeGraphIndex, ScopeGraphResult, Symbol, SymbolId, build_scope_graph, extract_symbols_fast,
|
||||
};
|
||||
pub use types::{FileMeta, IndexStats, Position, Range, SymbolAlias, SymbolOccurrence};
|
||||
|
||||
// String interning for memory-efficient storage
|
||||
pub use interner::{StringId, StringInterner};
|
||||
@@ -0,0 +1,507 @@
|
||||
//! Parallel pipelined index builder with thread-local caching.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use ahash::AHashMap as HashMap;
|
||||
use ignore::WalkBuilder;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::languages::LanguageRegistry;
|
||||
use crate::scope_graph::ScopeGraphIndex;
|
||||
use crate::types::{FileMeta, SymbolAlias, SymbolOccurrence};
|
||||
use xai_grok_paths::to_relative_path;
|
||||
|
||||
/// Error type for index building operations.
|
||||
#[derive(Debug)]
|
||||
pub enum IndexError {
|
||||
/// Error walking directory.
|
||||
WalkError { message: String },
|
||||
/// Thread panicked.
|
||||
ThreadPanic { message: String },
|
||||
/// IO error.
|
||||
IoError(std::io::Error),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IndexError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
IndexError::WalkError { message } => write!(f, "Walk error: {}", message),
|
||||
IndexError::ThreadPanic { message } => write!(f, "Thread panic: {}", message),
|
||||
IndexError::IoError(e) => write!(f, "IO error: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IndexError {}
|
||||
|
||||
impl From<std::io::Error> for IndexError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
IndexError::IoError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result type for index building operations.
|
||||
pub type Result<T> = std::result::Result<T, IndexError>;
|
||||
|
||||
// Thread-local caches for parsers and queries to avoid repeated initialization
|
||||
thread_local! {
|
||||
static PARSER_CACHE: RefCell<HashMap<String, tree_sitter::Parser>> = RefCell::new(HashMap::new());
|
||||
static QUERY_CACHE: RefCell<HashMap<String, tree_sitter::Query>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// Extracted symbols for a single file (lightweight, no ScopeGraph overhead)
|
||||
struct FileSymbols {
|
||||
path: Arc<str>,
|
||||
definitions: Vec<SymbolOccurrence>,
|
||||
references: Vec<SymbolOccurrence>,
|
||||
aliases: Vec<SymbolAlias>,
|
||||
file_meta: FileMeta,
|
||||
}
|
||||
|
||||
/// Builder for creating a symbol index.
|
||||
///
|
||||
/// Uses optimized parallel processing with:
|
||||
/// - Thread-local parser and query caching
|
||||
/// - Chunked parallel processing for cache locality
|
||||
/// - Lightweight symbol extraction (no intermediate ScopeGraph)
|
||||
/// - Bounded merge-batching to cap two-phase peak memory
|
||||
pub struct IndexBuilder {
|
||||
registry: LanguageRegistry,
|
||||
num_threads: usize,
|
||||
/// Whether to respect .gitignore files (default: true)
|
||||
respect_gitignore: bool,
|
||||
/// Whether to skip hidden files/directories (default: true)
|
||||
skip_hidden: bool,
|
||||
/// Chunk size for parallel processing / thread-local cache locality (default: 100)
|
||||
chunk_size: usize,
|
||||
/// Maximum number of files whose symbols are held in memory at once during
|
||||
/// the merge phase. Limiting this bounds the two-phase peak: parallel
|
||||
/// parsing produces at most `build_batch_size` FileSymbols before they are
|
||||
/// merged into the index and dropped. Default: 5 000 files per batch.
|
||||
build_batch_size: usize,
|
||||
}
|
||||
|
||||
/// Get the default number of threads (N-1 cores, minimum 1).
|
||||
fn default_num_threads() -> usize {
|
||||
num_cpus::get().saturating_sub(1).max(1)
|
||||
}
|
||||
|
||||
impl IndexBuilder {
|
||||
/// Create a new index builder.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
registry: LanguageRegistry::new(),
|
||||
num_threads: default_num_threads(),
|
||||
respect_gitignore: true,
|
||||
skip_hidden: true,
|
||||
chunk_size: 100,
|
||||
build_batch_size: 5_000,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new index builder with a custom language registry.
|
||||
pub fn with_registry(registry: LanguageRegistry) -> Self {
|
||||
Self {
|
||||
registry,
|
||||
num_threads: default_num_threads(),
|
||||
respect_gitignore: true,
|
||||
skip_hidden: true,
|
||||
chunk_size: 100,
|
||||
build_batch_size: 5_000,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the number of threads to use (default: N-1 cores).
|
||||
#[must_use]
|
||||
pub fn with_threads(mut self, count: usize) -> Self {
|
||||
self.num_threads = count;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the chunk size for parallel processing (default: 100).
|
||||
#[must_use]
|
||||
pub fn with_chunk_size(mut self, size: usize) -> Self {
|
||||
self.chunk_size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the merge-batch size (default: 5 000 files per batch).
|
||||
///
|
||||
/// Controls how many files' symbols are held in memory simultaneously
|
||||
/// during the sequential merge phase. Smaller values reduce peak RSS at
|
||||
/// the cost of slightly more pool scheduling overhead. Values below
|
||||
/// `chunk_size` are clamped to `chunk_size` at build time, so the call
|
||||
/// order of `with_build_batch_size` and `with_chunk_size` does not matter.
|
||||
#[must_use]
|
||||
pub fn with_build_batch_size(mut self, size: usize) -> Self {
|
||||
self.build_batch_size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set whether to respect .gitignore files (default: true).
|
||||
#[must_use]
|
||||
pub fn respect_gitignore(mut self, respect: bool) -> Self {
|
||||
self.respect_gitignore = respect;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set whether to skip hidden files/directories (default: true).
|
||||
#[must_use]
|
||||
pub fn skip_hidden(mut self, skip: bool) -> Self {
|
||||
self.skip_hidden = skip;
|
||||
self
|
||||
}
|
||||
|
||||
/// Build index from a directory, respecting .gitignore.
|
||||
///
|
||||
/// This walks the directory tree, automatically respecting:
|
||||
/// - `.gitignore` files at any level
|
||||
/// - `.git/info/exclude`
|
||||
/// - Global gitignore (`~/.config/git/ignore`)
|
||||
/// - Hidden files/directories (configurable)
|
||||
///
|
||||
/// **Note**: File paths in the index are stored as **relative paths** (to `root_path`)
|
||||
/// for portability across machines/sessions.
|
||||
pub fn build(&self, root_path: &Path) -> Result<ScopeGraphIndex> {
|
||||
// Collect files using the ignore crate
|
||||
let file_paths = self.collect_files(root_path)?;
|
||||
|
||||
if file_paths.is_empty() {
|
||||
let mut index = ScopeGraphIndex::new();
|
||||
// Set query version even for empty index so cache validation works
|
||||
index.set_query_version(self.registry.compute_query_hash());
|
||||
return Ok(index);
|
||||
}
|
||||
|
||||
self.build_fast(root_path, &file_paths)
|
||||
}
|
||||
|
||||
/// Collect all supported files from a directory, respecting gitignore.
|
||||
/// Uses `git ls-files` when available (faster), falls back to directory walking.
|
||||
fn collect_files(&self, root_path: &Path) -> Result<Vec<PathBuf>> {
|
||||
// Try git ls-files first - it's much faster as it reads from git's index
|
||||
// But it only works for tracked files, so we also add untracked files
|
||||
if let Some(files) = self.collect_files_git(root_path)
|
||||
&& !files.is_empty()
|
||||
{
|
||||
return Ok(files);
|
||||
}
|
||||
|
||||
// Fall back to directory walking
|
||||
self.collect_files_walk(root_path)
|
||||
}
|
||||
|
||||
/// Collect files using git2 - reads from the git index (tracked files).
|
||||
/// Untracked files are not included since:
|
||||
/// 1. They are typically a small minority
|
||||
/// 2. They will be picked up by fsnotify when created
|
||||
/// 3. The statuses() call for untracked files is very slow (~10x overhead)
|
||||
fn collect_files_git(&self, root_path: &Path) -> Option<Vec<PathBuf>> {
|
||||
use git2::Repository;
|
||||
|
||||
// Open the repository
|
||||
let repo = Repository::open(root_path).ok()?;
|
||||
|
||||
// Get all files from the index (tracked files)
|
||||
let index = repo.index().ok()?;
|
||||
let files: Vec<PathBuf> = index
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
// git2 stores paths as bytes, convert to str
|
||||
let path_str = std::str::from_utf8(&entry.path).ok()?;
|
||||
if self.registry.is_supported(path_str) {
|
||||
Some(root_path.join(path_str))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(files)
|
||||
}
|
||||
|
||||
/// Collect files by walking the directory tree.
|
||||
/// Used as fallback when not in a git repository.
|
||||
fn collect_files_walk(&self, root_path: &Path) -> Result<Vec<PathBuf>> {
|
||||
use std::sync::Mutex;
|
||||
|
||||
let files = Mutex::new(Vec::with_capacity(50000));
|
||||
|
||||
let walker = WalkBuilder::new(root_path)
|
||||
.hidden(self.skip_hidden)
|
||||
.git_ignore(self.respect_gitignore)
|
||||
.git_global(self.respect_gitignore)
|
||||
.git_exclude(self.respect_gitignore)
|
||||
.threads(self.num_threads.min(12)) // Use parallel walking (capped at 12)
|
||||
.build_parallel();
|
||||
|
||||
walker.run(|| {
|
||||
let files = &files;
|
||||
let registry = &self.registry;
|
||||
Box::new(move |entry| {
|
||||
use ignore::WalkState;
|
||||
|
||||
let entry = match entry {
|
||||
Ok(e) => e,
|
||||
Err(_) => return WalkState::Continue,
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
|
||||
// Skip directories
|
||||
if path.is_dir() {
|
||||
return WalkState::Continue;
|
||||
}
|
||||
|
||||
// Check if the file is supported
|
||||
if registry.is_supported(path) {
|
||||
files.lock().unwrap().push(path.to_path_buf());
|
||||
}
|
||||
|
||||
WalkState::Continue
|
||||
})
|
||||
});
|
||||
|
||||
Ok(files.into_inner().unwrap())
|
||||
}
|
||||
|
||||
/// Build index with maximum throughput optimizations:
|
||||
/// - Memory-mapped I/O for zero-copy file reading
|
||||
/// - Direct parsing from mmap (no intermediate buffer copy)
|
||||
/// - Lightweight symbol extraction (skip building full ScopeGraph)
|
||||
/// - Thread-local parser and query caching
|
||||
/// - Chunked parallel processing for better cache locality
|
||||
/// - Single StringInterner for memory-efficient string deduplication
|
||||
///
|
||||
/// Uses two-phase approach:
|
||||
/// 1. Parallel: parse files and extract symbols into Vec<FileSymbols>
|
||||
/// 2. Sequential: aggregate into single ScopeGraphIndex with single interner
|
||||
///
|
||||
/// This ensures all strings are deduplicated in one interner, avoiding
|
||||
/// the memory overhead of multiple interners during parallel aggregation.
|
||||
///
|
||||
/// File paths are stored as **relative paths** (to `root_path`) for portability.
|
||||
fn build_fast(&self, root_path: &Path, file_paths: &[PathBuf]) -> Result<ScopeGraphIndex> {
|
||||
// Configure thread pool with N-1 cores
|
||||
let pool = rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(self.num_threads)
|
||||
.build()
|
||||
.map_err(|e| IndexError::WalkError {
|
||||
message: format!("Failed to create thread pool: {}", e),
|
||||
})?;
|
||||
|
||||
let registry = Arc::new(LanguageRegistry::new());
|
||||
let chunk_size = self.chunk_size;
|
||||
// Clamp here against the final chunk_size so that call order of
|
||||
// with_build_batch_size / with_chunk_size on the builder does not matter.
|
||||
let build_batch_size = self.build_batch_size.max(chunk_size);
|
||||
let root_arc: Arc<Path> = Arc::from(root_path);
|
||||
|
||||
let mut index = ScopeGraphIndex::new();
|
||||
|
||||
// Process files in bounded merge-batches to cap two-phase peak memory.
|
||||
//
|
||||
// Old approach: collect ALL FileSymbols in one go, then merge.
|
||||
// Peak = O(total_files) symbols + growing index simultaneously.
|
||||
//
|
||||
// New approach: for each batch of build_batch_size files:
|
||||
// 1. Parse in parallel (par_chunks preserves thread-local cache locality)
|
||||
// 2. Merge the batch into the index
|
||||
// 3. Drop the batch before starting the next one
|
||||
// Peak = O(build_batch_size) symbols + growing index simultaneously.
|
||||
for batch in file_paths.chunks(build_batch_size) {
|
||||
let batch_symbols: Vec<FileSymbols> = pool.install(|| {
|
||||
batch
|
||||
.par_chunks(chunk_size)
|
||||
.flat_map_iter(|chunk| {
|
||||
chunk
|
||||
.iter()
|
||||
.filter_map(|path| process_file_fast(path, &root_arc, ®istry))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
|
||||
for file_syms in batch_symbols {
|
||||
let path_str: &str = &file_syms.path;
|
||||
for sym in file_syms.definitions {
|
||||
index.add_definition(&sym.name, path_str, sym.line);
|
||||
}
|
||||
for sym in file_syms.references {
|
||||
index.add_reference(&sym.name, path_str, sym.line);
|
||||
}
|
||||
for alias in file_syms.aliases {
|
||||
index.add_alias_arc(alias.alias, alias.original);
|
||||
}
|
||||
index.set_file_meta(path_str, file_syms.file_meta);
|
||||
}
|
||||
// batch_symbols dropped here — frees the parallel-extracted symbols
|
||||
// before the next batch is parsed
|
||||
}
|
||||
|
||||
// Set the query version hash so we can detect query changes on cache load
|
||||
index.set_query_version(self.registry.compute_query_hash());
|
||||
|
||||
// Reclaim over-allocated Vec capacity that accumulated during bulk push().
|
||||
// This is a one-time cost paid here (O(symbols)) to permanently reduce RSS.
|
||||
index.compact();
|
||||
|
||||
Ok(index)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for IndexBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Process a single file using thread-local caching.
|
||||
/// Returns lightweight FileSymbols (no ScopeGraph overhead).
|
||||
///
|
||||
/// File path is stored as **relative** (to `root_path`) for portability.
|
||||
fn process_file_fast(
|
||||
path: &Path,
|
||||
root_path: &Path,
|
||||
registry: &LanguageRegistry,
|
||||
) -> Option<FileSymbols> {
|
||||
use crate::index_manager::MAX_INDEXABLE_FILE_SIZE;
|
||||
|
||||
let lang_config = registry.for_file_path(path)?;
|
||||
let lang_id = lang_config.primary_language_id().to_string();
|
||||
|
||||
let metadata = fs::metadata(path).ok()?;
|
||||
if metadata.len() == 0 || metadata.len() > MAX_INDEXABLE_FILE_SIZE {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Prefix-read binary check: only reads 8KB, not the whole file
|
||||
{
|
||||
use std::io::Read;
|
||||
let mut f = fs::File::open(path).ok()?;
|
||||
let mut buf = [0u8; 8000];
|
||||
let n = f.read(&mut buf).ok()?;
|
||||
if buf[..n].contains(&0) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
let content = fs::read(path).ok()?;
|
||||
|
||||
// Parse using thread-local cached parser
|
||||
let tree = PARSER_CACHE.with(|cache| {
|
||||
let mut cache = cache.borrow_mut();
|
||||
let parser = cache.entry(lang_id.clone()).or_insert_with(|| {
|
||||
let mut p = tree_sitter::Parser::new();
|
||||
let ts_lang = lang_config.language();
|
||||
let _ = p.set_language(&ts_lang);
|
||||
p
|
||||
});
|
||||
parser.parse(&content, None)
|
||||
})?;
|
||||
|
||||
let root_node = tree.root_node();
|
||||
|
||||
// Extract symbols using thread-local cached query
|
||||
let (definitions, references, aliases) = QUERY_CACHE.with(|cache| {
|
||||
let mut cache = cache.borrow_mut();
|
||||
let query = cache.entry(lang_id.clone()).or_insert_with(|| {
|
||||
lang_config.compile_query().unwrap_or_else(|_| {
|
||||
let ts_lang = lang_config.language();
|
||||
tree_sitter::Query::new(&ts_lang, "").expect("empty query should always work")
|
||||
})
|
||||
});
|
||||
extract_symbols_fast_inline(query, root_node, &content)
|
||||
});
|
||||
|
||||
// Reuse metadata from the size check above (no re-stat needed)
|
||||
|
||||
// Convert absolute path to relative for portable storage
|
||||
let rel_path = to_relative_path(root_path, path);
|
||||
|
||||
Some(FileSymbols {
|
||||
path: rel_path.to_string_lossy().into(),
|
||||
definitions,
|
||||
references,
|
||||
aliases,
|
||||
file_meta: FileMeta::from_metadata(&metadata),
|
||||
})
|
||||
}
|
||||
|
||||
/// Lightweight symbol extraction - returns proper typed vectors.
|
||||
/// Inlined for maximum performance (avoids function call overhead in hot loop).
|
||||
#[inline]
|
||||
fn extract_symbols_fast_inline(
|
||||
query: &tree_sitter::Query,
|
||||
root_node: tree_sitter::Node<'_>,
|
||||
src: &[u8],
|
||||
) -> (
|
||||
Vec<SymbolOccurrence>,
|
||||
Vec<SymbolOccurrence>,
|
||||
Vec<SymbolAlias>,
|
||||
) {
|
||||
use tree_sitter::StreamingIterator;
|
||||
|
||||
// Pre-compute capture indices for fast lookup
|
||||
let capture_names = query.capture_names();
|
||||
let mut is_def = vec![false; capture_names.len()];
|
||||
let mut is_ref = vec![false; capture_names.len()];
|
||||
let mut alias_original_idx: Option<usize> = None;
|
||||
let mut alias_name_idx: Option<usize> = None;
|
||||
|
||||
for (i, name) in capture_names.iter().enumerate() {
|
||||
if name.starts_with("name.definition.") {
|
||||
is_def[i] = true;
|
||||
} else if name.starts_with("name.reference.") {
|
||||
is_ref[i] = true;
|
||||
} else if *name == "alias.original" {
|
||||
alias_original_idx = Some(i);
|
||||
} else if *name == "alias.name" {
|
||||
alias_name_idx = Some(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-allocate with reasonable capacity
|
||||
let mut definitions: Vec<SymbolOccurrence> = Vec::with_capacity(64);
|
||||
let mut references: Vec<SymbolOccurrence> = Vec::with_capacity(256);
|
||||
let mut aliases: Vec<SymbolAlias> = Vec::with_capacity(8);
|
||||
|
||||
let mut cursor = tree_sitter::QueryCursor::new();
|
||||
let mut matches = cursor.matches(query, root_node, src);
|
||||
|
||||
while let Some(match_) = matches.next() {
|
||||
let mut alias_original: Option<&[u8]> = None;
|
||||
let mut alias_name: Option<&[u8]> = None;
|
||||
|
||||
for capture in match_.captures {
|
||||
let idx = capture.index as usize;
|
||||
let node = capture.node;
|
||||
let byte_range = node.byte_range();
|
||||
|
||||
if is_def.get(idx).copied().unwrap_or(false) {
|
||||
// Convert Cow<str> directly to Arc<str> - avoids intermediate String allocation
|
||||
let text: Arc<str> = String::from_utf8_lossy(&src[byte_range]).into();
|
||||
// Line numbers are 1-indexed
|
||||
definitions.push(SymbolOccurrence::new(text, node.start_position().row + 1));
|
||||
} else if is_ref.get(idx).copied().unwrap_or(false) {
|
||||
let text: Arc<str> = String::from_utf8_lossy(&src[byte_range]).into();
|
||||
references.push(SymbolOccurrence::new(text, node.start_position().row + 1));
|
||||
} else if Some(idx) == alias_original_idx {
|
||||
alias_original = Some(&src[byte_range]);
|
||||
} else if Some(idx) == alias_name_idx {
|
||||
alias_name = Some(&src[byte_range]);
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(original), Some(alias)) = (alias_original, alias_name) {
|
||||
// Convert Cow<str> directly to Arc<str> - avoids intermediate String allocation
|
||||
let orig_arc: Arc<str> = String::from_utf8_lossy(original).into();
|
||||
let alias_arc: Arc<str> = String::from_utf8_lossy(alias).into();
|
||||
aliases.push(SymbolAlias::new(alias_arc, orig_arc));
|
||||
}
|
||||
}
|
||||
|
||||
(definitions, references, aliases)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Index caching for fast loading.
|
||||
//!
|
||||
//! Uses a custom binary format with magic bytes "SGIX" for the new interned format.
|
||||
//! Automatically detects and skips legacy bincode format (returns error so caller can rebuild).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::scope_graph::ScopeGraphIndex;
|
||||
|
||||
/// Default cache file name.
|
||||
pub const CACHE_FILE_NAME: &str = ".goto_index.bin";
|
||||
|
||||
/// Error type for cache operations.
|
||||
#[derive(Debug)]
|
||||
pub enum CacheError {
|
||||
/// IO error.
|
||||
IoError(std::io::Error),
|
||||
/// Serialization error.
|
||||
SerializeError(String),
|
||||
/// Deserialization error.
|
||||
DeserializeError(String),
|
||||
/// Legacy format detected (caller should rebuild).
|
||||
LegacyFormat,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CacheError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
CacheError::IoError(e) => write!(f, "IO error: {}", e),
|
||||
CacheError::SerializeError(msg) => write!(f, "Serialization error: {}", msg),
|
||||
CacheError::DeserializeError(msg) => write!(f, "Deserialization error: {}", msg),
|
||||
CacheError::LegacyFormat => write!(f, "Legacy cache format detected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CacheError {}
|
||||
|
||||
impl From<std::io::Error> for CacheError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
CacheError::IoError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result type for cache operations.
|
||||
pub type Result<T> = std::result::Result<T, CacheError>;
|
||||
|
||||
/// Get the default cache path for a repository.
|
||||
pub fn get_cache_path(root_path: &Path) -> std::path::PathBuf {
|
||||
root_path.join(CACHE_FILE_NAME)
|
||||
}
|
||||
|
||||
/// Load an index from cache.
|
||||
///
|
||||
/// Uses the new binary format with magic bytes "SGIX".
|
||||
/// Returns `CacheError::LegacyFormat` if the file uses the old bincode format,
|
||||
/// signaling to the caller that a rebuild is needed.
|
||||
pub fn load_index(cache_path: &Path) -> Result<ScopeGraphIndex> {
|
||||
if !cache_path.exists() {
|
||||
return Err(CacheError::IoError(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"Cache file not found",
|
||||
)));
|
||||
}
|
||||
|
||||
// Use ScopeGraphIndex::load which handles format detection
|
||||
match ScopeGraphIndex::load(cache_path) {
|
||||
Ok(Some(index)) => Ok(index),
|
||||
Ok(None) => {
|
||||
// None means legacy format was detected
|
||||
tracing::info!(
|
||||
cache_path = %cache_path.display(),
|
||||
"Legacy cache format detected, will rebuild"
|
||||
);
|
||||
Err(CacheError::LegacyFormat)
|
||||
}
|
||||
Err(e) => Err(CacheError::IoError(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save an index to cache using the new binary format.
|
||||
pub fn save_index(cache_path: &Path, index: &ScopeGraphIndex) -> Result<()> {
|
||||
index.save(cache_path).map_err(CacheError::IoError)
|
||||
}
|
||||
|
||||
/// Save an index to cache asynchronously (in a background thread).
|
||||
///
|
||||
/// Returns immediately and spawns a thread to do the actual saving.
|
||||
/// Useful for saving the index without blocking the main thread.
|
||||
pub fn save_index_async(cache_path: std::path::PathBuf, index: ScopeGraphIndex) {
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = save_index(&cache_path, &index) {
|
||||
tracing::warn!("Failed to save index cache: {}", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Check if a cache exists and return its metadata.
|
||||
pub fn cache_exists(cache_path: &Path) -> bool {
|
||||
cache_path.exists()
|
||||
}
|
||||
|
||||
/// Get cache file size in bytes.
|
||||
pub fn cache_size(cache_path: &Path) -> Option<u64> {
|
||||
std::fs::metadata(cache_path).ok().map(|m| m.len())
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
//! Workspace-level locking for index operations.
|
||||
//!
|
||||
//! Provides both in-memory (same-process) and file-based (cross-process)
|
||||
//! coordination to prevent redundant index operations on the same workspace.
|
||||
//!
|
||||
//! ## Design
|
||||
//!
|
||||
//! - **In-memory locks**: Fast path for same-process deduplication using a global registry
|
||||
//! - **File locks**: Cross-process coordination using lock files with PID and timestamp
|
||||
//! - **Stale detection**: Locks are considered stale if the holding process is dead or timeout exceeded
|
||||
//!
|
||||
//! ## Lock Types
|
||||
//!
|
||||
//! - **Shared (Load)**: Multiple readers allowed, blocked during exclusive operations
|
||||
//! - **Exclusive (Save/Build/Refresh)**: Single writer, blocks all other operations
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use dashmap::DashMap;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
const LOAD_STALE_DURATION_SEC: u64 = 120;
|
||||
const SAVE_STALE_DURATION_SEC: u64 = 120;
|
||||
const BUILD_STALE_DURATION_SEC: u64 = 600;
|
||||
const BG_REFRESH_STALE_DURATION_SEC: u64 = 300;
|
||||
|
||||
/// Operations that require locking.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IndexOperation {
|
||||
/// Loading index from cache (shared/read lock).
|
||||
Load,
|
||||
/// Saving index to cache (exclusive).
|
||||
Save,
|
||||
/// Building index from scratch (exclusive).
|
||||
Build,
|
||||
/// Background validation and refresh (exclusive).
|
||||
BackgroundRefresh,
|
||||
}
|
||||
|
||||
impl IndexOperation {
|
||||
/// String representation for lock file.
|
||||
fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Load => "load",
|
||||
Self::Save => "save",
|
||||
Self::Build => "build",
|
||||
Self::BackgroundRefresh => "background_refresh",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation requires exclusive access.
|
||||
pub fn is_exclusive(&self) -> bool {
|
||||
match self {
|
||||
Self::Load => false, // Shared/read access
|
||||
Self::Save | Self::Build | Self::BackgroundRefresh => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeout after which a lock is considered stale.
|
||||
fn stale_timeout(&self) -> Duration {
|
||||
match self {
|
||||
Self::Load => Duration::from_secs(LOAD_STALE_DURATION_SEC),
|
||||
Self::Save => Duration::from_secs(SAVE_STALE_DURATION_SEC),
|
||||
Self::Build => Duration::from_secs(BUILD_STALE_DURATION_SEC),
|
||||
Self::BackgroundRefresh => Duration::from_secs(BG_REFRESH_STALE_DURATION_SEC),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IndexOperation {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// In-memory lock state for same-process deduplication.
|
||||
struct InMemoryLockState {
|
||||
operation: IndexOperation,
|
||||
readers: usize, // Count for shared locks
|
||||
exclusive: bool, // Whether an exclusive lock is held
|
||||
}
|
||||
|
||||
/// Global registry of in-memory locks (same process).
|
||||
/// Uses DashMap for lock-free concurrent access.
|
||||
static IN_MEMORY_LOCKS: Lazy<DashMap<PathBuf, InMemoryLockState>> = Lazy::new(DashMap::new);
|
||||
|
||||
/// A guard that releases the lock when dropped.
|
||||
pub struct WorkspaceLockGuard {
|
||||
workspace: PathBuf,
|
||||
lock_file_path: PathBuf,
|
||||
operation: IndexOperation,
|
||||
}
|
||||
|
||||
impl Drop for WorkspaceLockGuard {
|
||||
fn drop(&mut self) {
|
||||
// Release in-memory lock
|
||||
release_in_memory_lock(&self.workspace, self.operation);
|
||||
|
||||
// Release file lock (only for exclusive operations)
|
||||
if self.operation.is_exclusive()
|
||||
&& let Err(e) = std::fs::remove_file(&self.lock_file_path)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!(
|
||||
path = %self.lock_file_path.display(),
|
||||
error = %e,
|
||||
"Failed to remove lock file"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of trying to acquire a lock.
|
||||
pub enum LockResult {
|
||||
/// Lock acquired successfully.
|
||||
Acquired(WorkspaceLockGuard),
|
||||
/// Another operation is in progress.
|
||||
Busy {
|
||||
/// Description of the blocking operation.
|
||||
operation: String,
|
||||
/// PID of the process holding the lock (if known).
|
||||
holder_pid: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl LockResult {
|
||||
/// Returns true if the lock was acquired.
|
||||
pub fn is_acquired(&self) -> bool {
|
||||
matches!(self, Self::Acquired(_))
|
||||
}
|
||||
|
||||
/// Unwrap the guard, panicking if busy.
|
||||
pub fn unwrap(self) -> WorkspaceLockGuard {
|
||||
match self {
|
||||
Self::Acquired(guard) => guard,
|
||||
Self::Busy { operation, .. } => {
|
||||
panic!("Lock was busy: {}", operation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to acquire a lock for an index operation on a workspace.
|
||||
///
|
||||
/// Returns `LockResult::Acquired` with a guard if successful, or `LockResult::Busy`
|
||||
/// if another operation is in progress.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `workspace` - The workspace root path
|
||||
/// * `operation` - The type of operation to perform
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// use xai_codebase_graph::manager::lock::{try_lock, IndexOperation, LockResult};
|
||||
///
|
||||
/// let workspace = Path::new("/path/to/workspace");
|
||||
/// match try_lock(workspace, IndexOperation::Build) {
|
||||
/// LockResult::Acquired(guard) => {
|
||||
/// // Do work...
|
||||
/// // Lock is released when guard is dropped
|
||||
/// }
|
||||
/// LockResult::Busy { operation, holder_pid } => {
|
||||
/// println!("Busy: {} by pid {:?}", operation, holder_pid);
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub fn try_lock(workspace: &Path, operation: IndexOperation) -> LockResult {
|
||||
let workspace = canonicalize_workspace(workspace);
|
||||
let lock_file_path = get_lock_file_path(&workspace);
|
||||
|
||||
// Step 1: Check/acquire in-memory lock (fast path for same process)
|
||||
if !try_acquire_in_memory_lock(&workspace, operation) {
|
||||
tracing::debug!(
|
||||
workspace = %workspace.display(),
|
||||
operation = %operation,
|
||||
"In-memory lock busy"
|
||||
);
|
||||
return LockResult::Busy {
|
||||
operation: format!("{} (same process)", operation),
|
||||
holder_pid: Some(std::process::id()),
|
||||
};
|
||||
}
|
||||
|
||||
// Step 2: For exclusive operations, also acquire file lock (cross-process)
|
||||
if operation.is_exclusive() {
|
||||
match try_acquire_file_lock(&lock_file_path, operation) {
|
||||
Ok(()) => {
|
||||
tracing::debug!(
|
||||
workspace = %workspace.display(),
|
||||
operation = %operation,
|
||||
lock_file = %lock_file_path.display(),
|
||||
"Acquired exclusive lock"
|
||||
);
|
||||
}
|
||||
Err((op, pid)) => {
|
||||
// Release in-memory lock since we failed to get file lock
|
||||
release_in_memory_lock(&workspace, operation);
|
||||
tracing::debug!(
|
||||
workspace = %workspace.display(),
|
||||
operation = %operation,
|
||||
blocking_op = %op,
|
||||
blocking_pid = ?pid,
|
||||
"File lock busy"
|
||||
);
|
||||
return LockResult::Busy {
|
||||
operation: op,
|
||||
holder_pid: pid,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LockResult::Acquired(WorkspaceLockGuard {
|
||||
workspace,
|
||||
lock_file_path,
|
||||
operation,
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if an operation is currently in progress for a workspace.
|
||||
///
|
||||
/// This is a non-blocking check that doesn't acquire any locks.
|
||||
pub fn is_operation_in_progress(workspace: &Path, operation: IndexOperation) -> bool {
|
||||
let workspace = canonicalize_workspace(workspace);
|
||||
|
||||
// Check in-memory first
|
||||
if let Some(state) = IN_MEMORY_LOCKS.get(&workspace) {
|
||||
if operation.is_exclusive() {
|
||||
if state.readers > 0 || state.exclusive {
|
||||
return true;
|
||||
}
|
||||
} else if state.exclusive {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check file lock for exclusive operations
|
||||
if operation.is_exclusive()
|
||||
&& let Ok(contents) = std::fs::read_to_string(get_lock_file_path(&workspace))
|
||||
&& let Some((_, pid, started)) = parse_lock_file(&contents)
|
||||
{
|
||||
let age = SystemTime::now()
|
||||
.duration_since(started)
|
||||
.unwrap_or(Duration::ZERO);
|
||||
if age < operation.stale_timeout() && is_process_alive(pid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Canonicalize workspace path for consistent lock keys.
|
||||
fn canonicalize_workspace(workspace: &Path) -> PathBuf {
|
||||
// Try to canonicalize, fall back to the original path
|
||||
dunce::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf())
|
||||
}
|
||||
|
||||
/// Get the lock file path for a workspace.
|
||||
fn get_lock_file_path(workspace: &Path) -> PathBuf {
|
||||
// Use the cache directory (same as where .goto_index.bin is stored)
|
||||
let cache_path = super::get_cache_path(workspace);
|
||||
cache_path.with_extension("lock")
|
||||
}
|
||||
|
||||
/// Try to acquire an in-memory lock for same-process deduplication.
|
||||
fn try_acquire_in_memory_lock(workspace: &Path, operation: IndexOperation) -> bool {
|
||||
// Use entry API for atomic check-and-modify
|
||||
match IN_MEMORY_LOCKS.entry(workspace.to_path_buf()) {
|
||||
dashmap::mapref::entry::Entry::Occupied(mut entry) => {
|
||||
let state = entry.get_mut();
|
||||
if operation.is_exclusive() {
|
||||
// Exclusive operation - must have no readers or existing exclusive
|
||||
if state.readers > 0 || state.exclusive {
|
||||
return false;
|
||||
}
|
||||
state.exclusive = true;
|
||||
state.operation = operation;
|
||||
} else {
|
||||
// Shared operation (Load) - OK if no exclusive lock
|
||||
if state.exclusive {
|
||||
return false;
|
||||
}
|
||||
state.readers += 1;
|
||||
}
|
||||
}
|
||||
dashmap::mapref::entry::Entry::Vacant(entry) => {
|
||||
// No existing lock - create one
|
||||
entry.insert(InMemoryLockState {
|
||||
operation,
|
||||
readers: if operation.is_exclusive() { 0 } else { 1 },
|
||||
exclusive: operation.is_exclusive(),
|
||||
});
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Release an in-memory lock.
|
||||
fn release_in_memory_lock(workspace: &Path, operation: IndexOperation) {
|
||||
// Use entry API for atomic check-and-modify
|
||||
if let dashmap::mapref::entry::Entry::Occupied(mut entry) =
|
||||
IN_MEMORY_LOCKS.entry(workspace.to_path_buf())
|
||||
{
|
||||
let should_remove = {
|
||||
let state = entry.get_mut();
|
||||
if operation.is_exclusive() {
|
||||
state.exclusive = false;
|
||||
} else {
|
||||
state.readers = state.readers.saturating_sub(1);
|
||||
}
|
||||
// Check if we should remove the entry
|
||||
!state.exclusive && state.readers == 0
|
||||
};
|
||||
|
||||
if should_remove {
|
||||
entry.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to acquire a file-based lock for cross-process coordination.
|
||||
fn try_acquire_file_lock(
|
||||
lock_path: &Path,
|
||||
operation: IndexOperation,
|
||||
) -> Result<(), (String, Option<u32>)> {
|
||||
// Check if existing lock file is valid
|
||||
if let Ok(contents) = std::fs::read_to_string(lock_path)
|
||||
&& let Some((op, pid, started)) = parse_lock_file(&contents)
|
||||
{
|
||||
// Check if lock is stale
|
||||
let age = SystemTime::now()
|
||||
.duration_since(started)
|
||||
.unwrap_or(Duration::ZERO);
|
||||
|
||||
if age < operation.stale_timeout() && is_process_alive(pid) {
|
||||
return Err((op, Some(pid)));
|
||||
}
|
||||
// Lock is stale - we can take over
|
||||
tracing::debug!(
|
||||
lock_path = %lock_path.display(),
|
||||
stale_op = %op,
|
||||
stale_pid = pid,
|
||||
age_secs = age.as_secs(),
|
||||
"Taking over stale lock"
|
||||
);
|
||||
}
|
||||
|
||||
// Create parent directory if needed
|
||||
if let Some(parent) = lock_path.parent()
|
||||
&& let Err(e) = std::fs::create_dir_all(parent)
|
||||
{
|
||||
tracing::warn!(
|
||||
path = %parent.display(),
|
||||
error = %e,
|
||||
"Failed to create lock directory"
|
||||
);
|
||||
}
|
||||
|
||||
// Write our lock file
|
||||
let contents = format!(
|
||||
"operation={}\npid={}\nstarted={}\nworkspace={}\n",
|
||||
operation.as_str(),
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs(),
|
||||
lock_path
|
||||
.parent()
|
||||
.and_then(|p| p.file_name())
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("unknown")
|
||||
);
|
||||
|
||||
std::fs::write(lock_path, contents).map_err(|e| (format!("io_error: {}", e), None))
|
||||
}
|
||||
|
||||
/// Parse a lock file's contents.
|
||||
fn parse_lock_file(contents: &str) -> Option<(String, u32, SystemTime)> {
|
||||
let mut operation = None;
|
||||
let mut pid = None;
|
||||
let mut started = None;
|
||||
|
||||
for line in contents.lines() {
|
||||
if let Some(val) = line.strip_prefix("operation=") {
|
||||
operation = Some(val.to_string());
|
||||
} else if let Some(val) = line.strip_prefix("pid=") {
|
||||
pid = val.parse().ok();
|
||||
} else if let Some(val) = line.strip_prefix("started=")
|
||||
&& let Ok(secs) = val.parse::<u64>()
|
||||
{
|
||||
started = Some(UNIX_EPOCH + Duration::from_secs(secs));
|
||||
}
|
||||
}
|
||||
|
||||
match (operation, pid, started) {
|
||||
(Some(op), Some(p), Some(s)) => Some((op, p, s)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a process is still alive.
|
||||
#[cfg(unix)]
|
||||
fn is_process_alive(pid: u32) -> bool {
|
||||
// kill with signal 0 checks if process exists without sending a signal
|
||||
// Returns 0 if process exists and we have permission to send signals
|
||||
// Returns -1 with ESRCH if process doesn't exist
|
||||
unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn is_process_alive(_pid: u32) -> bool {
|
||||
// On non-Unix platforms, rely on timeout-based stale detection
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_exclusive_lock_blocks_exclusive() {
|
||||
let dir = tempdir().unwrap();
|
||||
let workspace = dir.path();
|
||||
|
||||
// Acquire first exclusive lock
|
||||
let guard1 = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(guard1.is_acquired());
|
||||
|
||||
// Second exclusive lock should fail
|
||||
let result2 = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(!result2.is_acquired());
|
||||
|
||||
// Drop first lock
|
||||
drop(guard1);
|
||||
|
||||
// Now second should succeed
|
||||
let guard3 = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(guard3.is_acquired());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shared_locks_coexist() {
|
||||
let dir = tempdir().unwrap();
|
||||
let workspace = dir.path();
|
||||
|
||||
// Multiple shared locks should work
|
||||
let guard1 = try_lock(workspace, IndexOperation::Load);
|
||||
assert!(guard1.is_acquired());
|
||||
|
||||
let guard2 = try_lock(workspace, IndexOperation::Load);
|
||||
assert!(guard2.is_acquired());
|
||||
|
||||
let guard3 = try_lock(workspace, IndexOperation::Load);
|
||||
assert!(guard3.is_acquired());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_exclusive_blocks_shared() {
|
||||
let dir = tempdir().unwrap();
|
||||
let workspace = dir.path();
|
||||
|
||||
// Acquire exclusive lock
|
||||
let guard1 = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(guard1.is_acquired());
|
||||
|
||||
// Shared lock should fail
|
||||
let result2 = try_lock(workspace, IndexOperation::Load);
|
||||
assert!(!result2.is_acquired());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shared_blocks_exclusive() {
|
||||
let dir = tempdir().unwrap();
|
||||
let workspace = dir.path();
|
||||
|
||||
// Acquire shared lock
|
||||
let guard1 = try_lock(workspace, IndexOperation::Load);
|
||||
assert!(guard1.is_acquired());
|
||||
|
||||
// Exclusive lock should fail
|
||||
let result2 = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(!result2.is_acquired());
|
||||
|
||||
// Drop shared lock
|
||||
drop(guard1);
|
||||
|
||||
// Now exclusive should succeed
|
||||
let guard3 = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(guard3.is_acquired());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_workspaces_independent() {
|
||||
let dir1 = tempdir().unwrap();
|
||||
let dir2 = tempdir().unwrap();
|
||||
|
||||
// Locks on different workspaces should be independent
|
||||
let guard1 = try_lock(dir1.path(), IndexOperation::Build);
|
||||
assert!(guard1.is_acquired());
|
||||
|
||||
let guard2 = try_lock(dir2.path(), IndexOperation::Build);
|
||||
assert!(guard2.is_acquired());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lock_file_created_for_exclusive() {
|
||||
let dir = tempdir().unwrap();
|
||||
let workspace = dir.path();
|
||||
|
||||
let lock_file = get_lock_file_path(workspace);
|
||||
|
||||
// No lock file initially
|
||||
assert!(!lock_file.exists());
|
||||
|
||||
// Acquire exclusive lock
|
||||
let guard = try_lock(workspace, IndexOperation::Build);
|
||||
assert!(guard.is_acquired());
|
||||
|
||||
// Lock file should exist
|
||||
assert!(lock_file.exists());
|
||||
|
||||
// Check contents
|
||||
let contents = std::fs::read_to_string(&lock_file).unwrap();
|
||||
assert!(contents.contains("operation=build"));
|
||||
assert!(contents.contains(&format!("pid={}", std::process::id())));
|
||||
|
||||
// Drop guard
|
||||
drop(guard);
|
||||
|
||||
// Lock file should be removed
|
||||
assert!(!lock_file.exists());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Index management: building, caching, locking, and updating.
|
||||
|
||||
mod builder;
|
||||
pub mod cache;
|
||||
pub mod lock;
|
||||
|
||||
pub use builder::{IndexBuilder, IndexError, Result};
|
||||
pub use cache::{
|
||||
CACHE_FILE_NAME, CacheError, cache_exists, cache_size, get_cache_path, load_index, save_index,
|
||||
save_index_async,
|
||||
};
|
||||
pub use lock::{
|
||||
IndexOperation, LockResult, WorkspaceLockGuard, is_operation_in_progress, try_lock,
|
||||
};
|
||||
@@ -0,0 +1,844 @@
|
||||
//! Location-based navigation APIs for go-to-definition and go-to-references.
|
||||
//!
|
||||
//! This module provides APIs that take a file path and position (row, column)
|
||||
//! and return definition or reference locations.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::languages::LanguageRegistry;
|
||||
use crate::scope_graph::ScopeGraphIndex;
|
||||
|
||||
/// Result of a navigation operation (go-to-definition or go-to-references).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NavigationResult {
|
||||
/// The symbol that was found at the query position.
|
||||
pub symbol: String,
|
||||
/// List of locations where the symbol is defined/referenced.
|
||||
pub locations: Vec<Location>,
|
||||
}
|
||||
|
||||
/// A location in a file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Location {
|
||||
/// Path to the file.
|
||||
pub path: String,
|
||||
/// 1-indexed line number.
|
||||
pub line: usize,
|
||||
/// Optional: the matched symbol name (useful for aliases).
|
||||
pub symbol: Option<String>,
|
||||
}
|
||||
|
||||
impl Location {
|
||||
pub fn new(path: impl Into<String>, line: usize) -> Self {
|
||||
Self {
|
||||
path: path.into(),
|
||||
line,
|
||||
symbol: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_symbol(path: impl Into<String>, line: usize, symbol: String) -> Self {
|
||||
Self {
|
||||
path: path.into(),
|
||||
line,
|
||||
symbol: Some(symbol),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the path as a Path reference.
|
||||
pub fn as_path(&self) -> &Path {
|
||||
Path::new(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Error type for navigation operations.
|
||||
#[derive(Debug)]
|
||||
pub enum NavigationError {
|
||||
/// File not found or could not be read.
|
||||
FileNotFound(PathBuf),
|
||||
/// Position is out of bounds for the file.
|
||||
PositionOutOfBounds { row: usize, col: usize },
|
||||
/// No symbol found at the given position.
|
||||
NoSymbolAtPosition { row: usize, col: usize },
|
||||
/// Language not supported for this file type.
|
||||
UnsupportedLanguage(String),
|
||||
/// Parse error.
|
||||
ParseError(String),
|
||||
/// IO error.
|
||||
IoError(std::io::Error),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NavigationError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
NavigationError::FileNotFound(path) => {
|
||||
write!(f, "File not found: {}", path.display())
|
||||
}
|
||||
NavigationError::PositionOutOfBounds { row, col } => {
|
||||
write!(f, "Position out of bounds: {}:{}", row, col)
|
||||
}
|
||||
NavigationError::NoSymbolAtPosition { row, col } => {
|
||||
write!(f, "No symbol found at position {}:{}", row, col)
|
||||
}
|
||||
NavigationError::UnsupportedLanguage(ext) => {
|
||||
write!(f, "Unsupported language: {}", ext)
|
||||
}
|
||||
NavigationError::ParseError(msg) => write!(f, "Parse error: {}", msg),
|
||||
NavigationError::IoError(e) => write!(f, "IO error: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for NavigationError {}
|
||||
|
||||
impl From<std::io::Error> for NavigationError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
NavigationError::IoError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigator provides location-based code navigation.
|
||||
///
|
||||
/// It wraps a ScopeGraphIndex and provides methods to navigate code
|
||||
/// based on file path and position (row, column).
|
||||
pub struct Navigator {
|
||||
index: Arc<ScopeGraphIndex>,
|
||||
registry: LanguageRegistry,
|
||||
}
|
||||
|
||||
impl Navigator {
|
||||
/// Create a new Navigator backed by a shared index.
|
||||
///
|
||||
/// Accepts anything that converts into `Arc<ScopeGraphIndex>`, so both
|
||||
/// owned and already-shared indexes work without extra wrapping:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// // From an owned index (e.g. IndexBuilder)
|
||||
/// let navigator = Navigator::new(index);
|
||||
///
|
||||
/// // From a shared snapshot (zero-cost)
|
||||
/// let snapshot = handle.get_snapshot()?;
|
||||
/// let navigator = Navigator::new(snapshot);
|
||||
/// ```
|
||||
pub fn new(index: impl Into<Arc<ScopeGraphIndex>>) -> Self {
|
||||
Self {
|
||||
index: index.into(),
|
||||
registry: LanguageRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a reference to the underlying index.
|
||||
pub fn index(&self) -> &ScopeGraphIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
/// Get a mutable reference to the underlying index.
|
||||
///
|
||||
/// Uses copy-on-write: if other `Arc` clones of the index exist, the
|
||||
/// index is cloned before returning the mutable reference.
|
||||
pub fn index_mut(&mut self) -> &mut ScopeGraphIndex {
|
||||
Arc::make_mut(&mut self.index)
|
||||
}
|
||||
|
||||
/// Get the symbol at the given file path and position.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `file_path` - Path to the file
|
||||
/// * `row` - 1-indexed line number
|
||||
/// * `col` - 1-indexed column number
|
||||
///
|
||||
/// # Returns
|
||||
/// The symbol name at the given position.
|
||||
pub fn get_symbol_at_position(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
row: usize,
|
||||
col: usize,
|
||||
) -> Result<String, NavigationError> {
|
||||
// Validate position (1-indexed)
|
||||
if row == 0 || col == 0 {
|
||||
return Err(NavigationError::PositionOutOfBounds { row, col });
|
||||
}
|
||||
|
||||
let content = std::fs::read(file_path)
|
||||
.map_err(|_| NavigationError::FileNotFound(file_path.to_path_buf()))?;
|
||||
|
||||
// Get the language config
|
||||
let lang_config = self.registry.for_file_path(file_path).ok_or_else(|| {
|
||||
NavigationError::UnsupportedLanguage(
|
||||
file_path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Parse the file
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
parser
|
||||
.set_language(&lang_config.language())
|
||||
.map_err(|e| NavigationError::ParseError(format!("Failed to set language: {}", e)))?;
|
||||
|
||||
let tree = parser
|
||||
.parse(&content, None)
|
||||
.ok_or_else(|| NavigationError::ParseError("Failed to parse file".to_string()))?;
|
||||
|
||||
// Convert 1-indexed row/col to 0-indexed for tree-sitter
|
||||
let point = tree_sitter::Point::new(row - 1, col - 1);
|
||||
|
||||
// Find the node at the position
|
||||
let root = tree.root_node();
|
||||
let node = find_smallest_named_node_at_point(root, point);
|
||||
|
||||
match node {
|
||||
Some(n) => {
|
||||
let text = std::str::from_utf8(&content[n.byte_range()])
|
||||
.map_err(|_| NavigationError::ParseError("Invalid UTF-8".to_string()))?;
|
||||
Ok(text.to_string())
|
||||
}
|
||||
None => Err(NavigationError::NoSymbolAtPosition { row, col }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Go to definition for the symbol at the given position.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `file_path` - Path to the file
|
||||
/// * `row` - 1-indexed line number
|
||||
/// * `col` - 1-indexed column number
|
||||
///
|
||||
/// # Returns
|
||||
/// NavigationResult containing the symbol and its definition locations.
|
||||
pub fn goto_definition(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
row: usize,
|
||||
col: usize,
|
||||
) -> Result<NavigationResult, NavigationError> {
|
||||
let symbol = self.get_symbol_at_position(file_path, row, col)?;
|
||||
|
||||
// Look up definitions in the index
|
||||
let defs =
|
||||
self.index
|
||||
.find_definitions_smart(&symbol, Some(file_path), Some(&self.registry));
|
||||
|
||||
let locations: Vec<Location> = defs
|
||||
.into_iter()
|
||||
.map(|(path, line)| Location::new(path, line))
|
||||
.collect();
|
||||
|
||||
Ok(NavigationResult { symbol, locations })
|
||||
}
|
||||
|
||||
/// Go to references for the symbol at the given position.
|
||||
///
|
||||
/// This first resolves the symbol to its definition, then finds all references.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `file_path` - Path to the file
|
||||
/// * `row` - 1-indexed line number
|
||||
/// * `col` - 1-indexed column number
|
||||
/// * `include_definition` - Whether to include the definition location in results
|
||||
///
|
||||
/// # Returns
|
||||
/// NavigationResult containing the symbol and its reference locations.
|
||||
pub fn goto_references(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
row: usize,
|
||||
col: usize,
|
||||
include_definition: bool,
|
||||
) -> Result<NavigationResult, NavigationError> {
|
||||
let symbol = self.get_symbol_at_position(file_path, row, col)?;
|
||||
|
||||
// Get references (includes alias resolution)
|
||||
let refs = self
|
||||
.index
|
||||
.find_references_smart(&symbol, Some(file_path), Some(&self.registry));
|
||||
|
||||
let mut locations: Vec<Location> = refs
|
||||
.into_iter()
|
||||
.map(|(sym, path, line)| Location::with_symbol(path, line, sym))
|
||||
.collect();
|
||||
|
||||
// Optionally include definition locations
|
||||
if include_definition {
|
||||
let defs =
|
||||
self.index
|
||||
.find_definitions_smart(&symbol, Some(file_path), Some(&self.registry));
|
||||
|
||||
for (path, line) in defs {
|
||||
let loc = Location::new(path, line);
|
||||
if !locations
|
||||
.iter()
|
||||
.any(|l| l.path == loc.path && l.line == loc.line)
|
||||
{
|
||||
locations.insert(0, loc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(NavigationResult { symbol, locations })
|
||||
}
|
||||
|
||||
/// Go to definition by symbol name directly (without position lookup).
|
||||
pub fn goto_definition_by_name(
|
||||
&self,
|
||||
symbol: &str,
|
||||
context_file: Option<&Path>,
|
||||
) -> NavigationResult {
|
||||
let defs = self
|
||||
.index
|
||||
.find_definitions_smart(symbol, context_file, Some(&self.registry));
|
||||
|
||||
let locations: Vec<Location> = defs
|
||||
.into_iter()
|
||||
.map(|(path, line)| Location::new(path, line))
|
||||
.collect();
|
||||
|
||||
NavigationResult {
|
||||
symbol: symbol.to_string(),
|
||||
locations,
|
||||
}
|
||||
}
|
||||
|
||||
/// Go to references by symbol name directly (without position lookup).
|
||||
pub fn goto_references_by_name(
|
||||
&self,
|
||||
symbol: &str,
|
||||
context_file: Option<&Path>,
|
||||
include_definition: bool,
|
||||
) -> NavigationResult {
|
||||
let refs = self
|
||||
.index
|
||||
.find_references_smart(symbol, context_file, Some(&self.registry));
|
||||
|
||||
let mut locations: Vec<Location> = refs
|
||||
.into_iter()
|
||||
.map(|(sym, path, line)| Location::with_symbol(path, line, sym))
|
||||
.collect();
|
||||
|
||||
if include_definition {
|
||||
let defs =
|
||||
self.index
|
||||
.find_definitions_smart(symbol, context_file, Some(&self.registry));
|
||||
|
||||
for (path, line) in defs {
|
||||
let loc = Location::new(path, line);
|
||||
if !locations
|
||||
.iter()
|
||||
.any(|l| l.path == loc.path && l.line == loc.line)
|
||||
{
|
||||
locations.insert(0, loc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NavigationResult {
|
||||
symbol: symbol.to_string(),
|
||||
locations,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the smallest named node that contains the given point.
|
||||
fn find_smallest_named_node_at_point(
|
||||
node: tree_sitter::Node<'_>,
|
||||
point: tree_sitter::Point,
|
||||
) -> Option<tree_sitter::Node<'_>> {
|
||||
// Check if point is within this node
|
||||
if point < node.start_position() || point > node.end_position() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Try to find a smaller child node that contains the point
|
||||
let mut cursor = node.walk();
|
||||
for child in node.children(&mut cursor) {
|
||||
if let Some(found) = find_smallest_named_node_at_point(child, point) {
|
||||
// Prefer named nodes that look like identifiers
|
||||
if is_identifier_like(&found) {
|
||||
return Some(found);
|
||||
}
|
||||
// Keep searching for a better match
|
||||
if is_identifier_like(&child) {
|
||||
return Some(child);
|
||||
}
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
|
||||
// No smaller child contains the point, return this node if it's identifier-like
|
||||
if is_identifier_like(&node) {
|
||||
Some(node)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a node looks like an identifier.
|
||||
fn is_identifier_like(node: &tree_sitter::Node<'_>) -> bool {
|
||||
let kind = node.kind();
|
||||
matches!(
|
||||
kind,
|
||||
"identifier"
|
||||
| "type_identifier"
|
||||
| "property_identifier"
|
||||
| "field_identifier"
|
||||
| "shorthand_property_identifier"
|
||||
| "shorthand_property_identifier_pattern"
|
||||
| "attribute" // Python
|
||||
| "package_identifier" // Go
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::IndexBuilder;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_get_symbol_at_position() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.rs");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(file, "fn hello_world() {{").unwrap();
|
||||
writeln!(file, " println!(\"Hello\");").unwrap();
|
||||
writeln!(file, "}}").unwrap();
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Get symbol at "hello_world" (row 1, col 4)
|
||||
let symbol = navigator.get_symbol_at_position(&file_path, 1, 4).unwrap();
|
||||
assert_eq!(symbol, "hello_world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_for_of_array_destructuring() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"const myMap = new Map<string, {{ sessionId: string }}>();
|
||||
|
||||
function test(sessionId: string) {{
|
||||
for (const [toolCallId, request] of myMap) {{
|
||||
if (request.sessionId !== sessionId) continue;
|
||||
console.log(toolCallId);
|
||||
}}
|
||||
}}"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'request' is found as a definition at line 4
|
||||
let def_result = navigator.goto_definition_by_name("request", Some(&file_path));
|
||||
assert!(
|
||||
!def_result.locations.is_empty(),
|
||||
"request should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result.locations[0].line, 4,
|
||||
"request should be defined on line 4"
|
||||
);
|
||||
|
||||
// Test that 'toolCallId' is also found as a definition at line 4
|
||||
let def_result2 = navigator.goto_definition_by_name("toolCallId", Some(&file_path));
|
||||
assert!(
|
||||
!def_result2.locations.is_empty(),
|
||||
"toolCallId should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result2.locations[0].line, 4,
|
||||
"toolCallId should be defined on line 4"
|
||||
);
|
||||
|
||||
// Test that references to 'request' are found
|
||||
let ref_result = navigator.goto_references_by_name("request", Some(&file_path), false);
|
||||
assert!(
|
||||
!ref_result.locations.is_empty(),
|
||||
"request should have references"
|
||||
);
|
||||
// Check that line 5 reference is found (request.sessionId)
|
||||
let line5_ref = ref_result.locations.iter().any(|loc| loc.line == 5);
|
||||
assert!(line5_ref, "request should be referenced on line 5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_for_of_object_destructuring() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"const items = [{{ name: "a", value: 1 }}];
|
||||
|
||||
for (const {{ name, value }} of items) {{
|
||||
console.log(name, value);
|
||||
}}"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'name' is found as a definition at line 3
|
||||
let def_result = navigator.goto_definition_by_name("name", Some(&file_path));
|
||||
assert!(
|
||||
!def_result.locations.is_empty(),
|
||||
"name should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result.locations[0].line, 3,
|
||||
"name should be defined on line 3"
|
||||
);
|
||||
|
||||
// Test that 'value' is found as a definition at line 3
|
||||
let def_result2 = navigator.goto_definition_by_name("value", Some(&file_path));
|
||||
assert!(
|
||||
!def_result2.locations.is_empty(),
|
||||
"value should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result2.locations[0].line, 3,
|
||||
"value should be defined on line 3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_regular_array_destructuring() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"const arr = [1, 2, 3];
|
||||
const [first, second, third] = arr;
|
||||
console.log(first, second);"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'first' is found as a definition at line 2
|
||||
let def_result = navigator.goto_definition_by_name("first", Some(&file_path));
|
||||
assert!(
|
||||
!def_result.locations.is_empty(),
|
||||
"first should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result.locations[0].line, 2,
|
||||
"first should be defined on line 2"
|
||||
);
|
||||
|
||||
// Test that 'second' is found as a definition at line 2
|
||||
let def_result2 = navigator.goto_definition_by_name("second", Some(&file_path));
|
||||
assert!(
|
||||
!def_result2.locations.is_empty(),
|
||||
"second should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result2.locations[0].line, 2,
|
||||
"second should be defined on line 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_regular_object_destructuring() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"const obj = {{ foo: 1, bar: 2 }};
|
||||
const {{ foo, bar }} = obj;
|
||||
console.log(foo, bar);"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'foo' is found as a definition at line 2
|
||||
let def_result = navigator.goto_definition_by_name("foo", Some(&file_path));
|
||||
assert!(
|
||||
!def_result.locations.is_empty(),
|
||||
"foo should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result.locations[0].line, 2,
|
||||
"foo should be defined on line 2"
|
||||
);
|
||||
|
||||
// Test that 'bar' is found as a definition at line 2
|
||||
let def_result2 = navigator.goto_definition_by_name("bar", Some(&file_path));
|
||||
assert!(
|
||||
!def_result2.locations.is_empty(),
|
||||
"bar should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result2.locations[0].line, 2,
|
||||
"bar should be defined on line 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_member_expression_reference() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"const myObject = {{ value: 42 }};
|
||||
const result = myObject.value;"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'myObject' is referenced on line 2 (myObject.value)
|
||||
let ref_result = navigator.goto_references_by_name("myObject", Some(&file_path), false);
|
||||
assert!(
|
||||
!ref_result.locations.is_empty(),
|
||||
"myObject should have references"
|
||||
);
|
||||
let line2_ref = ref_result.locations.iter().any(|loc| loc.line == 2);
|
||||
assert!(line2_ref, "myObject should be referenced on line 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_function_parameter_destructuring() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"function process([first, second]: number[], {{ name }}: {{ name: string }}) {{
|
||||
console.log(first, second, name);
|
||||
}}"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'first' is found as a definition at line 1
|
||||
let def_result = navigator.goto_definition_by_name("first", Some(&file_path));
|
||||
assert!(
|
||||
!def_result.locations.is_empty(),
|
||||
"first should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result.locations[0].line, 1,
|
||||
"first should be defined on line 1"
|
||||
);
|
||||
|
||||
// Test that 'name' is found as a definition at line 1
|
||||
let def_result2 = navigator.goto_definition_by_name("name", Some(&file_path));
|
||||
assert!(
|
||||
!def_result2.locations.is_empty(),
|
||||
"name should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result2.locations[0].line, 1,
|
||||
"name should be defined on line 1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_simple_function_parameters() {
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("test.ts");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"function greet(name: string, age: number) {{
|
||||
console.log(name, age);
|
||||
}}"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'name' is found as a definition at line 1
|
||||
let def_result = navigator.goto_definition_by_name("name", Some(&file_path));
|
||||
assert!(
|
||||
!def_result.locations.is_empty(),
|
||||
"name should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result.locations[0].line, 1,
|
||||
"name should be defined on line 1"
|
||||
);
|
||||
|
||||
// Test that 'age' is found as a definition at line 1
|
||||
let def_result2 = navigator.goto_definition_by_name("age", Some(&file_path));
|
||||
assert!(
|
||||
!def_result2.locations.is_empty(),
|
||||
"age should be found as a definition"
|
||||
);
|
||||
assert_eq!(
|
||||
def_result2.locations[0].line, 1,
|
||||
"age should be defined on line 1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_typescript_react_dependency_array_references() {
|
||||
// Test that identifiers in React hook dependency arrays are captured as references
|
||||
// Regression test for dependency-array reference capture.
|
||||
let dir = tempdir().unwrap();
|
||||
let file_path = dir.path().join("component.tsx");
|
||||
|
||||
let mut file = File::create(&file_path).unwrap();
|
||||
writeln!(
|
||||
file,
|
||||
r#"import {{ useCallback, useEffect }} from 'react';
|
||||
|
||||
function FileTreeTab({{ basePath, onFileSelect }}) {{
|
||||
const fileTree = useFileTree();
|
||||
|
||||
const loadDirectory = useCallback(
|
||||
(path: string) => {{
|
||||
return fileTree.listFiles(path);
|
||||
}},
|
||||
[fileTree],
|
||||
);
|
||||
|
||||
const handleOpenPath = useCallback(
|
||||
(path: string) => {{
|
||||
loadDirectory(path);
|
||||
}},
|
||||
[loadDirectory, fileTree],
|
||||
);
|
||||
|
||||
const handleFileSelect = useCallback(
|
||||
(file) => {{
|
||||
fileTree.setSelectedPath(file.absPath);
|
||||
onFileSelect(file.absPath);
|
||||
}},
|
||||
[fileTree, onFileSelect],
|
||||
);
|
||||
|
||||
useEffect(() => {{
|
||||
loadDirectory(basePath);
|
||||
}}, [basePath, loadDirectory]);
|
||||
|
||||
return null;
|
||||
}}"#
|
||||
)
|
||||
.unwrap();
|
||||
drop(file);
|
||||
|
||||
let index = IndexBuilder::new().build(dir.path()).unwrap();
|
||||
let navigator = Navigator::new(index);
|
||||
|
||||
// Test that 'fileTree' is found in dependency arrays
|
||||
let ref_result = navigator.goto_references_by_name("fileTree", Some(&file_path), false);
|
||||
assert!(
|
||||
!ref_result.locations.is_empty(),
|
||||
"fileTree should have references"
|
||||
);
|
||||
|
||||
// Check references in dependency arrays:
|
||||
// Line 10: [fileTree]
|
||||
// Line 17: [loadDirectory, fileTree]
|
||||
// Line 25: [fileTree, onFileSelect]
|
||||
let dep_array_lines: Vec<usize> = ref_result
|
||||
.locations
|
||||
.iter()
|
||||
.filter(|loc| loc.line == 10 || loc.line == 17 || loc.line == 25)
|
||||
.map(|loc| loc.line)
|
||||
.collect();
|
||||
|
||||
assert!(
|
||||
dep_array_lines.contains(&10),
|
||||
"fileTree should be referenced on line 10 (first dependency array)"
|
||||
);
|
||||
assert!(
|
||||
dep_array_lines.contains(&17),
|
||||
"fileTree should be referenced on line 17 (second dependency array)"
|
||||
);
|
||||
assert!(
|
||||
dep_array_lines.contains(&25),
|
||||
"fileTree should be referenced on line 25 (third dependency array)"
|
||||
);
|
||||
|
||||
// Test that 'loadDirectory' is found in dependency arrays
|
||||
let ref_result2 =
|
||||
navigator.goto_references_by_name("loadDirectory", Some(&file_path), false);
|
||||
assert!(
|
||||
!ref_result2.locations.is_empty(),
|
||||
"loadDirectory should have references"
|
||||
);
|
||||
|
||||
// Line 17: [loadDirectory, fileTree]
|
||||
// Line 30: [basePath, loadDirectory]
|
||||
let load_dir_refs: Vec<usize> = ref_result2
|
||||
.locations
|
||||
.iter()
|
||||
.filter(|loc| loc.line == 17 || loc.line == 30)
|
||||
.map(|loc| loc.line)
|
||||
.collect();
|
||||
|
||||
assert!(
|
||||
load_dir_refs.contains(&17),
|
||||
"loadDirectory should be referenced on line 17"
|
||||
);
|
||||
assert!(
|
||||
load_dir_refs.contains(&30),
|
||||
"loadDirectory should be referenced on line 30"
|
||||
);
|
||||
|
||||
// Test that 'onFileSelect' is found in dependency array
|
||||
let ref_result3 =
|
||||
navigator.goto_references_by_name("onFileSelect", Some(&file_path), false);
|
||||
assert!(
|
||||
!ref_result3.locations.is_empty(),
|
||||
"onFileSelect should have references"
|
||||
);
|
||||
let on_file_select_line25 = ref_result3.locations.iter().any(|loc| loc.line == 25);
|
||||
assert!(
|
||||
on_file_select_line25,
|
||||
"onFileSelect should be referenced on line 25 (dependency array)"
|
||||
);
|
||||
|
||||
// Test that 'basePath' is found in dependency array
|
||||
let ref_result4 = navigator.goto_references_by_name("basePath", Some(&file_path), false);
|
||||
assert!(
|
||||
!ref_result4.locations.is_empty(),
|
||||
"basePath should have references"
|
||||
);
|
||||
let base_path_line30 = ref_result4.locations.iter().any(|loc| loc.line == 30);
|
||||
assert!(
|
||||
base_path_line30,
|
||||
"basePath should be referenced on line 30 (useEffect dependency array)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Edge types for the ScopeGraph.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Describes the relation between two nodes in the ScopeGraph.
|
||||
#[derive(Serialize, Deserialize, PartialEq, Eq, Copy, Clone, Debug)]
|
||||
pub enum EdgeKind {
|
||||
/// The edge weight from a nested scope to its parent scope.
|
||||
ScopeToScope,
|
||||
|
||||
/// The edge weight from a definition to its definition scope.
|
||||
DefToScope,
|
||||
|
||||
/// The edge weight from an import to its definition scope.
|
||||
ImportToScope,
|
||||
|
||||
/// The edge weight from a reference to its definition.
|
||||
RefToDef,
|
||||
|
||||
/// The edge weight from a reference to its import.
|
||||
RefToImport,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
//! ScopeGraph module for per-file symbol tracking.
|
||||
//!
|
||||
//! A ScopeGraph represents the symbols (definitions, references, imports) and their
|
||||
//! relationships within a single source file.
|
||||
|
||||
pub mod edges;
|
||||
pub mod graph;
|
||||
pub mod nodes;
|
||||
|
||||
pub use edges::EdgeKind;
|
||||
pub use graph::{
|
||||
NodeIndex, QueryVersion, ScopeGraph, ScopeGraphIndex, ScopeStack, Snippet,
|
||||
extract_symbols_fast, scope_graph_from_definitions_query,
|
||||
};
|
||||
pub use nodes::{LocalDef, LocalImport, LocalScope, NodeKind, Reference, Symbol, SymbolId};
|
||||
|
||||
use crate::languages::TSLanguageConfig;
|
||||
|
||||
/// Result of building a scope graph, including alias pairs.
|
||||
pub struct ScopeGraphResult {
|
||||
/// The scope graph for the file.
|
||||
pub graph: ScopeGraph,
|
||||
/// Alias pairs: (alias_name, original_name).
|
||||
pub aliases: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Build a ScopeGraph from tree-sitter query and source.
|
||||
///
|
||||
/// This is a convenience wrapper around `scope_graph_from_definitions_query`.
|
||||
pub fn build_scope_graph(
|
||||
query: &tree_sitter::Query,
|
||||
root_node: tree_sitter::Node<'_>,
|
||||
src: &[u8],
|
||||
language: &TSLanguageConfig,
|
||||
) -> ScopeGraphResult {
|
||||
let (graph, aliases) = scope_graph_from_definitions_query(query, root_node, src, language);
|
||||
ScopeGraphResult { graph, aliases }
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Node types for the ScopeGraph.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::types::Range;
|
||||
|
||||
/// A symbol extracted from the code.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Symbol {
|
||||
/// The kind/type of symbol (e.g., "function", "class", etc.)
|
||||
pub kind: Arc<str>,
|
||||
/// The range where the symbol appears.
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl Symbol {
|
||||
/// Create a new symbol.
|
||||
pub fn new(kind: Arc<str>, range: Range) -> Self {
|
||||
Self { kind, range }
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque identifier for every symbol in a language.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct SymbolId {
|
||||
/// Index into the namespace array.
|
||||
pub namespace_idx: usize,
|
||||
/// Index within the namespace.
|
||||
pub symbol_idx: usize,
|
||||
}
|
||||
|
||||
impl SymbolId {
|
||||
/// Create a new symbol ID.
|
||||
pub fn new(namespace_idx: usize, symbol_idx: usize) -> Self {
|
||||
Self {
|
||||
namespace_idx,
|
||||
symbol_idx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the symbol name from the namespaces.
|
||||
pub fn name<'a>(&self, namespaces: &'a [Vec<String>]) -> Option<&'a str> {
|
||||
namespaces
|
||||
.get(self.namespace_idx)
|
||||
.and_then(|ns| ns.get(self.symbol_idx))
|
||||
.map(|s| s.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// A local scope in the source code.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash, Eq)]
|
||||
pub struct LocalScope {
|
||||
/// The range of this scope.
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl LocalScope {
|
||||
/// Create a new local scope.
|
||||
pub fn new(range: Range) -> Self {
|
||||
Self { range }
|
||||
}
|
||||
}
|
||||
|
||||
/// A local definition in the source code.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct LocalDef {
|
||||
/// The range of the identifier being defined.
|
||||
pub range: Range,
|
||||
/// Optional symbol ID for type-aware resolution.
|
||||
pub symbol_id: Option<SymbolId>,
|
||||
/// The scope where this definition is visible.
|
||||
pub scope: LocalScope,
|
||||
}
|
||||
|
||||
impl LocalDef {
|
||||
/// Create a new local definition.
|
||||
pub fn new(range: Range, symbol_id: Option<SymbolId>, scope: LocalScope) -> Self {
|
||||
Self {
|
||||
range,
|
||||
symbol_id,
|
||||
scope,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the name of this definition from source bytes.
|
||||
pub fn name<'a>(&self, src: &'a [u8]) -> &'a [u8] {
|
||||
&src[self.range.start_byte()..self.range.end_byte()]
|
||||
}
|
||||
|
||||
/// Get the scope range.
|
||||
pub fn scope_range(&self) -> &Range {
|
||||
&self.scope.range
|
||||
}
|
||||
}
|
||||
|
||||
/// A local import in the source code.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct LocalImport {
|
||||
/// The range of the import identifier.
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl LocalImport {
|
||||
/// Create a new local import.
|
||||
pub fn new(range: Range) -> Self {
|
||||
Self { range }
|
||||
}
|
||||
|
||||
/// Get the name of this import from source bytes.
|
||||
pub fn name<'a>(&self, src: &'a [u8]) -> &'a [u8] {
|
||||
&src[self.range.start_byte()..self.range.end_byte()]
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference to a symbol in the source code.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Reference {
|
||||
/// The range of the reference.
|
||||
pub range: Range,
|
||||
/// Optional symbol ID for type-aware resolution.
|
||||
pub symbol_id: Option<SymbolId>,
|
||||
}
|
||||
|
||||
impl Reference {
|
||||
/// Create a new reference.
|
||||
pub fn new(range: Range, symbol_id: Option<SymbolId>) -> Self {
|
||||
Self { range, symbol_id }
|
||||
}
|
||||
|
||||
/// Get the name of this reference from source bytes.
|
||||
pub fn name<'a>(&self, src: &'a [u8]) -> &'a [u8] {
|
||||
&src[self.range.start_byte()..self.range.end_byte()]
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of a node in the ScopeGraph.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub enum NodeKind {
|
||||
/// A scope node.
|
||||
Scope(LocalScope),
|
||||
|
||||
/// A definition node.
|
||||
Def(LocalDef),
|
||||
|
||||
/// An import node.
|
||||
Import(LocalImport),
|
||||
|
||||
/// A reference node.
|
||||
Ref(Reference),
|
||||
}
|
||||
|
||||
impl NodeKind {
|
||||
/// Construct a scope node from a range.
|
||||
pub fn scope(range: Range) -> Self {
|
||||
Self::Scope(LocalScope::new(range))
|
||||
}
|
||||
|
||||
/// Produce the range spanned by this node.
|
||||
pub fn range(&self) -> Range {
|
||||
match self {
|
||||
Self::Scope(l) => l.range,
|
||||
// For definitions, return the scope range to capture the full context
|
||||
Self::Def(d) => d.scope.range,
|
||||
Self::Ref(r) => r.range,
|
||||
Self::Import(i) => i.range,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the identifier range (the actual symbol location).
|
||||
pub fn identifier_range(&self) -> Range {
|
||||
match self {
|
||||
Self::Scope(l) => l.range,
|
||||
Self::Def(d) => d.range,
|
||||
Self::Ref(r) => r.range,
|
||||
Self::Import(i) => i.range,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! File change events for live index updates.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Events that can trigger index updates.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FileEvent {
|
||||
/// A new file was created.
|
||||
Created {
|
||||
/// Path to the new file.
|
||||
path: PathBuf,
|
||||
},
|
||||
|
||||
/// An existing file was modified.
|
||||
Modified {
|
||||
/// Path to the modified file.
|
||||
path: PathBuf,
|
||||
},
|
||||
|
||||
/// A file was deleted.
|
||||
Deleted {
|
||||
/// Path to the deleted file.
|
||||
path: PathBuf,
|
||||
},
|
||||
|
||||
/// A file was renamed/moved.
|
||||
Renamed {
|
||||
/// Original path.
|
||||
from: PathBuf,
|
||||
/// New path.
|
||||
to: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
impl FileEvent {
|
||||
/// Get the primary path associated with this event.
|
||||
pub fn path(&self) -> &PathBuf {
|
||||
match self {
|
||||
FileEvent::Created { path } => path,
|
||||
FileEvent::Modified { path } => path,
|
||||
FileEvent::Deleted { path } => path,
|
||||
FileEvent::Renamed { to, .. } => to,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if this event requires reparsing the file content.
|
||||
pub fn requires_reparse(&self) -> bool {
|
||||
match self {
|
||||
FileEvent::Created { .. } => true,
|
||||
FileEvent::Modified { .. } => true,
|
||||
FileEvent::Deleted { .. } => false,
|
||||
FileEvent::Renamed { .. } => false, // Only path update needed
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if this event affects an existing indexed file.
|
||||
pub fn affects_existing(&self) -> bool {
|
||||
match self {
|
||||
FileEvent::Created { .. } => false,
|
||||
FileEvent::Modified { .. } => true,
|
||||
FileEvent::Deleted { .. } => true,
|
||||
FileEvent::Renamed { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FileEvent {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FileEvent::Created { path } => write!(f, "Created: {}", path.display()),
|
||||
FileEvent::Modified { path } => write!(f, "Modified: {}", path.display()),
|
||||
FileEvent::Deleted { path } => write!(f, "Deleted: {}", path.display()),
|
||||
FileEvent::Renamed { from, to } => {
|
||||
write!(f, "Renamed: {} -> {}", from.display(), to.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Location type for query results.
|
||||
//!
|
||||
//! Location uses 1-indexed line and column numbers for LSP compatibility.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Range;
|
||||
|
||||
/// A location in the codebase, used for query results.
|
||||
///
|
||||
/// Following LSP protocol conventions:
|
||||
/// - `file_path`: Absolute path to the file
|
||||
/// - `line`: 1-indexed line number
|
||||
/// - `column`: 1-indexed column number
|
||||
/// - `range`: Full range information (0-indexed internally)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Location {
|
||||
/// File path (absolute)
|
||||
pub file_path: PathBuf,
|
||||
/// Line number (1-indexed)
|
||||
pub line: usize,
|
||||
/// Column number (1-indexed)
|
||||
pub column: usize,
|
||||
/// Full range information (0-indexed internally)
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl Location {
|
||||
/// Create a new location with 1-indexed line and column.
|
||||
pub fn new(file_path: PathBuf, line: usize, column: usize, range: Range) -> Self {
|
||||
Self {
|
||||
file_path,
|
||||
line,
|
||||
column,
|
||||
range,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a location from a range (automatically converts to 1-indexed).
|
||||
pub fn from_range(file_path: PathBuf, range: Range) -> Self {
|
||||
Self {
|
||||
file_path,
|
||||
line: range.start_line_1indexed(),
|
||||
column: range.start_column_1indexed(),
|
||||
range,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the file path.
|
||||
pub fn file_path(&self) -> &PathBuf {
|
||||
&self.file_path
|
||||
}
|
||||
|
||||
/// Alias for file_path() - for compatibility.
|
||||
pub fn path(&self) -> &PathBuf {
|
||||
&self.file_path
|
||||
}
|
||||
|
||||
/// Get the 1-indexed line number.
|
||||
pub fn line(&self) -> usize {
|
||||
self.line
|
||||
}
|
||||
|
||||
/// Get the 1-indexed column number.
|
||||
pub fn column(&self) -> usize {
|
||||
self.column
|
||||
}
|
||||
|
||||
/// Get the range (0-indexed internally).
|
||||
pub fn range(&self) -> &Range {
|
||||
&self.range
|
||||
}
|
||||
|
||||
/// Get the file extension, if any.
|
||||
pub fn extension(&self) -> Option<&str> {
|
||||
self.file_path.extension().and_then(|e| e.to_str())
|
||||
}
|
||||
|
||||
/// Get the parent directory of the file.
|
||||
pub fn parent_dir(&self) -> Option<&std::path::Path> {
|
||||
self.file_path.parent()
|
||||
}
|
||||
|
||||
/// Get the 0-indexed line number (for internal use).
|
||||
pub fn line_0indexed(&self) -> usize {
|
||||
self.line.saturating_sub(1)
|
||||
}
|
||||
|
||||
/// Get the 0-indexed column number (for internal use).
|
||||
pub fn column_0indexed(&self) -> usize {
|
||||
self.column.saturating_sub(1)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Location {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}:{}:{}",
|
||||
self.file_path.display(),
|
||||
self.line,
|
||||
self.column
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Core types for the goto_index crate.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
mod file_event;
|
||||
mod location;
|
||||
mod range;
|
||||
|
||||
pub use file_event::FileEvent;
|
||||
pub use location::Location;
|
||||
pub use range::{Position, Range};
|
||||
|
||||
/// Statistics about an index.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct IndexStats {
|
||||
/// Number of files indexed
|
||||
pub files: usize,
|
||||
/// Number of symbol definitions
|
||||
pub definitions: usize,
|
||||
/// Number of symbol references
|
||||
pub references: usize,
|
||||
}
|
||||
|
||||
impl IndexStats {
|
||||
/// Create new index stats.
|
||||
pub fn new(files: usize, definitions: usize, references: usize) -> Self {
|
||||
Self {
|
||||
files,
|
||||
definitions,
|
||||
references,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol with its line number (1-indexed).
|
||||
/// Uses Arc<str> to avoid extra allocation when merging into index.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SymbolOccurrence {
|
||||
/// The symbol name
|
||||
pub name: Arc<str>,
|
||||
/// Line number (1-indexed)
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
impl SymbolOccurrence {
|
||||
/// Create a new symbol occurrence.
|
||||
pub fn new(name: Arc<str>, line: usize) -> Self {
|
||||
Self { name, line }
|
||||
}
|
||||
}
|
||||
|
||||
/// An alias mapping (alias_name -> original_name).
|
||||
/// Uses Arc<str> to avoid extra allocation when merging into index.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SymbolAlias {
|
||||
/// The alias name (e.g., imported as)
|
||||
pub alias: Arc<str>,
|
||||
/// The original symbol name
|
||||
pub original: Arc<str>,
|
||||
}
|
||||
|
||||
impl SymbolAlias {
|
||||
/// Create a new symbol alias.
|
||||
pub fn new(alias: Arc<str>, original: Arc<str>) -> Self {
|
||||
Self { alias, original }
|
||||
}
|
||||
}
|
||||
|
||||
/// File metadata for staleness detection.
|
||||
///
|
||||
/// Stores size and modification time to quickly detect if a file has changed
|
||||
/// without reading its contents.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FileMeta {
|
||||
/// File size in bytes
|
||||
pub size: u64,
|
||||
/// Modification time as seconds since UNIX epoch
|
||||
pub mtime_secs: i64,
|
||||
/// Modification time nanoseconds component
|
||||
pub mtime_nanos: u32,
|
||||
}
|
||||
|
||||
impl FileMeta {
|
||||
/// Create new file metadata.
|
||||
pub fn new(size: u64, mtime_secs: i64, mtime_nanos: u32) -> Self {
|
||||
Self {
|
||||
size,
|
||||
mtime_secs,
|
||||
mtime_nanos,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create file metadata from std::fs::Metadata.
|
||||
pub fn from_metadata(meta: &std::fs::Metadata) -> Self {
|
||||
let size = meta.len();
|
||||
let (mtime_secs, mtime_nanos) = meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| (d.as_secs() as i64, d.subsec_nanos()))
|
||||
.unwrap_or((0, 0));
|
||||
Self {
|
||||
size,
|
||||
mtime_secs,
|
||||
mtime_nanos,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the file has changed compared to current filesystem state.
|
||||
pub fn is_stale(&self, path: &std::path::Path) -> bool {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) => {
|
||||
let current = Self::from_metadata(&meta);
|
||||
*self != current
|
||||
}
|
||||
Err(_) => true, // File deleted or inaccessible
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user