Compare commits

..

8 Commits

Author SHA1 Message Date
Yeachan-Heo
fa81684707 docs: replace WSJ README section with related projects cards
Replace the Wall Street Journal feature block in the README with a Related Projects section that points readers to the surrounding harness-engineering tooling. Keep the project cards focused on OmX, OmC, clawhip, and OmO, and tighten the surrounding copy for clarity.\n\nConstraint: This follow-up is README-only and must not include unrelated workspace edits\nRejected: Restore the WSJ feature section | owner requested it remain removed\nRejected: Expand the section into a longer narrative | weaker scannability than concise project cards\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: Keep this section concise and ecosystem-oriented; avoid reintroducing unrelated press/profile copy here\nTested: Manual README diff review\nNot-tested: Rendered GitHub markdown preview
2026-04-02 00:06:06 +00:00
Yeachan-Heo
b8d78c9a53 feat: add honest plugin inspection reporting
Shift the Rust parity increment away from implying TS-style plugin UX and toward an honest inspection surface. /plugin now reports current local plugin support, checked directories, and missing runtime wiring, while /reload-plugins rebuilds the runtime and prints the same inspection snapshot.\n\nConstraint: Rust only supports local manifest-backed plugins today; marketplace/discovery parity does not exist\nRejected: Stub marketplace installer flow | would overstate current capability\nRejected: Keep /plugin as list-only output | hides important gaps and checked paths\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: Keep plugin reporting aligned with actual runtime wiring; do not advertise manifest commands/hooks as active until the runtime uses them\nTested: cargo test -p commands\nTested: cargo test -p claw-cli\nNot-tested: cargo clippy -p commands -p claw-cli --tests -- -D warnings (blocked by pre-existing workspace warnings in commands/claw-cli/lsp)
2026-04-02 00:04:23 +00:00
Yeachan-Heo
a2f22b1ece feat: add hooks inspection report
This adds a narrow, shippable /hooks surface that reports the merged\nPreToolUse and PostToolUse shell hook configuration from the Rust\nruntime. The CLI now exposes hooks consistently in direct, REPL, and\nresume-safe slash-command flows, with focused tests covering parsing,\nhelp text, and report rendering.\n\nConstraint: Keep the increment inspection-only instead of introducing a broader TS-style hook model\nRejected: Build matcher-based or interactive hook editing now | too broad for the next parity slice\nConfidence: high\nScope-risk: narrow\nReversibility: clean\nDirective: Extend /hooks from the runtime's current string-list model unless config parsing grows first\nTested: cargo fmt --all; cargo test -p commands; cargo test -p claw-cli; cargo test --workspace\nNot-tested: cargo clippy --workspace --all-targets -- -D warnings (blocked by unrelated existing lsp warnings in rust/crates/lsp/src/client.rs and rust/crates/lsp/src/lib.rs)
2026-04-01 23:47:18 +00:00
Yeachan-Heo
05bcf6751b docs: add crypto affiliation disclaimer 2026-04-01 23:41:05 +00:00
Yeachan-Heo
fdd06e814b feat(rust): surface workspace skill discovery in /skills
The TypeScript CLI exposes a skills browser backed by workspace/user skill
discovery, while the Rust port only had partial local loading and an
inconsistent slash-command view. This change adds a shared runtime skill
discovery path, teaches the Skill tool to resolve workspace `.codex/.claw`
skills plus legacy `/commands`, and makes `/skills` report the checked local
skill directories in the current workspace context.

Constraint: Keep scope limited to local/workspace skill discovery without inventing bundled or remote registries yet
Rejected: Add a bundled skill registry surface now | too broad for this parity increment
Rejected: Leave tool resolution and /skills discovery separate | misleading output and weaker parity with TS
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: Extend the shared runtime skill discovery path before adding new skill sources so the tool surface and /skills stay aligned
Tested: cargo fmt --all; cargo test -p runtime skills:: -- --nocapture; cargo test -p commands skills -- --nocapture; cargo test -p tools skill_ -- --nocapture; cargo test -p claw-cli skills -- --nocapture; cargo test -p claw-cli init_help_mentions_direct_subcommand -- --nocapture
Not-tested: Full workspace-wide cargo test sweep
2026-04-01 23:34:38 +00:00
Yeachan-Heo
8599bac67b docs(readme): add philosophy section
Add the owner-requested Philosophy section near the top of the README and tighten the wording once for clarity so the repo frames the orchestration workflow, not just the generated artifacts.

Constraint: Keep this commit limited to README copy and exclude session noise or code changes
Rejected: Split the section into multiple commits | the requested work is a single cohesive README update
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep future README philosophy edits aligned with the repository's emphasis on agent coordination as the primary subject
Tested: Manual review of staged README.md diff
Not-tested: N/A
2026-04-01 23:21:05 +00:00
Yeachan-Heo
06ee5a2dc4 test(parity): lock clean JSON prompt transport output
PARITY.md still claimed tool-capable JSON prompt runs leaked human-readable tool result lines, but a local mock SSE reproduction showed stdout already stays transport-clean. Add a real CLI regression test around the binary prompt path and update the parity note so future work does not chase a stale bug report.

Constraint: Keep scope limited to JSON prompt parity and leave the existing README Philosophy edits untouched
Rejected: Modify claw-cli transport code | current behavior already verified clean via a mock SSE prompt run
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep prompt JSON stdout parseable as a single transport object even when tool loops fire
Tested: cargo test -p claw-cli prompt_json_with_tool_use_writes_clean_transport_output --test prompt_json_transport -- --nocapture
Tested: cargo test -p claw-cli parses_bare_prompt_and_json_output_flag -- --nocapture
Tested: cargo test -p claw-cli response_to_events_preserves_empty_object_json_input_outside_streaming -- --nocapture
Not-tested: Live provider behavior outside the local mock SSE harness
2026-04-01 23:15:15 +00:00
Yeachan-Heo
bcaf6e0771 Bring slash-command UX closer to the TypeScript terminal UI
Port the Rust REPL toward the TypeScript UI patterns by adding ranked slash
command suggestions, canonical alias completion, trailing-space acceptance,
argument hints, and clearer entry/help copy for discoverability.

Constraint: Keep this worktree scoped to UI-only parity; discard unrelated plugin-loading edits
Constraint: Rust terminal UI remains line-editor based, so the parity pass focuses on practical affordances instead of React modal surfaces
Rejected: Rework the REPL into a full multi-pane typeahead overlay | too large for this UI-only parity slice
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep slash metadata and completion behavior aligned; new slash commands should update both descriptors and help text together
Tested: cargo check; cargo test
Not-tested: Interactive manual terminal pass in a live TTY
2026-04-01 21:57:13 +00:00
10 changed files with 1719 additions and 1335 deletions

View File

@@ -59,15 +59,18 @@ Evidence:
### Rust exists ### Rust exists
Evidence: Evidence:
- Hook config is parsed and merged in `rust/crates/runtime/src/config.rs`. - Hook config is parsed and merged in `rust/crates/runtime/src/config.rs`.
- Hook config can be inspected via Rust config reporting in `rust/crates/commands/src/lib.rs` and `rust/crates/claw-cli/src/main.rs`. - Shell-command `PreToolUse` / `PostToolUse` hooks execute via `rust/crates/runtime/src/hooks.rs`.
- Conversation runtime runs pre/post hooks around tool execution in `rust/crates/runtime/src/conversation.rs`.
- Hook config can now be inspected through a dedicated Rust `/hooks` report in `rust/crates/commands/src/lib.rs` and `rust/crates/claw-cli/src/main.rs`.
- Prompt guidance mentions hooks in `rust/crates/runtime/src/prompt.rs`. - Prompt guidance mentions hooks in `rust/crates/runtime/src/prompt.rs`.
### Missing or broken in Rust ### Missing or broken in Rust
- No actual hook execution pipeline in `rust/crates/runtime/src/conversation.rs`. - No TS-style matcher-based hook config model; Rust only supports merged string command lists under `settings.hooks.PreToolUse` and `PostToolUse`.
- No PreToolUse/PostToolUse mutation/deny/rewrite/result-hook behavior. - No TS-style prompt/agent/http hook types, `PostToolUseFailure`, `PermissionDenied`, or richer hook lifecycle surfaces.
- No Rust `/hooks` parity command. - No TS-equivalent interactive `/hooks` browser/editor; Rust currently provides inspection/reporting only.
- No PreToolUse/PostToolUse input rewrite, MCP-output mutation, or continuation-stop behavior beyond allow/deny plus feedback text.
**Status:** config-only; runtime behavior missing. **Status:** basic shell hook runtime plus `/hooks` inspection; richer TS hook model still missing.
--- ---
@@ -81,16 +84,19 @@ Evidence:
### Rust exists ### Rust exists
Evidence: Evidence:
- No dedicated plugin subsystem appears under `rust/crates/`. - Local plugin manifests, registry/state, install/update/uninstall flows, and bundled/external discovery live in `rust/crates/plugins/src/lib.rs`.
- Repo-wide Rust references to plugins are effectively absent beyond text/help mentions. - Runtime config parses plugin settings (`enabledPlugins`, external directories, install root, registry path, bundled root) in `rust/crates/runtime/src/config.rs`.
- CLI wiring builds a `PluginManager`, exposes `/plugin` inspection/reporting, and now exposes `/reload-plugins` runtime rebuild/reporting in `rust/crates/commands/src/lib.rs` and `rust/crates/claw-cli/src/main.rs`.
- Plugin-provided tools are merged into the runtime tool registry in `rust/crates/claw-cli/src/main.rs` and `rust/crates/tools/src/lib.rs`.
### Missing or broken in Rust ### Missing or broken in Rust
- No plugin loader. - No TS-style marketplace/discovery/editor UI; current surfaces are local manifest/reporting oriented.
- No marketplace install/update/enable/disable flow. - Plugin-defined slash commands are validated from manifests but not exposed in the CLI runtime.
- No `/plugin` or `/reload-plugins` parity. - Plugin hooks and lifecycle commands are validated but not wired into the conversation runtime startup/shutdown or hook runner.
- No plugin-provided hook/tool/command/MCP extension path. - No plugin-provided MCP/server extension path.
- `/reload-plugins` only rebuilds the current local runtime; it is not a richer TS hot-reload/plugin-browser flow.
**Status:** missing. **Status:** local plugin discovery/install/inspection exists; TS marketplace/runtime-extension parity is still partial.
--- ---
@@ -104,18 +110,18 @@ Evidence:
### Rust exists ### Rust exists
Evidence: Evidence:
- `Skill` tool in `rust/crates/tools/src/lib.rs` resolves and reads local `SKILL.md` files. - `Skill` tool in `rust/crates/tools/src/lib.rs` now resolves workspace-local `.codex/.claw` skills plus legacy `/commands` entries through shared runtime discovery.
- `/skills` exists in `rust/crates/commands/src/lib.rs` and `rust/crates/claw-cli/src/main.rs`, listing discoverable local skills and checked skill directories in the current workspace context.
- CLAW.md discovery is implemented in `rust/crates/runtime/src/prompt.rs`. - CLAW.md discovery is implemented in `rust/crates/runtime/src/prompt.rs`.
- Rust supports `/memory` and `/init` via `rust/crates/commands/src/lib.rs` and `rust/crates/claw-cli/src/main.rs`. - Rust supports `/memory` and `/init` via `rust/crates/commands/src/lib.rs` and `rust/crates/claw-cli/src/main.rs`.
### Missing or broken in Rust ### Missing or broken in Rust
- No bundled skill registry equivalent. - No bundled skill registry equivalent.
- No `/skills` command.
- No MCP skill-builder pipeline. - No MCP skill-builder pipeline.
- No TS-style live skill discovery/reload/change handling. - No TS-style live skill discovery/reload/change handling.
- No comparable session-memory / team-memory integration around skills. - No comparable session-memory / team-memory integration around skills.
**Status:** basic local skill loading only. **Status:** local/workspace skill loading plus minimal `/skills` discovery; bundled/MCP parity still missing.
--- ---
@@ -130,14 +136,14 @@ Evidence:
### Rust exists ### Rust exists
Evidence: Evidence:
- Shared slash command registry in `rust/crates/commands/src/lib.rs`. - Shared slash command registry in `rust/crates/commands/src/lib.rs`.
- Rust slash commands currently cover `help`, `status`, `compact`, `model`, `permissions`, `clear`, `cost`, `resume`, `config`, `memory`, `init`, `diff`, `version`, `export`, `session`. - Rust slash commands currently cover `help`, `status`, `compact`, `model`, `permissions`, `clear`, `cost`, `resume`, `config`, `hooks`, `memory`, `init`, `diff`, `version`, `export`, `session`, `plugin`, `reload-plugins`, `agents`, and `skills`.
- Main CLI/repl/prompt handling lives in `rust/crates/claw-cli/src/main.rs`. - Main CLI/repl/prompt handling lives in `rust/crates/claw-cli/src/main.rs`.
### Missing or broken in Rust ### Missing or broken in Rust
- Missing major TS command families: `/agents`, `/hooks`, `/mcp`, `/plugin`, `/skills`, `/plan`, `/review`, `/tasks`, and many others. - Missing major TS command families: `/hooks`, `/mcp`, `/plan`, `/review`, `/tasks`, and many others.
- No Rust equivalent to TS structured IO / remote transport layers. - No Rust equivalent to TS structured IO / remote transport layers.
- No TS-style handler decomposition for auth/plugins/MCP/agents. - No TS-style handler decomposition for auth/plugins/MCP/agents.
- JSON prompt mode is improved on this branch, but still not clean transport parity: empirical verification shows tool-capable JSON output can emit human-readable tool-result lines before the final JSON object. - JSON prompt mode now maintains clean transport output in tool-capable runs; targeted CLI coverage should guard against regressions.
**Status:** functional local CLI core, much narrower than TS. **Status:** functional local CLI core, much narrower than TS.
@@ -161,7 +167,7 @@ Evidence:
- No TS-style hook-aware orchestration layer. - No TS-style hook-aware orchestration layer.
- No TS structured/remote assistant transport stack. - No TS structured/remote assistant transport stack.
- No richer TS assistant/session-history/background-task integration. - No richer TS assistant/session-history/background-task integration.
- JSON output path is no longer single-turn only on this branch, but output cleanliness still lags TS transport expectations. - JSON output path is no longer single-turn only on this branch, and tool-capable prompt output now stays transport-clean like the TypeScript behavior.
**Status:** strong core loop, missing orchestration layers. **Status:** strong core loop, missing orchestration layers.
@@ -209,6 +215,6 @@ Evidence:
- **Unlimited max_iterations** - **Unlimited max_iterations**
- Verified at `rust/crates/runtime/src/conversation.rs` with `usize::MAX`. - Verified at `rust/crates/runtime/src/conversation.rs` with `usize::MAX`.
### Remaining notable parity issue ### JSON prompt output cleanliness status
- **JSON prompt output cleanliness** - **JSON prompt output cleanliness**
- Tool-capable JSON mode now loops, but empirical verification still shows pre-JSON human-readable tool-result output when tools fire. - Verified clean in tool-capable prompt mode: stdout remains a single final JSON object when tools fire.

View File

@@ -26,6 +26,27 @@
<a href="https://github.com/sponsors/instructkr"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink?logo=github&style=for-the-badge" alt="Sponsor on GitHub" /></a> <a href="https://github.com/sponsors/instructkr"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink?logo=github&style=for-the-badge" alt="Sponsor on GitHub" /></a>
</p> </p>
## Philosophy
If you are staring at the generated files, you are looking at the wrong layer.
The Python rewrite was a byproduct, and the Rust port is too. The real subject of this repository is the **agent coordination system** that made both possible: a human giving direction in Discord, agents decomposing the work, implementing in parallel, reviewing each other, fixing failures, and shipping without constant babysitting.
That is the point of this project.
- **the code is evidence, not the product**
- **the system that produces the code is the thing worth studying**
- **architectural clarity, task decomposition, and coordination matter more than typing speed**
- **clean-room rebuilding is valuable because it exposes process, not because it preserves an archive**
- **the future of software work is better agent orchestration, not more manual pane babysitting**
This repository exists to document and improve that loop: direction from the human, execution by the agents, notifications routed outside the context window, and repeated verification until the result is good enough to ship.
In other words: **stop staring at the files**. Study the workflow that produced them.
> [!IMPORTANT]
> **This repository is not affiliated with any coin, token, NFT, or crypto project.** It is software infrastructure work only, and any attempt to frame it as a cryptocurrency project is incorrect.
> [!IMPORTANT] > [!IMPORTANT]
> **Rust port is now in progress** on the [`dev/rust`](https://github.com/instructkr/claw-code/tree/dev/rust) branch and is expected to be merged into main today. The Rust implementation aims to deliver a faster, memory-safe harness runtime. Stay tuned — this will be the definitive version of the project. > **Rust port is now in progress** on the [`dev/rust`](https://github.com/instructkr/claw-code/tree/dev/rust) branch and is expected to be merged into main today. The Rust implementation aims to deliver a faster, memory-safe harness runtime. Stay tuned — this will be the definitive version of the project.
@@ -68,21 +89,33 @@ https://github.com/instructkr/claw-code
![Tweet screenshot](assets/tweet-screenshot.png) ![Tweet screenshot](assets/tweet-screenshot.png)
## The Creators Featured in Wall Street Journal For Avid Claw Code Fans ## Related Projects
I've been deeply interested in **harness engineering** — studying how agent systems wire tools, orchestrate tasks, and manage runtime context. This isn't a sudden thing. The Wall Street Journal featured my work earlier this month, documenting how I've been one of the most active power users exploring these systems: This repository sits inside a broader harness-engineering stack. If you want the surrounding tooling rather than only this port, start here:
> AI startup worker Sigrid Jin, who attended the Seoul dinner, single-handedly used 25 billion of Claw Code tokens last year. At the time, usage limits were looser, allowing early enthusiasts to reach tens of billions of tokens at a very low cost. ### oh-my-codex (OmX)
>
> Despite his countless hours with Claw Code, Jin isn't faithful to any one AI lab. The tools available have different strengths and weaknesses, he said. Codex is better at reasoning, while Claw Code generates cleaner, more shareable code.
>
> Jin flew to San Francisco in February for Claw Code's first birthday party, where attendees waited in line to compare notes with Cherny. The crowd included a practicing cardiologist from Belgium who had built an app to help patients navigate care, and a California lawyer who made a tool for automating building permit approvals using Claw Code.
>
> "It was basically like a sharing party," Jin said. "There were lawyers, there were doctors, there were dentists. They did not have software engineering backgrounds."
>
> — *The Wall Street Journal*, March 21, 2026, [*"The Trillion Dollar Race to Automate Our Entire Lives"*](https://lnkd.in/gs9td3qd)
![WSJ Feature](assets/wsj-feature.png) [![oh-my-codex](https://opengraph.githubassets.com/1/Yeachan-Heo/oh-my-codex)](https://github.com/Yeachan-Heo/oh-my-codex)
Primary orchestration layer for planning, delegation, verification loops, and long-running execution patterns such as `$team` and `$ralph`.
### oh-my-claudecode (OmC)
[![oh-my-claudecode](https://opengraph.githubassets.com/1/Yeachan-Heo/oh-my-claudecode)](https://github.com/Yeachan-Heo/oh-my-claudecode)
Companion workflow layer for Claude Code-centered orchestration and multi-agent terminal workflows.
### clawhip
[![clawhip](https://opengraph.githubassets.com/1/Yeachan-Heo/clawhip)](https://github.com/Yeachan-Heo/clawhip)
Event-to-channel routing for commits, PRs, issues, tmux sessions, and agent lifecycle updates — keeping monitoring traffic out of the active agent context window.
### oh-my-opencode (OmO)
[![oh-my-opencode](https://opengraph.githubassets.com/1/code-yeongyu/oh-my-openagent)](https://github.com/code-yeongyu/oh-my-openagent)
Used here for later-pass implementation acceleration and verification support alongside OmX.
--- ---

View File

@@ -6,6 +6,31 @@ use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifier
use crossterm::queue; use crossterm::queue;
use crossterm::terminal::{self, Clear, ClearType}; use crossterm::terminal::{self, Clear, ClearType};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlashCommandDescriptor {
pub command: String,
pub description: Option<String>,
pub argument_hint: Option<String>,
pub aliases: Vec<String>,
}
impl SlashCommandDescriptor {
#[allow(dead_code)]
#[must_use]
pub fn simple(command: impl Into<String>) -> Self {
Self {
command: command.into(),
description: None,
argument_hint: None,
aliases: Vec::new(),
}
}
fn triggers(&self) -> impl Iterator<Item = &str> {
std::iter::once(self.command.as_str()).chain(self.aliases.iter().map(String::as_str))
}
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadOutcome { pub enum ReadOutcome {
Submit(String), Submit(String),
@@ -178,14 +203,21 @@ impl EditSession {
out: &mut impl Write, out: &mut impl Write,
base_prompt: &str, base_prompt: &str,
vim_enabled: bool, vim_enabled: bool,
assist_lines: &[String],
) -> io::Result<()> { ) -> io::Result<()> {
self.clear_render(out)?; self.clear_render(out)?;
let prompt = self.prompt(base_prompt, vim_enabled); let prompt = self.prompt(base_prompt, vim_enabled);
let buffer = self.visible_buffer(); let buffer = self.visible_buffer();
write!(out, "{prompt}{buffer}")?; write!(out, "{prompt}{buffer}")?;
if !assist_lines.is_empty() {
for line in assist_lines {
write!(out, "\r\n{line}")?;
}
}
let (cursor_row, cursor_col, total_lines) = self.cursor_layout(prompt.as_ref()); let (cursor_row, cursor_col, total_lines) =
self.cursor_layout(prompt.as_ref(), assist_lines.len());
let rows_to_move_up = total_lines.saturating_sub(cursor_row + 1); let rows_to_move_up = total_lines.saturating_sub(cursor_row + 1);
if rows_to_move_up > 0 { if rows_to_move_up > 0 {
queue!(out, MoveUp(to_u16(rows_to_move_up)?))?; queue!(out, MoveUp(to_u16(rows_to_move_up)?))?;
@@ -211,7 +243,7 @@ impl EditSession {
writeln!(out) writeln!(out)
} }
fn cursor_layout(&self, prompt: &str) -> (usize, usize, usize) { fn cursor_layout(&self, prompt: &str, assist_line_count: usize) -> (usize, usize, usize) {
let active_text = self.active_text(); let active_text = self.active_text();
let cursor = if self.mode == EditorMode::Command { let cursor = if self.mode == EditorMode::Command {
self.command_cursor self.command_cursor
@@ -225,7 +257,8 @@ impl EditSession {
Some((_, suffix)) => suffix.chars().count(), Some((_, suffix)) => suffix.chars().count(),
None => prompt.chars().count() + cursor_prefix.chars().count(), None => prompt.chars().count() + cursor_prefix.chars().count(),
}; };
let total_lines = active_text.bytes().filter(|byte| *byte == b'\n').count() + 1; let total_lines =
active_text.bytes().filter(|byte| *byte == b'\n').count() + 1 + assist_line_count;
(cursor_row, cursor_col, total_lines) (cursor_row, cursor_col, total_lines)
} }
} }
@@ -240,7 +273,7 @@ enum KeyAction {
pub struct LineEditor { pub struct LineEditor {
prompt: String, prompt: String,
completions: Vec<String>, slash_commands: Vec<SlashCommandDescriptor>,
history: Vec<String>, history: Vec<String>,
yank_buffer: YankBuffer, yank_buffer: YankBuffer,
vim_enabled: bool, vim_enabled: bool,
@@ -255,11 +288,24 @@ struct CompletionState {
} }
impl LineEditor { impl LineEditor {
#[allow(dead_code)]
#[must_use] #[must_use]
pub fn new(prompt: impl Into<String>, completions: Vec<String>) -> Self { pub fn new(prompt: impl Into<String>, completions: Vec<String>) -> Self {
let slash_commands = completions
.into_iter()
.map(SlashCommandDescriptor::simple)
.collect();
Self::with_slash_commands(prompt, slash_commands)
}
#[must_use]
pub fn with_slash_commands(
prompt: impl Into<String>,
slash_commands: Vec<SlashCommandDescriptor>,
) -> Self {
Self { Self {
prompt: prompt.into(), prompt: prompt.into(),
completions, slash_commands,
history: Vec::new(), history: Vec::new(),
yank_buffer: YankBuffer::default(), yank_buffer: YankBuffer::default(),
vim_enabled: false, vim_enabled: false,
@@ -284,7 +330,12 @@ impl LineEditor {
let _raw_mode = RawModeGuard::new()?; let _raw_mode = RawModeGuard::new()?;
let mut stdout = io::stdout(); let mut stdout = io::stdout();
let mut session = EditSession::new(self.vim_enabled); let mut session = EditSession::new(self.vim_enabled);
session.render(&mut stdout, &self.prompt, self.vim_enabled)?; session.render(
&mut stdout,
&self.prompt,
self.vim_enabled,
&self.command_assist_lines(&session),
)?;
loop { loop {
let Event::Key(key) = event::read()? else { let Event::Key(key) = event::read()? else {
@@ -296,7 +347,12 @@ impl LineEditor {
match self.handle_key_event(&mut session, key) { match self.handle_key_event(&mut session, key) {
KeyAction::Continue => { KeyAction::Continue => {
session.render(&mut stdout, &self.prompt, self.vim_enabled)?; session.render(
&mut stdout,
&self.prompt,
self.vim_enabled,
&self.command_assist_lines(&session),
)?;
} }
KeyAction::Submit(line) => { KeyAction::Submit(line) => {
session.finalize_render(&mut stdout, &self.prompt, self.vim_enabled)?; session.finalize_render(&mut stdout, &self.prompt, self.vim_enabled)?;
@@ -325,7 +381,12 @@ impl LineEditor {
} }
)?; )?;
session = EditSession::new(self.vim_enabled); session = EditSession::new(self.vim_enabled);
session.render(&mut stdout, &self.prompt, self.vim_enabled)?; session.render(
&mut stdout,
&self.prompt,
self.vim_enabled,
&self.command_assist_lines(&session),
)?;
} }
} }
} }
@@ -699,25 +760,21 @@ impl LineEditor {
state state
.matches .matches
.iter() .iter()
.any(|candidate| candidate == &session.text) .any(|candidate| session.text == *candidate || session.text == format!("{candidate} "))
}) })
{ {
let candidate = state.matches[state.next_index % state.matches.len()].clone(); let candidate = state.matches[state.next_index % state.matches.len()].clone();
state.next_index += 1; state.next_index += 1;
session.text.replace_range(..session.cursor, &candidate); let replacement = completed_command(&candidate);
session.cursor = candidate.len(); session.text.replace_range(..session.cursor, &replacement);
session.cursor = replacement.len();
return; return;
} }
let Some(prefix) = slash_command_prefix(&session.text, session.cursor) else { let Some(prefix) = slash_command_prefix(&session.text, session.cursor) else {
self.completion_state = None; self.completion_state = None;
return; return;
}; };
let matches = self let matches = self.matching_commands(prefix);
.completions
.iter()
.filter(|candidate| candidate.starts_with(prefix) && candidate.as_str() != prefix)
.cloned()
.collect::<Vec<_>>();
if matches.is_empty() { if matches.is_empty() {
self.completion_state = None; self.completion_state = None;
return; return;
@@ -741,8 +798,111 @@ impl LineEditor {
candidate candidate
}; };
session.text.replace_range(..session.cursor, &candidate); let replacement = completed_command(&candidate);
session.cursor = candidate.len(); session.text.replace_range(..session.cursor, &replacement);
session.cursor = replacement.len();
}
fn matching_commands(&self, prefix: &str) -> Vec<String> {
let normalized = prefix.to_ascii_lowercase();
let mut ranked = self
.slash_commands
.iter()
.filter_map(|descriptor| {
let command = descriptor.command.clone();
let mut best_rank = None::<(u8, usize)>;
for trigger in descriptor.triggers() {
let trigger_lower = trigger.to_ascii_lowercase();
let rank = if trigger_lower == normalized {
if trigger == descriptor.command {
Some((0, trigger.len()))
} else {
Some((1, trigger.len()))
}
} else if trigger_lower.starts_with(&normalized) {
if trigger == descriptor.command {
Some((2, trigger.len()))
} else {
Some((3, trigger.len()))
}
} else if trigger_lower.contains(&normalized) {
Some((4, trigger.len()))
} else {
None
};
if let Some(rank) = rank {
best_rank = Some(best_rank.map_or(rank, |current| current.min(rank)));
}
}
best_rank.map(|(bucket, len)| (bucket, len, command))
})
.collect::<Vec<_>>();
ranked.sort_by(|left, right| left.cmp(right));
ranked.dedup_by(|left, right| left.2 == right.2);
ranked.into_iter().map(|(_, _, command)| command).collect()
}
fn command_assist_lines(&self, session: &EditSession) -> Vec<String> {
if session.mode == EditorMode::Command || session.cursor != session.text.len() {
return Vec::new();
}
let input = session.text.as_str();
if !input.starts_with('/') {
return Vec::new();
}
if let Some((command, args)) = command_and_args(input) {
if input.ends_with(' ') && args.is_empty() {
if let Some(descriptor) = self.find_command_descriptor(command) {
let mut lines = Vec::new();
if let Some(argument_hint) = &descriptor.argument_hint {
lines.push(dimmed_line(format!("Arguments: {argument_hint}")));
}
if let Some(description) = &descriptor.description {
lines.push(dimmed_line(description));
}
if !lines.is_empty() {
return lines;
}
}
}
}
if input.contains(char::is_whitespace) {
return Vec::new();
}
let matches = self.matching_commands(input);
if matches.is_empty() {
return Vec::new();
}
let mut lines = vec![dimmed_line("Suggestions")];
lines.extend(matches.into_iter().take(3).map(|command| {
let description = self
.find_command_descriptor(command.trim_start_matches('/'))
.and_then(|descriptor| descriptor.description.as_deref())
.unwrap_or_default();
if description.is_empty() {
dimmed_line(format!(" {command}"))
} else {
dimmed_line(format!(" {command:<18} {description}"))
}
}));
lines
}
fn find_command_descriptor(&self, name: &str) -> Option<&SlashCommandDescriptor> {
let normalized = name.trim().trim_start_matches('/').to_ascii_lowercase();
self.slash_commands.iter().find(|descriptor| {
descriptor.command.trim_start_matches('/').eq_ignore_ascii_case(&normalized)
|| descriptor
.aliases
.iter()
.any(|alias| alias.trim_start_matches('/').eq_ignore_ascii_case(&normalized))
})
} }
fn history_up(&self, session: &mut EditSession) { fn history_up(&self, session: &mut EditSession) {
@@ -964,6 +1124,27 @@ fn slash_command_prefix(line: &str, pos: usize) -> Option<&str> {
Some(prefix) Some(prefix)
} }
fn command_and_args(input: &str) -> Option<(&str, &str)> {
let trimmed = input.trim_start();
let without_slash = trimmed.strip_prefix('/')?;
let (command, args) = without_slash
.split_once(' ')
.map_or((without_slash, ""), |(command, args)| (command, args));
Some((command, args))
}
fn completed_command(command: &str) -> String {
if command.ends_with(' ') {
command.to_string()
} else {
format!("{command} ")
}
}
fn dimmed_line(text: impl AsRef<str>) -> String {
format!("\x1b[2m{}\x1b[0m", text.as_ref())
}
fn to_u16(value: usize) -> io::Result<u16> { fn to_u16(value: usize) -> io::Result<u16> {
u16::try_from(value).map_err(|_| { u16::try_from(value).map_err(|_| {
io::Error::new( io::Error::new(
@@ -977,6 +1158,7 @@ fn to_u16(value: usize) -> io::Result<u16> {
mod tests { mod tests {
use super::{ use super::{
selection_bounds, slash_command_prefix, EditSession, EditorMode, KeyAction, LineEditor, selection_bounds, slash_command_prefix, EditSession, EditorMode, KeyAction, LineEditor,
SlashCommandDescriptor,
}; };
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
@@ -1149,7 +1331,7 @@ mod tests {
// then // then
assert_eq!(session.text, "/help "); assert_eq!(session.text, "/help ");
assert_eq!(session.cursor, 5); assert_eq!(session.cursor, 6);
} }
#[test] #[test]
@@ -1171,8 +1353,65 @@ mod tests {
let second = session.text.clone(); let second = session.text.clone();
// then // then
assert_eq!(first, "/permissions"); assert_eq!(first, "/plugin ");
assert_eq!(second, "/plugin"); assert_eq!(second, "/permissions ");
}
#[test]
fn tab_completion_prefers_canonical_command_over_alias() {
let mut editor = LineEditor::with_slash_commands(
"> ",
vec![SlashCommandDescriptor {
command: "/plugin".to_string(),
description: Some("Manage plugins".to_string()),
argument_hint: Some("[list]".to_string()),
aliases: vec!["/plugins".to_string(), "/marketplace".to_string()],
}],
);
let mut session = EditSession::new(false);
session.text = "/plugins".to_string();
session.cursor = session.text.len();
editor.complete_slash_command(&mut session);
assert_eq!(session.text, "/plugin ");
}
#[test]
fn command_assist_lines_show_suggestions_and_argument_hints() {
let editor = LineEditor::with_slash_commands(
"> ",
vec![
SlashCommandDescriptor {
command: "/help".to_string(),
description: Some("Show help and available commands".to_string()),
argument_hint: None,
aliases: Vec::new(),
},
SlashCommandDescriptor {
command: "/model".to_string(),
description: Some("Show or switch the active model".to_string()),
argument_hint: Some("[model]".to_string()),
aliases: Vec::new(),
},
],
);
let mut prefix_session = EditSession::new(false);
prefix_session.text = "/h".to_string();
prefix_session.cursor = prefix_session.text.len();
let prefix_lines = editor.command_assist_lines(&prefix_session);
assert!(prefix_lines.iter().any(|line| line.contains("Suggestions")));
assert!(prefix_lines.iter().any(|line| line.contains("/help")));
let mut hint_session = EditSession::new(false);
hint_session.text = "/model ".to_string();
hint_session.cursor = hint_session.text.len();
let hint_lines = editor.command_assist_lines(&hint_session);
assert!(hint_lines.iter().any(|line| line.contains("Arguments: [model]")));
assert!(hint_lines
.iter()
.any(|line| line.contains("Show or switch the active model")));
} }
#[test] #[test]

View File

@@ -22,12 +22,13 @@ use api::{
}; };
use commands::{ use commands::{
handle_agents_slash_command, handle_plugins_slash_command, handle_skills_slash_command, handle_agents_slash_command, handle_hooks_slash_command, handle_plugins_slash_command,
render_slash_command_help, resume_supported_slash_commands, slash_command_specs, handle_skills_slash_command, render_plugin_inspection_report, render_slash_command_help,
suggest_slash_commands, SlashCommand, resume_supported_slash_commands, slash_command_specs, suggest_slash_commands, SlashCommand,
}; };
use compat_harness::{extract_manifest, UpstreamPaths}; use compat_harness::{extract_manifest, UpstreamPaths};
use init::initialize_repo; use init::initialize_repo;
use input::SlashCommandDescriptor;
use plugins::{PluginManager, PluginManagerConfig}; use plugins::{PluginManager, PluginManagerConfig};
use render::{MarkdownStreamState, Spinner, TerminalRenderer}; use render::{MarkdownStreamState, Spinner, TerminalRenderer};
use runtime::{ use runtime::{
@@ -85,6 +86,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
CliAction::DumpManifests => dump_manifests(), CliAction::DumpManifests => dump_manifests(),
CliAction::BootstrapPlan => print_bootstrap_plan(), CliAction::BootstrapPlan => print_bootstrap_plan(),
CliAction::Agents { args } => LiveCli::print_agents(args.as_deref())?, CliAction::Agents { args } => LiveCli::print_agents(args.as_deref())?,
CliAction::Hooks { args } => LiveCli::print_hooks(args.as_deref())?,
CliAction::Skills { args } => LiveCli::print_skills(args.as_deref())?, CliAction::Skills { args } => LiveCli::print_skills(args.as_deref())?,
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date), CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
CliAction::Version => print_version(), CliAction::Version => print_version(),
@@ -120,6 +122,9 @@ enum CliAction {
Agents { Agents {
args: Option<String>, args: Option<String>,
}, },
Hooks {
args: Option<String>,
},
Skills { Skills {
args: Option<String>, args: Option<String>,
}, },
@@ -289,6 +294,9 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
"agents" => Ok(CliAction::Agents { "agents" => Ok(CliAction::Agents {
args: join_optional_args(&rest[1..]), args: join_optional_args(&rest[1..]),
}), }),
"hooks" => Ok(CliAction::Hooks {
args: join_optional_args(&rest[1..]),
}),
"skills" => Ok(CliAction::Skills { "skills" => Ok(CliAction::Skills {
args: join_optional_args(&rest[1..]), args: join_optional_args(&rest[1..]),
}), }),
@@ -331,6 +339,7 @@ fn parse_direct_slash_cli_action(rest: &[String]) -> Result<CliAction, String> {
match SlashCommand::parse(&raw) { match SlashCommand::parse(&raw) {
Some(SlashCommand::Help) => Ok(CliAction::Help), Some(SlashCommand::Help) => Ok(CliAction::Help),
Some(SlashCommand::Agents { args }) => Ok(CliAction::Agents { args }), Some(SlashCommand::Agents { args }) => Ok(CliAction::Agents { args }),
Some(SlashCommand::Hooks { args }) => Ok(CliAction::Hooks { args }),
Some(SlashCommand::Skills { args }) => Ok(CliAction::Skills { args }), Some(SlashCommand::Skills { args }) => Ok(CliAction::Skills { args }),
Some(command) => Err(format_direct_slash_command_error( Some(command) => Err(format_direct_slash_command_error(
match &command { match &command {
@@ -942,6 +951,13 @@ fn run_resume_command(
session: session.clone(), session: session.clone(),
message: Some(render_config_report(section.as_deref())?), message: Some(render_config_report(section.as_deref())?),
}), }),
SlashCommand::Hooks { args } => {
let cwd = env::current_dir()?;
Ok(ResumeCommandOutcome {
session: session.clone(),
message: Some(handle_hooks_slash_command(args.as_deref(), &cwd)?),
})
}
SlashCommand::Memory => Ok(ResumeCommandOutcome { SlashCommand::Memory => Ok(ResumeCommandOutcome {
session: session.clone(), session: session.clone(),
message: Some(render_memory_report()?), message: Some(render_memory_report()?),
@@ -999,6 +1015,7 @@ fn run_resume_command(
| SlashCommand::Permissions { .. } | SlashCommand::Permissions { .. }
| SlashCommand::Session { .. } | SlashCommand::Session { .. }
| SlashCommand::Plugins { .. } | SlashCommand::Plugins { .. }
| SlashCommand::ReloadPlugins
| SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()), | SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
} }
} }
@@ -1009,7 +1026,7 @@ fn run_repl(
permission_mode: PermissionMode, permission_mode: PermissionMode,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?; let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
let mut editor = input::LineEditor::new("> ", slash_command_completion_candidates()); let mut editor = input::LineEditor::with_slash_commands("> ", slash_command_descriptors());
println!("{}", cli.startup_banner()); println!("{}", cli.startup_banner());
loop { loop {
@@ -1141,13 +1158,13 @@ impl LiveCli {
format!( format!(
" Quick start {}", " Quick start {}",
if has_claw_md { if has_claw_md {
"/help · /status · ask for a task" "Type / to browse commands · /help for shortcuts · ask for a task"
} else { } else {
"/init · /help · /status" "/init · then type / to browse commands"
} }
), ),
" Editor Tab completes slash commands · /vim toggles modal editing" " Autocomplete Type / for command suggestions · Tab accepts or cycles".to_string(),
.to_string(), " Editor /vim toggles modal editing · Esc clears menus first".to_string(),
" Multiline Shift+Enter or Ctrl+J inserts a newline".to_string(), " Multiline Shift+Enter or Ctrl+J inserts a newline".to_string(),
]; ];
if !has_claw_md { if !has_claw_md {
@@ -1294,6 +1311,10 @@ impl LiveCli {
Self::print_config(section.as_deref())?; Self::print_config(section.as_deref())?;
false false
} }
SlashCommand::Hooks { args } => {
Self::print_hooks(args.as_deref())?;
false
}
SlashCommand::Memory => { SlashCommand::Memory => {
Self::print_memory()?; Self::print_memory()?;
false false
@@ -1320,6 +1341,7 @@ impl LiveCli {
SlashCommand::Plugins { action, target } => { SlashCommand::Plugins { action, target } => {
self.handle_plugins_command(action.as_deref(), target.as_deref())? self.handle_plugins_command(action.as_deref(), target.as_deref())?
} }
SlashCommand::ReloadPlugins => self.reload_plugins_command()?,
SlashCommand::Agents { args } => { SlashCommand::Agents { args } => {
Self::print_agents(args.as_deref())?; Self::print_agents(args.as_deref())?;
false false
@@ -1555,6 +1577,12 @@ impl LiveCli {
Ok(()) Ok(())
} }
fn print_hooks(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
let cwd = env::current_dir()?;
println!("{}", handle_hooks_slash_command(args, &cwd)?);
Ok(())
}
fn print_skills(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> { fn print_skills(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
let cwd = env::current_dir()?; let cwd = env::current_dir()?;
println!("{}", handle_skills_slash_command(args, &cwd)?); println!("{}", handle_skills_slash_command(args, &cwd)?);
@@ -1645,6 +1673,22 @@ impl LiveCli {
Ok(false) Ok(false)
} }
fn reload_plugins_command(&mut self) -> Result<bool, Box<dyn std::error::Error>> {
self.reload_runtime_features()?;
let cwd = env::current_dir()?;
let loader = ConfigLoader::default_for(&cwd);
let runtime_config = loader.load()?;
let manager = build_plugin_manager(&cwd, &loader, &runtime_config);
let inspection = manager.inspect()?;
println!(
"Plugin runtime reloaded from local manifests.\n{}",
render_plugin_inspection_report(&inspection)
);
Ok(false)
}
fn reload_runtime_features(&mut self) -> Result<(), Box<dyn std::error::Error>> { fn reload_runtime_features(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.runtime = build_runtime( self.runtime = build_runtime(
self.runtime.session().clone(), self.runtime.session().clone(),
@@ -1973,14 +2017,15 @@ fn render_session_list(active_session_id: &str) -> Result<String, Box<dyn std::e
fn render_repl_help() -> String { fn render_repl_help() -> String {
[ [
"Interactive REPL".to_string(), "Interactive REPL".to_string(),
" Quick start Ask a task in plain English or use one of the core commands below." " Quick start Ask a task in plain English, or type / to browse slash commands."
.to_string(), .to_string(),
" Core commands /help · /status · /model · /permissions · /compact".to_string(), " Core commands /help · /status · /model · /permissions · /compact".to_string(),
" Exit /exit or /quit".to_string(), " Exit /exit or /quit".to_string(),
" Autocomplete Type / for suggestions · Tab accepts or cycles matches".to_string(),
" Vim mode /vim toggles modal editing".to_string(), " Vim mode /vim toggles modal editing".to_string(),
" History Up/Down recalls previous prompts".to_string(), " History Up/Down recalls previous prompts".to_string(),
" Completion Tab cycles slash command matches".to_string(), " Cancel Esc dismisses menus first · Ctrl-C clears input (or exits on empty)"
" Cancel Ctrl-C clears input (or exits on an empty prompt)".to_string(), .to_string(),
" Multiline Shift+Enter or Ctrl+J inserts a newline".to_string(), " Multiline Shift+Enter or Ctrl+J inserts a newline".to_string(),
String::new(), String::new(),
render_slash_command_help(), render_slash_command_help(),
@@ -3283,21 +3328,48 @@ fn collect_tool_results(summary: &runtime::TurnSummary) -> Vec<serde_json::Value
.collect() .collect()
} }
fn slash_command_completion_candidates() -> Vec<String> { fn slash_command_descriptors() -> Vec<SlashCommandDescriptor> {
let mut candidates = slash_command_specs() let mut descriptors = slash_command_specs()
.iter() .iter()
.flat_map(|spec| { .map(|spec| SlashCommandDescriptor {
std::iter::once(spec.name) command: format!("/{}", spec.name),
.chain(spec.aliases.iter().copied()) description: Some(spec.summary.to_string()),
.map(|name| format!("/{name}")) argument_hint: spec.argument_hint.map(ToOwned::to_owned),
aliases: spec
.aliases
.iter()
.map(|alias| format!("/{alias}"))
.collect(),
})
.collect::<Vec<_>>();
descriptors.extend([
SlashCommandDescriptor {
command: "/vim".to_string(),
description: Some("Toggle modal editing".to_string()),
argument_hint: None,
aliases: Vec::new(),
},
SlashCommandDescriptor {
command: "/exit".to_string(),
description: Some("Exit the interactive REPL".to_string()),
argument_hint: None,
aliases: vec!["/quit".to_string()],
},
]);
descriptors.sort_by(|left, right| left.command.cmp(&right.command));
descriptors.dedup_by(|left, right| left.command == right.command);
descriptors
}
fn slash_command_completion_candidates() -> Vec<String> {
let mut candidates = slash_command_descriptors()
.into_iter()
.flat_map(|descriptor| {
std::iter::once(descriptor.command)
.chain(descriptor.aliases)
.collect::<Vec<_>>() .collect::<Vec<_>>()
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
candidates.extend([
String::from("/vim"),
String::from("/exit"),
String::from("/quit"),
]);
candidates.sort(); candidates.sort();
candidates.dedup(); candidates.dedup();
candidates candidates
@@ -3986,6 +4058,10 @@ fn print_help_to(out: &mut impl Write) -> io::Result<()> {
out, out,
" /help Browse the full slash command map" " /help Browse the full slash command map"
)?; )?;
writeln!(
out,
" / Open slash suggestions in the REPL"
)?;
writeln!( writeln!(
out, out,
" /status Inspect session + workspace state" " /status Inspect session + workspace state"
@@ -4000,7 +4076,7 @@ fn print_help_to(out: &mut impl Write) -> io::Result<()> {
)?; )?;
writeln!( writeln!(
out, out,
" Tab Complete slash commands" " Tab Accept or cycle slash command suggestions"
)?; )?;
writeln!( writeln!(
out, out,
@@ -4026,7 +4102,11 @@ fn print_help_to(out: &mut impl Write) -> io::Result<()> {
)?; )?;
writeln!( writeln!(
out, out,
" claw skills List installed skills" " claw hooks Inspect configured tool hooks"
)?;
writeln!(
out,
" claw skills List discoverable local skills"
)?; )?;
writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?; writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?;
writeln!( writeln!(
@@ -4095,6 +4175,7 @@ fn print_help_to(out: &mut impl Write) -> io::Result<()> {
" claw --resume session.json /status /diff /export notes.txt" " claw --resume session.json /status /diff /export notes.txt"
)?; )?;
writeln!(out, " claw agents")?; writeln!(out, " claw agents")?;
writeln!(out, " claw hooks")?;
writeln!(out, " claw /skills")?; writeln!(out, " claw /skills")?;
writeln!(out, " claw login")?; writeln!(out, " claw login")?;
writeln!(out, " claw init")?; writeln!(out, " claw init")?;
@@ -4115,9 +4196,10 @@ mod tests {
normalize_permission_mode, parse_args, parse_git_status_metadata, permission_policy, normalize_permission_mode, parse_args, parse_git_status_metadata, permission_policy,
print_help_to, push_output_block, render_config_report, render_memory_report, print_help_to, push_output_block, render_config_report, render_memory_report,
render_repl_help, render_unknown_repl_command, resolve_model_alias, response_to_events, render_repl_help, render_unknown_repl_command, resolve_model_alias, response_to_events,
resume_supported_slash_commands, slash_command_completion_candidates, status_context, resume_supported_slash_commands, slash_command_completion_candidates,
CliAction, CliOutputFormat, InternalPromptProgressEvent, InternalPromptProgressState, slash_command_descriptors, status_context, CliAction, CliOutputFormat,
SlashCommand, StatusUsage, DEFAULT_MODEL, InternalPromptProgressEvent, InternalPromptProgressState, SlashCommand, StatusUsage,
DEFAULT_MODEL,
}; };
use api::{MessageResponse, OutputContentBlock, Usage}; use api::{MessageResponse, OutputContentBlock, Usage};
use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission}; use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};
@@ -4321,6 +4403,10 @@ mod tests {
parse_args(&["agents".to_string()]).expect("agents should parse"), parse_args(&["agents".to_string()]).expect("agents should parse"),
CliAction::Agents { args: None } CliAction::Agents { args: None }
); );
assert_eq!(
parse_args(&["hooks".to_string()]).expect("hooks should parse"),
CliAction::Hooks { args: None }
);
assert_eq!( assert_eq!(
parse_args(&["skills".to_string()]).expect("skills should parse"), parse_args(&["skills".to_string()]).expect("skills should parse"),
CliAction::Skills { args: None } CliAction::Skills { args: None }
@@ -4340,6 +4426,10 @@ mod tests {
parse_args(&["/agents".to_string()]).expect("/agents should parse"), parse_args(&["/agents".to_string()]).expect("/agents should parse"),
CliAction::Agents { args: None } CliAction::Agents { args: None }
); );
assert_eq!(
parse_args(&["/hooks".to_string()]).expect("/hooks should parse"),
CliAction::Hooks { args: None }
);
assert_eq!( assert_eq!(
parse_args(&["/skills".to_string()]).expect("/skills should parse"), parse_args(&["/skills".to_string()]).expect("/skills should parse"),
CliAction::Skills { args: None } CliAction::Skills { args: None }
@@ -4439,6 +4529,7 @@ mod tests {
fn repl_help_includes_shared_commands_and_exit() { fn repl_help_includes_shared_commands_and_exit() {
let help = render_repl_help(); let help = render_repl_help();
assert!(help.contains("Interactive REPL")); assert!(help.contains("Interactive REPL"));
assert!(help.contains("type / to browse slash commands"));
assert!(help.contains("/help")); assert!(help.contains("/help"));
assert!(help.contains("/status")); assert!(help.contains("/status"));
assert!(help.contains("/model [model]")); assert!(help.contains("/model [model]"));
@@ -4447,6 +4538,7 @@ mod tests {
assert!(help.contains("/cost")); assert!(help.contains("/cost"));
assert!(help.contains("/resume <session-path>")); assert!(help.contains("/resume <session-path>"));
assert!(help.contains("/config [env|hooks|model|plugins]")); assert!(help.contains("/config [env|hooks|model|plugins]"));
assert!(help.contains("/hooks"));
assert!(help.contains("/memory")); assert!(help.contains("/memory"));
assert!(help.contains("/init")); assert!(help.contains("/init"));
assert!(help.contains("/diff")); assert!(help.contains("/diff"));
@@ -4454,13 +4546,15 @@ mod tests {
assert!(help.contains("/export [file]")); assert!(help.contains("/export [file]"));
assert!(help.contains("/session [list|switch <session-id>]")); assert!(help.contains("/session [list|switch <session-id>]"));
assert!(help.contains( assert!(help.contains(
"/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]" "/plugin [inspect|list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
)); ));
assert!(help.contains("/reload-plugins"));
assert!(help.contains("aliases: /plugins, /marketplace")); assert!(help.contains("aliases: /plugins, /marketplace"));
assert!(help.contains("/agents")); assert!(help.contains("/agents"));
assert!(help.contains("/skills")); assert!(help.contains("/skills"));
assert!(help.contains("/exit")); assert!(help.contains("/exit"));
assert!(help.contains("Tab cycles slash command matches")); assert!(help.contains("Type / for suggestions"));
assert!(help.contains("Tab accepts or cycles matches"));
} }
#[test] #[test]
@@ -4472,6 +4566,36 @@ mod tests {
assert!(candidates.contains(&"/quit".to_string())); assert!(candidates.contains(&"/quit".to_string()));
} }
#[test]
fn slash_command_descriptors_include_descriptions_and_aliases() {
let descriptors = slash_command_descriptors();
let plugin = descriptors
.iter()
.find(|descriptor| descriptor.command == "/plugin")
.expect("plugin descriptor should exist");
assert_eq!(
plugin.description.as_deref(),
Some("Inspect and manage local Claw Code plugins")
);
assert!(plugin.aliases.contains(&"/plugins".to_string()));
assert!(plugin.aliases.contains(&"/marketplace".to_string()));
let reload = descriptors
.iter()
.find(|descriptor| descriptor.command == "/reload-plugins")
.expect("reload plugins descriptor should exist");
assert_eq!(
reload.description.as_deref(),
Some("Reload plugin-derived runtime features and print current support")
);
let exit = descriptors
.iter()
.find(|descriptor| descriptor.command == "/exit")
.expect("exit descriptor should exist");
assert!(exit.aliases.contains(&"/quit".to_string()));
}
#[test] #[test]
fn unknown_repl_command_suggestions_include_repl_shortcuts() { fn unknown_repl_command_suggestions_include_repl_shortcuts() {
let rendered = render_unknown_repl_command("exi"); let rendered = render_unknown_repl_command("exi");
@@ -4489,8 +4613,8 @@ mod tests {
assert_eq!( assert_eq!(
names, names,
vec![ vec![
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff", "help", "status", "compact", "clear", "cost", "config", "hooks", "memory", "init",
"version", "export", "agents", "skills", "diff", "version", "export", "agents", "skills",
] ]
); );
} }
@@ -4559,7 +4683,9 @@ mod tests {
print_help_to(&mut help).expect("help should render"); print_help_to(&mut help).expect("help should render");
let help = String::from_utf8(help).expect("help should be utf8"); let help = String::from_utf8(help).expect("help should be utf8");
assert!(help.contains("claw init")); assert!(help.contains("claw init"));
assert!(help.contains("Open slash suggestions in the REPL"));
assert!(help.contains("claw agents")); assert!(help.contains("claw agents"));
assert!(help.contains("claw hooks"));
assert!(help.contains("claw skills")); assert!(help.contains("claw skills"));
assert!(help.contains("claw /skills")); assert!(help.contains("claw /skills"));
} }
@@ -4762,7 +4888,7 @@ mod tests {
fn repl_help_mentions_history_completion_and_multiline() { fn repl_help_mentions_history_completion_and_multiline() {
let help = render_repl_help(); let help = render_repl_help();
assert!(help.contains("Up/Down")); assert!(help.contains("Up/Down"));
assert!(help.contains("Tab cycles")); assert!(help.contains("Tab accepts or cycles"));
assert!(help.contains("Shift+Enter or Ctrl+J")); assert!(help.contains("Shift+Enter or Ctrl+J"));
} }

View File

@@ -0,0 +1,299 @@
use std::fs;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::Command;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde_json::{json, Value};
#[test]
fn prompt_json_with_tool_use_writes_clean_transport_output() {
let fixture_root = unique_temp_dir("claw-json-transport");
fs::create_dir_all(&fixture_root).expect("create fixture root");
fs::write(fixture_root.join("fixture.txt"), "fixture contents\n").expect("write fixture file");
fs::create_dir_all(fixture_root.join("config")).expect("create config dir");
let server = TestServer::spawn(vec![
sse_response(
"req_tool",
&tool_use_stream("read_file", json!({ "path": "fixture.txt" })),
),
sse_response("req_done", &text_stream("done")),
]);
let output = Command::new(env!("CARGO_BIN_EXE_claw"))
.current_dir(&fixture_root)
.env("ANTHROPIC_BASE_URL", server.base_url())
.env("ANTHROPIC_API_KEY", "test-key")
.env("CLAW_CONFIG_HOME", fixture_root.join("config"))
.arg("--output-format")
.arg("json")
.arg("prompt")
.arg("use a tool")
.output()
.expect("run claw prompt json");
server.finish();
let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
let stderr = String::from_utf8(output.stderr).expect("stderr should be utf8");
assert!(
output.status.success(),
"status: {:?}\nstderr:\n{stderr}",
output.status
);
assert!(stderr.trim().is_empty(), "unexpected stderr: {stderr}");
assert!(
stdout.trim_start().starts_with('{'),
"stdout should begin with JSON object, got:\n{stdout}"
);
let parsed: Value = serde_json::from_str(stdout.trim())
.expect("full stdout should be a single parseable JSON object");
assert_eq!(parsed["message"], "done");
assert_eq!(parsed["iterations"], 2);
assert_eq!(parsed["tool_uses"].as_array().map(Vec::len), Some(1));
assert_eq!(parsed["tool_results"].as_array().map(Vec::len), Some(1));
assert_eq!(parsed["tool_uses"][0]["name"], "read_file");
assert_eq!(parsed["tool_results"][0]["tool_name"], "read_file");
assert_eq!(parsed["tool_results"][0]["is_error"], false);
let tool_output = parsed["tool_results"][0]["output"]
.as_str()
.expect("tool result output string");
assert!(tool_output.contains("fixture contents"));
assert!(
!stdout.contains("📄 Read"),
"stdout leaked human-readable tool rendering:\n{stdout}"
);
}
struct TestServer {
base_url: String,
join_handle: thread::JoinHandle<()>,
}
impl TestServer {
fn spawn(responses: Vec<String>) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
listener
.set_nonblocking(true)
.expect("set nonblocking listener");
let address = listener.local_addr().expect("listener addr");
let join_handle = thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(10);
let mut served = 0usize;
while served < responses.len() && Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
drain_http_request(&mut stream);
stream
.write_all(responses[served].as_bytes())
.expect("write response");
served += 1;
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("accept failed: {error}"),
}
}
assert_eq!(
served,
responses.len(),
"server did not observe expected request count"
);
});
Self {
base_url: format!("http://{address}"),
join_handle,
}
}
fn base_url(&self) -> &str {
&self.base_url
}
fn finish(self) {
self.join_handle.join().expect("join server thread");
}
}
fn drain_http_request(stream: &mut std::net::TcpStream) {
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.expect("set read timeout");
let mut buffer = Vec::new();
let mut header_end = None;
while header_end.is_none() {
let mut chunk = [0_u8; 1024];
let read = stream.read(&mut chunk).expect("read request chunk");
if read == 0 {
break;
}
buffer.extend_from_slice(&chunk[..read]);
header_end = find_header_end(&buffer);
}
let header_end = header_end.expect("request should contain headers");
let headers = String::from_utf8(buffer[..header_end].to_vec()).expect("header utf8");
let content_length = headers
.lines()
.find_map(|line| {
line.split_once(':').and_then(|(name, value)| {
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().expect("content length"))
})
})
.unwrap_or(0);
let mut body = buffer[(header_end + 4)..].to_vec();
while body.len() < content_length {
let mut chunk = vec![0_u8; content_length - body.len()];
let read = stream.read(&mut chunk).expect("read request body");
if read == 0 {
break;
}
body.extend_from_slice(&chunk[..read]);
}
}
fn find_header_end(buffer: &[u8]) -> Option<usize> {
buffer.windows(4).position(|window| window == b"\r\n\r\n")
}
fn sse_response(request_id: &str, body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nrequest-id: {request_id}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn tool_use_stream(tool_name: &str, input: Value) -> String {
let mut body = String::new();
body.push_str(&sse_event(
"message_start",
json!({
"type": "message_start",
"message": {
"id": "msg_tool",
"type": "message",
"role": "assistant",
"content": [],
"model": "claude-opus-4-6",
"stop_reason": null,
"stop_sequence": null,
"usage": {"input_tokens": 8, "output_tokens": 0}
}
}),
));
body.push_str(&sse_event(
"content_block_start",
json!({
"type": "content_block_start",
"index": 0,
"content_block": {
"type": "tool_use",
"id": "toolu_1",
"name": tool_name,
"input": {}
}
}),
));
body.push_str(&sse_event(
"content_block_delta",
json!({
"type": "content_block_delta",
"index": 0,
"delta": {
"type": "input_json_delta",
"partial_json": input.to_string()
}
}),
));
body.push_str(&sse_event(
"content_block_stop",
json!({"type": "content_block_stop", "index": 0}),
));
body.push_str(&sse_event(
"message_delta",
json!({
"type": "message_delta",
"delta": {"stop_reason": "tool_use", "stop_sequence": null},
"usage": {"input_tokens": 8, "output_tokens": 1}
}),
));
body.push_str(&sse_event("message_stop", json!({"type": "message_stop"})));
body.push_str("data: [DONE]\n\n");
body
}
fn text_stream(text: &str) -> String {
let mut body = String::new();
body.push_str(&sse_event(
"message_start",
json!({
"type": "message_start",
"message": {
"id": "msg_done",
"type": "message",
"role": "assistant",
"content": [],
"model": "claude-opus-4-6",
"stop_reason": null,
"stop_sequence": null,
"usage": {"input_tokens": 20, "output_tokens": 0}
}
}),
));
body.push_str(&sse_event(
"content_block_start",
json!({
"type": "content_block_start",
"index": 0,
"content_block": {"type": "text", "text": ""}
}),
));
body.push_str(&sse_event(
"content_block_delta",
json!({
"type": "content_block_delta",
"index": 0,
"delta": {"type": "text_delta", "text": text}
}),
));
body.push_str(&sse_event(
"content_block_stop",
json!({"type": "content_block_stop", "index": 0}),
));
body.push_str(&sse_event(
"message_delta",
json!({
"type": "message_delta",
"delta": {"stop_reason": "end_turn", "stop_sequence": null},
"usage": {"input_tokens": 20, "output_tokens": 2}
}),
));
body.push_str(&sse_event("message_stop", json!({"type": "message_stop"})));
body.push_str("data: [DONE]\n\n");
body
}
fn sse_event(event_name: &str, payload: Value) -> String {
format!("event: {event_name}\ndata: {payload}\n\n")
}
fn unique_temp_dir(prefix: &str) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock should be after epoch")
.as_nanos();
std::env::temp_dir().join(format!("{prefix}-{nanos}"))
}

File diff suppressed because it is too large Load Diff

View File

@@ -119,10 +119,6 @@ pub struct PluginManifest {
pub tools: Vec<PluginToolManifest>, pub tools: Vec<PluginToolManifest>,
#[serde(default)] #[serde(default)]
pub commands: Vec<PluginCommandManifest>, pub commands: Vec<PluginCommandManifest>,
#[serde(default)]
pub agents: Vec<String>,
#[serde(default)]
pub skills: Vec<String>,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
@@ -232,10 +228,6 @@ struct RawPluginManifest {
pub tools: Vec<RawPluginToolManifest>, pub tools: Vec<RawPluginToolManifest>,
#[serde(default)] #[serde(default)]
pub commands: Vec<PluginCommandManifest>, pub commands: Vec<PluginCommandManifest>,
#[serde(default, deserialize_with = "deserialize_string_list")]
pub agents: Vec<String>,
#[serde(default, deserialize_with = "deserialize_string_list")]
pub skills: Vec<String>,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -254,24 +246,6 @@ struct RawPluginToolManifest {
pub required_permission: String, pub required_permission: String,
} }
fn deserialize_string_list<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StringList {
One(String),
Many(Vec<String>),
}
Ok(match Option::<StringList>::deserialize(deserializer)? {
Some(StringList::One(value)) => vec![value],
Some(StringList::Many(values)) => values,
None => Vec::new(),
})
}
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct PluginTool { pub struct PluginTool {
plugin_id: String, plugin_id: String,
@@ -674,6 +648,17 @@ pub struct PluginSummary {
pub enabled: bool, pub enabled: bool,
} }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginInspection {
pub install_root: PathBuf,
pub registry_path: PathBuf,
pub settings_path: PathBuf,
pub bundled_root: PathBuf,
pub external_dirs: Vec<PathBuf>,
pub discoverable_plugins: Vec<PluginSummary>,
pub installed_plugins: Vec<PluginSummary>,
}
#[derive(Debug, Clone, Default, PartialEq)] #[derive(Debug, Clone, Default, PartialEq)]
pub struct PluginRegistry { pub struct PluginRegistry {
plugins: Vec<RegisteredPlugin>, plugins: Vec<RegisteredPlugin>,
@@ -960,6 +945,31 @@ impl PluginManager {
self.config.config_home.join(SETTINGS_FILE_NAME) self.config.config_home.join(SETTINGS_FILE_NAME)
} }
#[must_use]
pub fn bundled_root_path(&self) -> PathBuf {
self.config
.bundled_root
.clone()
.unwrap_or_else(Self::bundled_root)
}
#[must_use]
pub fn external_dirs(&self) -> &[PathBuf] {
&self.config.external_dirs
}
pub fn inspect(&self) -> Result<PluginInspection, PluginError> {
Ok(PluginInspection {
install_root: self.install_root(),
registry_path: self.registry_path(),
settings_path: self.settings_path(),
bundled_root: self.bundled_root_path(),
external_dirs: self.external_dirs().to_vec(),
discoverable_plugins: self.list_plugins()?,
installed_plugins: self.list_installed_plugins()?,
})
}
pub fn plugin_registry(&self) -> Result<PluginRegistry, PluginError> { pub fn plugin_registry(&self) -> Result<PluginRegistry, PluginError> {
Ok(PluginRegistry::new( Ok(PluginRegistry::new(
self.discover_plugins()? self.discover_plugins()?
@@ -1487,8 +1497,6 @@ fn build_plugin_manifest(
"lifecycle command", "lifecycle command",
&mut errors, &mut errors,
); );
let agents = build_manifest_paths(root, raw.agents, "agent", &mut errors);
let skills = build_manifest_paths(root, raw.skills, "skill", &mut errors);
let tools = build_manifest_tools(root, raw.tools, &mut errors); let tools = build_manifest_tools(root, raw.tools, &mut errors);
let commands = build_manifest_commands(root, raw.commands, &mut errors); let commands = build_manifest_commands(root, raw.commands, &mut errors);
@@ -1506,8 +1514,6 @@ fn build_plugin_manifest(
lifecycle: raw.lifecycle, lifecycle: raw.lifecycle,
tools, tools,
commands, commands,
agents,
skills,
}) })
} }
@@ -1623,47 +1629,6 @@ fn build_manifest_tools(
validated validated
} }
fn build_manifest_paths(
root: &Path,
paths: Vec<String>,
kind: &'static str,
errors: &mut Vec<PluginManifestValidationError>,
) -> Vec<String> {
let mut seen = BTreeSet::new();
let mut validated = Vec::new();
for path in paths {
let trimmed = path.trim();
if trimmed.is_empty() {
errors.push(PluginManifestValidationError::EmptyEntryField {
kind,
field: "path",
name: None,
});
continue;
}
let resolved = if Path::new(trimmed).is_absolute() {
PathBuf::from(trimmed)
} else {
root.join(trimmed)
};
if !resolved.exists() {
errors.push(PluginManifestValidationError::MissingPath {
kind,
path: resolved,
});
continue;
}
if seen.insert(trimmed.to_string()) {
validated.push(trimmed.to_string());
}
}
validated
}
fn build_manifest_commands( fn build_manifest_commands(
root: &Path, root: &Path,
commands: Vec<PluginCommandManifest>, commands: Vec<PluginCommandManifest>,
@@ -2298,38 +2263,6 @@ mod tests {
let _ = fs::remove_dir_all(root); let _ = fs::remove_dir_all(root);
} }
#[test]
fn load_plugin_from_directory_parses_agent_and_skill_paths() {
let root = temp_dir("manifest-component-paths");
write_file(
root.join("agents").join("ops").join("triage.md").as_path(),
"---\nname: triage\ndescription: triage agent\n---\n",
);
write_file(
root.join("skills")
.join("review")
.join("SKILL.md")
.as_path(),
"---\nname: review\ndescription: review skill\n---\n",
);
write_file(
root.join(MANIFEST_FILE_NAME).as_path(),
r#"{
"name": "component-paths",
"version": "1.0.0",
"description": "Manifest component paths",
"agents": "./agents/ops/triage.md",
"skills": ["./skills"]
}"#,
);
let manifest = load_plugin_from_directory(&root).expect("manifest should load");
assert_eq!(manifest.agents, vec!["./agents/ops/triage.md"]);
assert_eq!(manifest.skills, vec!["./skills"]);
let _ = fs::remove_dir_all(root);
}
#[test] #[test]
fn load_plugin_from_directory_defaults_optional_fields() { fn load_plugin_from_directory_defaults_optional_fields() {
let root = temp_dir("manifest-defaults"); let root = temp_dir("manifest-defaults");

View File

@@ -15,12 +15,9 @@ mod prompt;
mod remote; mod remote;
pub mod sandbox; pub mod sandbox;
mod session; mod session;
mod skills;
mod usage; mod usage;
pub use lsp::{
FileDiagnostics, LspContextEnrichment, LspError, LspManager, LspServerConfig,
SymbolLocation, WorkspaceDiagnostics,
};
pub use bash::{execute_bash, BashCommandInput, BashCommandOutput}; pub use bash::{execute_bash, BashCommandInput, BashCommandOutput};
pub use bootstrap::{BootstrapPhase, BootstrapPlan}; pub use bootstrap::{BootstrapPhase, BootstrapPlan};
pub use compact::{ pub use compact::{
@@ -28,8 +25,8 @@ pub use compact::{
get_compact_continuation_message, should_compact, CompactionConfig, CompactionResult, get_compact_continuation_message, should_compact, CompactionConfig, CompactionResult,
}; };
pub use config::{ pub use config::{
ConfigEntry, ConfigError, ConfigLoader, ConfigSource, McpManagedProxyServerConfig, ConfigEntry, ConfigError, ConfigLoader, ConfigSource, McpConfigCollection,
McpConfigCollection, McpOAuthConfig, McpRemoteServerConfig, McpSdkServerConfig, McpManagedProxyServerConfig, McpOAuthConfig, McpRemoteServerConfig, McpSdkServerConfig,
McpServerConfig, McpStdioServerConfig, McpTransport, McpWebSocketServerConfig, OAuthConfig, McpServerConfig, McpStdioServerConfig, McpTransport, McpWebSocketServerConfig, OAuthConfig,
ResolvedPermissionMode, RuntimeConfig, RuntimeFeatureConfig, RuntimeHookConfig, ResolvedPermissionMode, RuntimeConfig, RuntimeFeatureConfig, RuntimeHookConfig,
RuntimePluginConfig, ScopedMcpServerConfig, CLAW_SETTINGS_SCHEMA_NAME, RuntimePluginConfig, ScopedMcpServerConfig, CLAW_SETTINGS_SCHEMA_NAME,
@@ -44,12 +41,16 @@ pub use file_ops::{
WriteFileOutput, WriteFileOutput,
}; };
pub use hooks::{HookEvent, HookRunResult, HookRunner}; pub use hooks::{HookEvent, HookRunResult, HookRunner};
pub use lsp::{
FileDiagnostics, LspContextEnrichment, LspError, LspManager, LspServerConfig, SymbolLocation,
WorkspaceDiagnostics,
};
pub use mcp::{ pub use mcp::{
mcp_server_signature, mcp_tool_name, mcp_tool_prefix, normalize_name_for_mcp, mcp_server_signature, mcp_tool_name, mcp_tool_prefix, normalize_name_for_mcp,
scoped_mcp_config_hash, unwrap_ccr_proxy_url, scoped_mcp_config_hash, unwrap_ccr_proxy_url,
}; };
pub use mcp_client::{ pub use mcp_client::{
McpManagedProxyTransport, McpClientAuth, McpClientBootstrap, McpClientTransport, McpClientAuth, McpClientBootstrap, McpClientTransport, McpManagedProxyTransport,
McpRemoteTransport, McpSdkTransport, McpStdioTransport, McpRemoteTransport, McpSdkTransport, McpStdioTransport,
}; };
pub use mcp_stdio::{ pub use mcp_stdio::{
@@ -81,6 +82,10 @@ pub use remote::{
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS, DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
}; };
pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError}; pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError};
pub use skills::{
discover_skill_roots, resolve_skill_path, SkillDiscoveryRoot, SkillDiscoverySource,
SkillRootKind,
};
pub use usage::{ pub use usage::{
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker, format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
}; };

View File

@@ -0,0 +1,313 @@
use std::env;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SkillDiscoverySource {
ProjectCodex,
ProjectClaw,
UserCodexHome,
UserCodex,
UserClaw,
}
impl SkillDiscoverySource {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::ProjectCodex => "Project (.codex)",
Self::ProjectClaw => "Project (.claw)",
Self::UserCodexHome => "User ($CODEX_HOME)",
Self::UserCodex => "User (~/.codex)",
Self::UserClaw => "User (~/.claw)",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillRootKind {
SkillsDir,
LegacyCommandsDir,
}
impl SkillRootKind {
#[must_use]
pub const fn detail_label(self) -> Option<&'static str> {
match self {
Self::SkillsDir => None,
Self::LegacyCommandsDir => Some("legacy /commands"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillDiscoveryRoot {
pub source: SkillDiscoverySource,
pub path: PathBuf,
pub kind: SkillRootKind,
}
pub fn discover_skill_roots(cwd: &Path) -> Vec<SkillDiscoveryRoot> {
let mut roots = Vec::new();
for ancestor in cwd.ancestors() {
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::ProjectCodex,
ancestor.join(".codex").join("skills"),
SkillRootKind::SkillsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::ProjectClaw,
ancestor.join(".claw").join("skills"),
SkillRootKind::SkillsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::ProjectCodex,
ancestor.join(".codex").join("commands"),
SkillRootKind::LegacyCommandsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::ProjectClaw,
ancestor.join(".claw").join("commands"),
SkillRootKind::LegacyCommandsDir,
);
}
if let Ok(codex_home) = env::var("CODEX_HOME") {
let codex_home = PathBuf::from(codex_home);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::UserCodexHome,
codex_home.join("skills"),
SkillRootKind::SkillsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::UserCodexHome,
codex_home.join("commands"),
SkillRootKind::LegacyCommandsDir,
);
}
if let Some(home) = env::var_os("HOME") {
let home = PathBuf::from(home);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::UserCodex,
home.join(".codex").join("skills"),
SkillRootKind::SkillsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::UserCodex,
home.join(".codex").join("commands"),
SkillRootKind::LegacyCommandsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::UserClaw,
home.join(".claw").join("skills"),
SkillRootKind::SkillsDir,
);
push_unique_skill_root(
&mut roots,
SkillDiscoverySource::UserClaw,
home.join(".claw").join("commands"),
SkillRootKind::LegacyCommandsDir,
);
}
roots
}
pub fn resolve_skill_path(skill: &str, cwd: &Path) -> Result<PathBuf, String> {
let requested = normalize_requested_skill_name(skill)?;
for root in discover_skill_roots(cwd) {
match root.kind {
SkillRootKind::SkillsDir => {
let direct = root.path.join(&requested).join("SKILL.md");
if direct.is_file() {
return Ok(direct);
}
if let Ok(entries) = std::fs::read_dir(&root.path) {
for entry in entries.flatten() {
let path = entry.path().join("SKILL.md");
if !path.is_file() {
continue;
}
if entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case(&requested)
{
return Ok(path);
}
}
}
}
SkillRootKind::LegacyCommandsDir => {
let direct_markdown = root.path.join(format!("{requested}.md"));
if direct_markdown.is_file() {
return Ok(direct_markdown);
}
let direct_skill_dir = root.path.join(&requested).join("SKILL.md");
if direct_skill_dir.is_file() {
return Ok(direct_skill_dir);
}
if let Ok(entries) = std::fs::read_dir(&root.path) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let skill_path = path.join("SKILL.md");
if !skill_path.is_file() {
continue;
}
if entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case(&requested)
{
return Ok(skill_path);
}
continue;
}
if !path
.extension()
.is_some_and(|ext| ext.to_string_lossy().eq_ignore_ascii_case("md"))
{
continue;
}
let Some(stem) = path.file_stem() else {
continue;
};
if stem.to_string_lossy().eq_ignore_ascii_case(&requested) {
return Ok(path);
}
}
}
}
}
}
Err(format!("unknown skill: {requested}"))
}
fn normalize_requested_skill_name(skill: &str) -> Result<String, String> {
let requested = skill.trim().trim_start_matches('/').trim_start_matches('$');
if requested.is_empty() {
return Err(String::from("skill must not be empty"));
}
Ok(requested.to_string())
}
fn push_unique_skill_root(
roots: &mut Vec<SkillDiscoveryRoot>,
source: SkillDiscoverySource,
path: PathBuf,
kind: SkillRootKind,
) {
if path.is_dir() && !roots.iter().any(|existing| existing.path == path) {
roots.push(SkillDiscoveryRoot { source, path, kind });
}
}
#[cfg(test)]
mod tests {
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use super::{
discover_skill_roots, resolve_skill_path, SkillDiscoveryRoot, SkillDiscoverySource,
SkillRootKind,
};
fn temp_dir(label: &str) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock")
.as_nanos();
std::env::temp_dir().join(format!("runtime-skills-{label}-{nanos}"))
}
fn write_skill(root: &Path, name: &str) {
let skill_root = root.join(name);
fs::create_dir_all(&skill_root).expect("skill root");
fs::write(skill_root.join("SKILL.md"), format!("# {name}\n")).expect("write skill");
}
fn write_legacy_markdown(root: &Path, name: &str) {
fs::create_dir_all(root).expect("legacy root");
fs::write(root.join(format!("{name}.md")), format!("# {name}\n")).expect("write command");
}
#[test]
fn discovers_workspace_and_user_skill_roots() {
let _guard = crate::test_env_lock();
let workspace = temp_dir("workspace");
let nested = workspace.join("apps").join("ui");
let user_home = temp_dir("home");
fs::create_dir_all(&nested).expect("nested cwd");
fs::create_dir_all(workspace.join(".codex").join("skills")).expect("project codex skills");
fs::create_dir_all(workspace.join(".claw").join("commands"))
.expect("project claw commands");
fs::create_dir_all(user_home.join(".codex").join("skills")).expect("user codex skills");
std::env::set_var("HOME", &user_home);
std::env::remove_var("CODEX_HOME");
let roots = discover_skill_roots(&nested);
assert!(roots.contains(&SkillDiscoveryRoot {
source: SkillDiscoverySource::ProjectCodex,
path: workspace.join(".codex").join("skills"),
kind: SkillRootKind::SkillsDir,
}));
assert!(roots.contains(&SkillDiscoveryRoot {
source: SkillDiscoverySource::ProjectClaw,
path: workspace.join(".claw").join("commands"),
kind: SkillRootKind::LegacyCommandsDir,
}));
assert!(roots.contains(&SkillDiscoveryRoot {
source: SkillDiscoverySource::UserCodex,
path: user_home.join(".codex").join("skills"),
kind: SkillRootKind::SkillsDir,
}));
std::env::remove_var("HOME");
let _ = fs::remove_dir_all(workspace);
let _ = fs::remove_dir_all(user_home);
}
#[test]
fn resolves_workspace_skills_and_legacy_commands() {
let _guard = crate::test_env_lock();
let workspace = temp_dir("resolve");
let nested = workspace.join("apps").join("ui");
let original_dir = std::env::current_dir().expect("cwd");
fs::create_dir_all(&nested).expect("nested cwd");
write_skill(&workspace.join(".claw").join("skills"), "review");
write_legacy_markdown(&workspace.join(".codex").join("commands"), "deploy");
std::env::set_current_dir(&nested).expect("set cwd");
let review = resolve_skill_path("review", &nested).expect("workspace skill");
let deploy = resolve_skill_path("/deploy", &nested).expect("legacy command");
std::env::set_current_dir(&original_dir).expect("restore cwd");
assert!(review.ends_with(".claw/skills/review/SKILL.md"));
assert!(deploy.ends_with(".codex/commands/deploy.md"));
let _ = fs::remove_dir_all(workspace);
}
}

View File

@@ -8,15 +8,14 @@ use api::{
MessageRequest, MessageResponse, OutputContentBlock, ProviderClient, MessageRequest, MessageResponse, OutputContentBlock, ProviderClient,
StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock, StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
}; };
use plugins::{ use plugins::PluginTool;
load_plugin_from_directory, PluginManager, PluginManagerConfig, PluginSummary, PluginTool,
};
use reqwest::blocking::Client; use reqwest::blocking::Client;
use runtime::{ use runtime::{
edit_file, execute_bash, glob_search, grep_search, load_system_prompt, read_file, write_file, edit_file, execute_bash, glob_search, grep_search, load_system_prompt, read_file,
ApiClient, ApiRequest, AssistantEvent, BashCommandInput, ConfigLoader, ContentBlock, resolve_skill_path as resolve_runtime_skill_path, write_file, ApiClient, ApiRequest,
ConversationMessage, ConversationRuntime, GrepSearchInput, MessageRole, PermissionMode, AssistantEvent, BashCommandInput, ContentBlock, ConversationMessage, ConversationRuntime,
PermissionPolicy, RuntimeError, Session, TokenUsage, ToolError, ToolExecutor, GrepSearchInput, MessageRole, PermissionMode, PermissionPolicy, RuntimeError, Session,
TokenUsage, ToolError, ToolExecutor,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{json, Value}; use serde_json::{json, Value};
@@ -1465,391 +1464,9 @@ fn todo_store_path() -> Result<std::path::PathBuf, String> {
Ok(cwd.join(".claw-todos.json")) Ok(cwd.join(".claw-todos.json"))
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SkillRootKind {
Skills,
LegacyCommands,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SkillCandidate {
name: String,
path: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SkillCandidateRoot {
path: PathBuf,
kind: SkillRootKind,
name_prefix: Option<String>,
}
fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> { fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
let requested = skill.trim().trim_start_matches('/').trim_start_matches('$'); let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
if requested.is_empty() { resolve_runtime_skill_path(skill, &cwd)
return Err(String::from("skill must not be empty"));
}
let candidates = discover_skill_candidates().map_err(|error| error.to_string())?;
if let Some(candidate) = candidates
.iter()
.find(|candidate| candidate.name.eq_ignore_ascii_case(requested))
{
return Ok(candidate.path.clone());
}
let suffix = format!(":{requested}");
let suffix_matches = candidates
.iter()
.filter(|candidate| candidate.name.ends_with(&suffix))
.collect::<Vec<_>>();
match suffix_matches.as_slice() {
[candidate] => Ok(candidate.path.clone()),
[] => Err(format!("unknown skill: {requested}")),
matches => Err(format!(
"ambiguous skill `{requested}`; use one of: {}",
matches
.iter()
.map(|candidate| candidate.name.as_str())
.collect::<Vec<_>>()
.join(", ")
)),
}
}
fn discover_skill_candidates() -> std::io::Result<Vec<SkillCandidate>> {
let cwd = std::env::current_dir()?;
let mut roots = local_skill_candidate_roots(&cwd);
extend_plugin_skill_candidate_roots(&cwd, &mut roots);
let mut candidates = Vec::new();
for root in &roots {
collect_skill_candidates(root, &root.path, &mut candidates)?;
}
Ok(candidates)
}
fn local_skill_candidate_roots(cwd: &Path) -> Vec<SkillCandidateRoot> {
let mut roots = Vec::new();
for ancestor in cwd.ancestors() {
push_skill_candidate_root(
&mut roots,
ancestor.join(".codex").join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
ancestor.join(".claw").join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
ancestor.join(".codex").join("commands"),
SkillRootKind::LegacyCommands,
None,
);
push_skill_candidate_root(
&mut roots,
ancestor.join(".claw").join("commands"),
SkillRootKind::LegacyCommands,
None,
);
}
if let Ok(codex_home) = std::env::var("CODEX_HOME") {
let codex_home = PathBuf::from(codex_home);
push_skill_candidate_root(
&mut roots,
codex_home.join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
codex_home.join("commands"),
SkillRootKind::LegacyCommands,
None,
);
}
if let Ok(home) = std::env::var("HOME") {
let home = PathBuf::from(home);
push_skill_candidate_root(
&mut roots,
home.join(".agents").join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
home.join(".config").join("opencode").join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
home.join(".codex").join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
home.join(".claw").join("skills"),
SkillRootKind::Skills,
None,
);
push_skill_candidate_root(
&mut roots,
home.join(".codex").join("commands"),
SkillRootKind::LegacyCommands,
None,
);
push_skill_candidate_root(
&mut roots,
home.join(".claw").join("commands"),
SkillRootKind::LegacyCommands,
None,
);
}
push_skill_candidate_root(
&mut roots,
PathBuf::from("/home/bellman/.codex/skills"),
SkillRootKind::Skills,
None,
);
roots
}
fn extend_plugin_skill_candidate_roots(cwd: &Path, roots: &mut Vec<SkillCandidateRoot>) {
for plugin in enabled_plugins_for_cwd(cwd) {
let Some(root) = &plugin.metadata.root else {
continue;
};
push_skill_candidate_root(
roots,
root.join("skills"),
SkillRootKind::Skills,
Some(plugin.metadata.name.clone()),
);
if let Ok(manifest) = load_plugin_from_directory(root) {
for relative in manifest.skills {
let path = resolve_plugin_component_path(root, &relative);
let kind = if path
.extension()
.is_some_and(|ext| ext.to_string_lossy().eq_ignore_ascii_case("md"))
{
SkillRootKind::LegacyCommands
} else {
SkillRootKind::Skills
};
push_skill_candidate_root(roots, path, kind, Some(plugin.metadata.name.clone()));
}
}
}
}
fn push_skill_candidate_root(
roots: &mut Vec<SkillCandidateRoot>,
path: PathBuf,
kind: SkillRootKind,
name_prefix: Option<String>,
) {
if path.exists() && !roots.iter().any(|existing| existing.path == path) {
roots.push(SkillCandidateRoot {
path,
kind,
name_prefix,
});
}
}
fn collect_skill_candidates(
root: &SkillCandidateRoot,
path: &Path,
candidates: &mut Vec<SkillCandidate>,
) -> std::io::Result<()> {
if path.is_file() {
if let Some(candidate) = load_skill_candidate(root, path, &root.path)? {
candidates.push(candidate);
}
return Ok(());
}
let skill_md = path.join("SKILL.md");
if skill_md.is_file() {
if let Some(candidate) = load_skill_candidate(root, &skill_md, &root.path)? {
candidates.push(candidate);
}
return Ok(());
}
let mut entries = std::fs::read_dir(path)?.collect::<Result<Vec<_>, _>>()?;
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
let entry_path = entry.path();
if entry_path.is_dir() {
collect_skill_candidates(root, &entry_path, candidates)?;
} else if root.kind == SkillRootKind::LegacyCommands {
if let Some(candidate) = load_skill_candidate(root, &entry_path, &root.path)? {
candidates.push(candidate);
}
}
}
Ok(())
}
fn load_skill_candidate(
root: &SkillCandidateRoot,
path: &Path,
base_root: &Path,
) -> std::io::Result<Option<SkillCandidate>> {
if !path
.extension()
.is_some_and(|ext| ext.to_string_lossy().eq_ignore_ascii_case("md"))
{
return Ok(None);
}
let is_skill_file = path
.file_name()
.is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case("SKILL.md"));
if root.kind == SkillRootKind::Skills && !is_skill_file {
return Ok(None);
}
let name = skill_candidate_name(root, path, base_root, is_skill_file);
Ok(Some(SkillCandidate {
name,
path: path.to_path_buf(),
}))
}
fn skill_candidate_name(
root: &SkillCandidateRoot,
path: &Path,
base_root: &Path,
is_skill_file: bool,
) -> String {
let base_name = if is_skill_file {
path.parent().and_then(Path::file_name).map_or_else(
|| fallback_file_stem(path),
|segment| segment.to_string_lossy().to_string(),
)
} else {
fallback_file_stem(path)
};
prefixed_definition_name(
root.name_prefix.as_deref(),
namespace_for_file(path, base_root, is_skill_file),
&base_name,
)
}
fn namespace_for_file(path: &Path, base_root: &Path, is_skill_file: bool) -> Option<String> {
let relative_parent = if is_skill_file {
path.parent()
.and_then(Path::parent)
.and_then(|parent| parent.strip_prefix(base_root).ok())
} else {
path.parent()
.and_then(|parent| parent.strip_prefix(base_root).ok())
}?;
let segments = relative_parent
.iter()
.map(|segment| segment.to_string_lossy())
.filter(|segment| !segment.is_empty())
.map(|segment| segment.to_string())
.collect::<Vec<_>>();
(!segments.is_empty()).then(|| segments.join(":"))
}
fn prefixed_definition_name(
prefix: Option<&str>,
namespace: Option<String>,
base_name: &str,
) -> String {
let mut parts = Vec::new();
if let Some(prefix) = prefix.filter(|prefix| !prefix.is_empty()) {
parts.push(prefix.to_string());
}
if let Some(namespace) = namespace.filter(|namespace| !namespace.is_empty()) {
parts.push(namespace);
}
parts.push(base_name.to_string());
parts.join(":")
}
fn fallback_file_stem(path: &Path) -> String {
path.file_stem()
.map_or_else(String::new, |stem| stem.to_string_lossy().to_string())
}
fn enabled_plugins_for_cwd(cwd: &Path) -> Vec<PluginSummary> {
let Some(manager) = plugin_manager_for_cwd(cwd) else {
return Vec::new();
};
manager
.list_installed_plugins()
.map(|plugins| {
plugins
.into_iter()
.filter(|plugin| plugin.enabled)
.collect::<Vec<_>>()
})
.unwrap_or_default()
}
fn plugin_manager_for_cwd(cwd: &Path) -> Option<PluginManager> {
let loader = ConfigLoader::default_for(cwd);
let runtime_config = loader.load().ok()?;
let plugin_settings = runtime_config.plugins();
let mut plugin_config = PluginManagerConfig::new(loader.config_home().to_path_buf());
plugin_config.enabled_plugins = plugin_settings.enabled_plugins().clone();
plugin_config.external_dirs = plugin_settings
.external_directories()
.iter()
.map(|path| resolve_plugin_path(cwd, loader.config_home(), path))
.collect();
plugin_config.install_root = plugin_settings
.install_root()
.map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
plugin_config.registry_path = plugin_settings
.registry_path()
.map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
plugin_config.bundled_root = plugin_settings
.bundled_root()
.map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
Some(PluginManager::new(plugin_config))
}
fn resolve_plugin_path(cwd: &Path, config_home: &Path, value: &str) -> PathBuf {
let path = Path::new(value);
if path.is_absolute() {
path.to_path_buf()
} else if value.starts_with('.') {
cwd.join(path)
} else {
config_home.join(path)
}
}
fn resolve_plugin_component_path(root: &Path, value: &str) -> PathBuf {
let path = Path::new(value);
if path.is_absolute() {
path.to_path_buf()
} else {
root.join(path)
}
} }
const DEFAULT_AGENT_MODEL: &str = "claude-opus-4-6"; const DEFAULT_AGENT_MODEL: &str = "claude-opus-4-6";
@@ -3446,27 +3063,6 @@ mod tests {
std::env::temp_dir().join(format!("claw-tools-{unique}-{name}")) std::env::temp_dir().join(format!("claw-tools-{unique}-{name}"))
} }
fn write_skill(root: &std::path::Path, name: &str, description: &str) {
let skill_root = root.join(name);
fs::create_dir_all(&skill_root).expect("skill root");
fs::write(
skill_root.join("SKILL.md"),
format!("---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n"),
)
.expect("write skill");
}
fn write_plugin_manifest(root: &std::path::Path, name: &str, extra_fields: &str) {
fs::create_dir_all(root.join(".claw-plugin")).expect("manifest dir");
fs::write(
root.join(".claw-plugin").join("plugin.json"),
format!(
"{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"test plugin\"{extra_fields}\n}}"
),
)
.expect("write plugin manifest");
}
#[test] #[test]
fn exposes_mvp_tools() { fn exposes_mvp_tools() {
let names = mvp_tool_specs() let names = mvp_tool_specs()
@@ -3864,100 +3460,62 @@ mod tests {
} }
#[test] #[test]
fn skill_resolves_namespaced_plugin_skill_by_unique_suffix() { fn skill_resolves_workspace_skill_and_legacy_command() {
let _guard = env_lock() let _guard = env_lock()
.lock() .lock()
.unwrap_or_else(std::sync::PoisonError::into_inner); .unwrap_or_else(std::sync::PoisonError::into_inner);
let workspace = temp_path("skill-plugin-workspace"); let root = temp_path("workspace-skills");
let config_home = temp_path("skill-plugin-home"); let cwd = root.join("apps").join("ui");
let install_root = config_home.join("plugins").join("installed"); let original_dir = std::env::current_dir().expect("cwd");
let plugin_root = install_root.join("demo-plugin");
fs::create_dir_all(&config_home).expect("config home"); std::fs::create_dir_all(root.join(".claw").join("skills").join("review"))
fs::write( .expect("workspace skill dir");
config_home.join("settings.json"), std::fs::write(
r#"{"plugins":{"enabled":{"demo-plugin@external":true}}}"#, root.join(".claw")
.join("skills")
.join("review")
.join("SKILL.md"),
"---\ndescription: Workspace review guidance\n---\n# review\n",
) )
.expect("write settings"); .expect("write workspace skill");
write_plugin_manifest(&plugin_root, "demo-plugin", ",\n \"defaultEnabled\": true"); std::fs::create_dir_all(root.join(".codex").join("commands")).expect("legacy root");
write_skill( std::fs::write(
&plugin_root.join("skills").join("ops"), root.join(".codex").join("commands").join("deploy.md"),
"review", "---\ndescription: Deploy command guidance\n---\n# deploy\n",
"Plugin review guidance",
);
fs::create_dir_all(&workspace).expect("workspace");
let previous_cwd = std::env::current_dir().expect("cwd");
let previous_claw_config_home = std::env::var_os("CLAW_CONFIG_HOME");
std::env::set_var("CLAW_CONFIG_HOME", &config_home);
std::env::set_current_dir(&workspace).expect("set cwd");
let result = execute_tool("Skill", &json!({ "skill": "review" }))
.expect("plugin skill should resolve");
let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
let expected_path = plugin_root
.join("skills/ops/review/SKILL.md")
.display()
.to_string();
assert_eq!(output["path"].as_str(), Some(expected_path.as_str()));
std::env::set_current_dir(previous_cwd).expect("restore cwd");
if let Some(value) = previous_claw_config_home {
std::env::set_var("CLAW_CONFIG_HOME", value);
} else {
std::env::remove_var("CLAW_CONFIG_HOME");
}
let _ = fs::remove_dir_all(workspace);
let _ = fs::remove_dir_all(config_home);
}
#[test]
fn skill_reports_ambiguous_bare_name_for_multiple_namespaced_matches() {
let _guard = env_lock()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let workspace = temp_path("skill-ambiguous-workspace");
let config_home = temp_path("skill-ambiguous-home");
let install_root = config_home.join("plugins").join("installed");
let plugin_root = install_root.join("demo-plugin");
fs::create_dir_all(&config_home).expect("config home");
fs::write(
config_home.join("settings.json"),
r#"{"plugins":{"enabled":{"demo-plugin@external":true}}}"#,
) )
.expect("write settings"); .expect("write legacy command");
write_skill( std::fs::create_dir_all(&cwd).expect("cwd");
&workspace.join(".codex").join("skills").join("ops"),
"review", std::env::set_current_dir(&cwd).expect("set cwd");
"Local review",
let workspace_skill = execute_tool("Skill", &json!({ "skill": "review" }))
.expect("workspace skill should resolve");
let workspace_output: serde_json::Value =
serde_json::from_str(&workspace_skill).expect("valid json");
assert_eq!(
workspace_output["description"].as_str(),
Some("Workspace review guidance")
); );
write_plugin_manifest(&plugin_root, "demo-plugin", ",\n \"defaultEnabled\": true"); assert!(workspace_output["path"]
write_skill( .as_str()
&plugin_root.join("skills").join("ops"), .expect("path")
"review", .ends_with(".claw/skills/review/SKILL.md"));
"Plugin review guidance",
let legacy_skill = execute_tool("Skill", &json!({ "skill": "/deploy" }))
.expect("legacy command should resolve");
let legacy_output: serde_json::Value =
serde_json::from_str(&legacy_skill).expect("valid json");
assert_eq!(
legacy_output["description"].as_str(),
Some("Deploy command guidance")
); );
assert!(legacy_output["path"]
.as_str()
.expect("path")
.ends_with(".codex/commands/deploy.md"));
let previous_cwd = std::env::current_dir().expect("cwd"); std::env::set_current_dir(&original_dir).expect("restore cwd");
let previous_claw_config_home = std::env::var_os("CLAW_CONFIG_HOME"); let _ = std::fs::remove_dir_all(root);
std::env::set_var("CLAW_CONFIG_HOME", &config_home);
std::env::set_current_dir(&workspace).expect("set cwd");
let error = execute_tool("Skill", &json!({ "skill": "review" }))
.expect_err("review should be ambiguous");
assert!(error.contains("ambiguous skill `review`"));
assert!(error.contains("ops:review"));
assert!(error.contains("demo-plugin:ops:review"));
std::env::set_current_dir(previous_cwd).expect("restore cwd");
if let Some(value) = previous_claw_config_home {
std::env::set_var("CLAW_CONFIG_HOME", value);
} else {
std::env::remove_var("CLAW_CONFIG_HOME");
}
let _ = fs::remove_dir_all(workspace);
let _ = fs::remove_dir_all(config_home);
} }
#[test] #[test]