Compare commits

...

141 Commits

Author SHA1 Message Date
YeonGyu-Kim
08106b0c37 docs: add hierarchical AGENTS.md knowledge base
Root knowledge base plus complexity-scored subdirectory files for the
rust/ workspace, its five highest-mass crates (runtime, rusty-claude-cli,
api, tools, commands, plugins), and the src/ Python porting workspace.

Generated via init-deep: 13 parallel explore agents, LSP/ast-grep code
map, centrality-scored placement. Snapshot in .omo/init-deep.json (local).
2026-08-16 15:18:33 +09:00
YeonGyu-Kim
b71afddae1 Merge pull request #3280 from Einspanner123/fix/sandbox-map-auto-fallback
fix(sandbox): fall back to --map-auto when root-user mapping is restricted
2026-08-06 20:18:35 +09:00
code-yeongyu
525035b51b fix(sandbox): probe the full launcher shape, not just the mapping
The startup probe validated only the mapping flags against the trivial
program `true`, but the real launcher always adds
--mount --ipc --pid --uts --fork. On environments where the user
namespace is created but mount propagation inside it is restricted
(e.g. AppArmor-restricted CI runners), the fallback mapping passed the
probe and the sandbox activated, yet every sandboxed command died with
"cannot change root filesystem propagation: Permission denied",
silently returning empty tool output and breaking the mock parity
suite.

The candidates now define the complete static launcher shape (mapping
flags + namespace flags), so probe success implies launch success; the
launcher reuses the candidate instead of re-appending the namespace
flags, keeping probe and launch as one source of truth. The
order-guarding test asserts the namespace flags are present in every
candidate.

Co-authored-by: linkst <2024023709@m.scnu.edu.cn>
2026-08-06 19:41:27 +09:00
linkst
9cbe6d9a8c docs(sandbox): document newuidmap/newgidmap dependency for --map-auto fallback
The fallback candidate relies on the setuid newuidmap/newgidmap helpers
(uidmap package) plus a subuid/subgid range for the current user. Note in
the candidate docs that the startup probe rejects the candidate when those
are missing, so the plain --map-root-user form is used instead.
2026-08-01 15:21:56 +08:00
linkst
277fdda894 fix(sandbox): fall back to --map-auto when root-user mapping is restricted
Plain `unshare --user --map-root-user` fails on kernels and containers
that block unprivileged writes to /proc/self/uid_map (e.g. GitHub Actions,
restricted AppArmor profiles). On those systems util-linux delegates to the
setuid newuidmap/newgidmap helpers when --map-auto is also present.

Add the combined form as a fallback candidate and build the launcher args
from the probed mapping, so systems without newuidmap/newgidmap or a
/etc/subuid range keep using the plain form.
2026-07-31 17:09:00 +08:00
linkst
1c8338ea66 refactor(sandbox): extract unshare mapping probe into cached helper
No behavior change. Move the inline probe out of
unshare_user_namespace_works into a reusable unshare_probe helper and a
cached working_unshare_mapping() that picks the first working candidate
from UNSHARE_MAPPING_CANDIDATES, so the launcher and the capability probe
share one code path.
2026-07-31 17:08:51 +08:00
Sigrid Jin (ง'̀-'́)ง oO
4ea31c1bc9 Merge pull request #3253 from EmreCelenli/docs/mlx-compatibility
docs: document mlx-lm backend for Apple Silicon and known gotchas
2026-06-27 01:17:10 +09:00
Sigrid Jin (ง'̀-'́)ง oO
4e0cba76cc Merge pull request #3263 from hiisandog/fix/claw-small-cleanup-c6b25
Improve command lookup normalization
2026-06-27 01:16:51 +09:00
陈家名
5babda196b Improve command lookup normalization 2026-06-25 15:43:30 +08:00
EmreCelenli
3ae922508c docs: document mlx-lm backend and known model-resolution/EOS gotchas 2026-06-18 18:36:39 +02:00
YeonGyu-Kim
d229a9b022 Merge pull request #3227 from TheArchitectit/worktree-wizard-entry-points
feat: wizard entry points — /setup command, claw setup subcommand (rebased)
2026-06-08 15:06:11 +09:00
YeonGyu-Kim
05f0201ec7 fix: preserve runtime config validation compatibility 2026-06-08 15:01:48 +09:00
YeonGyu-Kim
36f6afcafd Merge pull request #3230 from Gaurav-x111/contributor/example-change
docs: add interactive session example to quick start
2026-06-08 14:44:43 +09:00
YeonGyu-Kim
2e52ea7a67 Merge pull request #3237 from hiisandog/fix/redirection-path-scope-20260608
fix: validate attached redirection paths
2026-06-08 14:43:52 +09:00
陈家名
eb21179dde fix: validate attached redirection paths 2026-06-08 10:18:48 +08:00
YeonGyu-Kim
9b3548ca43 Merge pull request #3236 from ultraworkers/fix/ollama-qwen-reasoning-field
fix: parse Ollama reasoning fields
2026-06-08 10:11:52 +09:00
YeonGyu-Kim
01f4dd48a3 docs: mention local Ollama reasoning setup 2026-06-08 10:08:44 +09:00
YeonGyu-Kim
222faabd7f fix(cli): hint Ollama for Qwen tags 2026-06-08 10:08:38 +09:00
YeonGyu-Kim
7503c1c031 fix(providers): parse Ollama reasoning fields 2026-06-08 10:08:32 +09:00
YeonGyu-Kim
6001156a6c Merge pull request #3234 from ultraworkers/fix/openai-compatible-reasoning-history
fix(providers): preserve OpenAI-compatible reasoning history
2026-06-08 09:27:33 +09:00
YeonGyu-Kim
a1da1ca8e6 test(cli): serialize env-sensitive model alias checks 2026-06-08 01:37:28 +09:00
YeonGyu-Kim
27acfe1014 test(runtime): isolate session and git metadata checks 2026-06-08 01:23:32 +09:00
YeonGyu-Kim
c1646613d1 fix(providers): preserve OpenAI-compatible reasoning history 2026-06-08 01:23:13 +09:00
Sigrid Jin (ง'̀-'́)ง oO
ae2f203eb5 Merge pull request #3232 from Ajinkya-Ghuge/fix/deepseek-model-routing 2026-06-07 18:40:11 +09:00
Ajinkya-Ghuge
0755ddff3c fix(providers): strip provider prefix from model names for openai_compat endpoints 2026-06-06 22:29:59 +05:30
Gaurav-x111
db9ff49256 docs: add interactive session example to quick start
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 22:25:55 +05:45
Sigrid Jin (ง'̀-'́)ง oO
3acb677d70 Update README.md 2026-06-06 18:16:58 +09:00
Sigrid Jin (ง'̀-'́)ง oO
43eac8fbec Update README.md 2026-06-06 18:16:26 +09:00
Sigrid Jin (ง'̀-'́)ง oO
c8505092f8 update readme 2026-06-06 18:14:04 +09:00
bellman
eaa2e320d9 docs: add ROADMAP #833 — native Ollama provider support via OLLAMA_HOST 2026-06-05 12:27:08 +09:00
bellman
be8112f5f5 feat: add native Ollama provider support via OLLAMA_HOST env var
- OLLAMA_HOST takes priority over OPENAI_BASE_URL for local Ollama instances
- No API key required; placeholder token used for Authorization header
- Model names like 'qwen3:8b' bypass strict provider/model syntax validation
- detect_provider_kind() checks OLLAMA_HOST first in routing cascade
- ProviderClient dispatch uses from_ollama_env() when OLLAMA_HOST is set
- Updated USAGE.md and docs with OLLAMA_HOST as preferred env var
- Added OLLAMA_CONFIG constant and from_ollama_env() to openai_compat
- Added test_ollama_host_bypasses_model_validation unit test
- Supersedes PR #3213 (which had a duplicate if-let bug in mod.rs)
2026-06-05 12:12:56 +09:00
TheArchitectit
d58197cca4 fix: update slash command count and add /setup assertion in test
- Update slash_command_specs().len() assertion from 139 to 140.
  The /setup command added by this PR increased the spec count by 1
  but the test's expected count was not updated, causing CI failure.

- Add assert!(help.contains("/setup")) to the
  renders_help_from_shared_specs test so the new command is
  verified in the help output.

  Fixes CI Build  and Test  on #3218.
2026-06-04 22:06:32 -05:00
Your Name
3845040b9d feat: wizard entry points -- /setup command, claw setup subcommand, and RuntimeProviderConfig
The setup wizard was merged in PR #3017 but was orphaned -- it was not
declared as a module in main.rs, making it unreachable. Additionally,
the setup_wizard.rs imports RuntimeProviderConfig which did not exist
on upstream/main. This commit makes the wizard accessible and adds the
necessary RuntimeProviderConfig type.

Changes:
- Add RuntimeProviderConfig struct to runtime/src/config.rs with
  kind(), api_key(), base_url(), model() accessors.
- Add parse_optional_provider_config() to parse the provider object
  from merged settings JSON.
- Add provider() method to RuntimeConfig and RuntimeFeatureConfig.
- Export RuntimeProviderConfig, save_user_provider_settings,
  clear_user_provider_settings, and default_config_home from runtime
  crate public API (runtime/src/lib.rs).
- Add mod setup_wizard to rusty-claude-cli/src/main.rs.
- Add claw setup CLI subcommand.
- Add /setup slash command.
- Add Setup variant to SlashCommand enum.
- Add Setup to LocalHelpTopic enum.
- Add setup to diagnostic subcommand matching.
- Add subagentModel to TOP_LEVEL_FIELDS in config_validate.rs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 21:52:48 -05:00
bellman
503d515f38 style: cargo fmt after merged PRs (#3164, #3209, #3214, #3216)
Fix formatting inconsistencies introduced by merged external PRs.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:52:37 +09:00
Bellman
114c2da9fc Merge pull request #3216 from TheArchitectit/worktree-session-resume-fixes
fix: session resume — scan all workspaces, skip current empty session
2026-06-05 10:38:19 +09:00
Bellman
b90f18f75a Merge pull request #3214 from TheArchitectit/worktree-api-timeout-retry-v2
feat: API timeout config, Retry-After header, configurable retry, and 400 transient retry
2026-06-05 10:33:35 +09:00
Bellman
5b15197117 Merge pull request #3209 from Sam0urr/harden-permission-enforcer
Harden permission enforcement against sandbox bypasses
2026-06-05 10:32:50 +09:00
bellman
61e8ad9a8e docs: add gajae-code to Ecosystem section
Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:27:06 +09:00
Bellman
ef0d0c30a4 Merge pull request #3164 from petterreinholdtsen/llama.cpp-errors
fix: recover from llama.cpp context overflow and reqwest SSE decode failures
2026-06-05 10:25:54 +09:00
bellman
7305e5509a fix: update skills help test assertions for --project flag (#95 CI fix)
Updated the agents_and_skills_usage_support_help_and_unexpected_args
test to match the new skills help text that includes [--project].

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:23:36 +09:00
bellman
2f0b5b36eb fix: wrap concurrent ENOENT as domain-specific session error (#112)
Session save_to_path now wraps ENOENT errors from rotate and atomic
write with a clear "possible concurrent modification" message instead
of surfacing raw OS errno. Helps operators debugging race conditions
when multiple claw invocations touch the same session file.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:19:43 +09:00
bellman
c848eeb768 fix: status JSON reports all workspace panes not just the first (#326)
SessionLifecycleSummary now collects all matching tmux panes into an
all_panes field and includes them in the JSON output. Previously the
status command returned on the first non-idle pane, losing all other
active panes in the same workspace/session.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:15:23 +09:00
bellman
d4aad7103e fix: add actionable auth hint to 401/403 API errors (#28)
401 and 403 errors now include a hint explaining which env vars to
check for each provider (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)
and suggesting claw doctor for credential verification.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:10:24 +09:00
bellman
b60cbebb3a feat: skills install --project flag for project-level scope (#95)
claw skills install --project <path> now installs to .claw/skills/
in the current project instead of the user-level registry. Skills
installed at project level are already discovered by the existing
registry system. Both text and JSON handlers updated.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:05:36 +09:00
bellman
7c4bcd92b6 fix: expand ${VAR} and ~/ in MCP config fields (#92)
MCP server config now expands ${VAR} environment variable references
and ~/ home directory prefix in command, args, and url fields. Previously
these values were passed verbatim to execve/URL-parse, causing silent
"No such file or directory" failures for standard config patterns.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 10:00:45 +09:00
bellman
f8822aabdb fix: config merge concatenates arrays instead of replacing (#106)
deep_merge_objects now concatenates arrays when both layers provide
the same key. Previously permissions.allow, hooks.PreToolUse, etc.
from earlier config layers (e.g. ~/.claw/settings.json) were silently
discarded when a later layer (e.g. project .claw/settings.json) set
the same key. Now arrays are merged additively across layers.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 09:57:22 +09:00
bellman
aca6584fd5 fix: normalize permission rule tool names to lowercase (#94)
PermissionRule::parse now normalizes tool_name to lowercase, matching
the runtime convention. Previously "Bash(rm:*)" would never match
because the runtime tool name is lowercase "bash". Same fix applied
to denied_tools list.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 09:53:26 +09:00
bellman
b8cbb1834f fix: /clear preserves session_id to prevent resume divergence (#114)
/resume mode /clear now preserves the original session_id instead of
generating a new one. This prevents the filename/meta-header divergence
where /session list reported an id that --resume couldn't find.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 09:47:37 +09:00
bellman
cb027adf65 fix: /session switch and /session fork return structured JSON in resume mode (#113)
/session switch and /session fork now return structured JSON with
kind:error, error_kind:unsupported_resumed_command, and actionable
hint instead of a raw error string that resume callers couldn't parse.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 09:42:16 +09:00
bellman
5bdffbe161 docs: mark ROADMAP #330 DONE (verified /cost and /stats work in resume)
Verified with a roundtrip test: creating a session with usage data
({input_tokens:100, output_tokens:50}), saving to JSONL, loading via
--resume, and running /cost and /stats both return correct values.
The UsageTracker::from_session reads message.usage which is properly
serialized/deserialized by ConversationMessage::to_json/from_json.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 09:32:23 +09:00
bellman
04f18862a8 fix: strip macOS /private symlink prefix from JSON cwd (#421)
Add friendly_cwd() helper that strips /private prefix on macOS so
status, doctor, and diff JSON output matches user-visible invocation
cwd instead of the canonicalized /private/tmp path.

Applied to status_context() and render_doctor_report().

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 09:08:09 +09:00
bellman
f0e10ff182 docs: mark ROADMAP #342 DONE (covered by #325)
342: /commands command-index alias is now covered by /help --output-format
json which returns structured commands array with 139 entries (name,
summary, resume_supported per command). Implemented in #325.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 08:56:25 +09:00
bellman
0cab03df75 fix: /model returns structured JSON in resume mode (#343)
/model was in the unsupported resume group but is a read-only command
that can safely return model configuration. Now returns default_model,
configured_model, resolved_model, and requested_model in JSON mode.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 08:54:11 +09:00
bellman
eb86f4d2c3 fix: reject --compact for non-prompt subcommands (#98)
--compact was silently ignored when used with non-prompt commands like
claw --compact status or claw --compact config. Now returns a typed
error with guidance on proper usage.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 07:25:49 +09:00
bellman
6c3d7be370 fix: /tasks returns structured JSON in resume mode (#341)
/tasks was marked resume_supported but rejected in resume mode.
Now returns a structured JSON response with kind:'tasks' and note
that background tasks are only available in the interactive REPL.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 07:15:36 +09:00
bellman
e3ffaefba1 fix: /config help returns structured section list (#344)
- /config help now returns available_sections array and loaded_keys
  count instead of treating 'help' as an unsupported section
- Updated test to exclude 'help' from unsupported sections test
- Added new test config_help_returns_structured_section_list_344

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 07:09:48 +09:00
bellman
cd18cf5385 fix: /config help returns structured section list (#344)
/config help now returns a list of available config sections in both
text and JSON mode instead of treating 'help' as an unsupported section.

Text mode shows available sections with descriptions.
JSON mode returns available_sections array with loaded_keys count.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 07:05:16 +09:00
bellman
2f3120e70a fix: add structured command list to top-level help JSON (#325)
Top-level 'claw --output-format json help' now includes a 'commands'
array with name, summary, and resume_supported for each registered
slash command, plus 'total_commands' count.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:57:51 +09:00
bellman
f1a16398fe fix: plugins enable/disable only reloads when state changes (#411)
plugins enable now checks if the plugin was already enabled before
setting reload_runtime:true. Same for disable. Returns 'already enabled'
or 'already disabled' in the message when no state change occurred.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:49:01 +09:00
bellman
8d50276366 docs: mark ROADMAP #339 DONE (/session delete resume-safe)
339: /session delete works in resume mode with --force flag. The
confirmation-required path returns a typed JSON error with hint.
delete-force path performs actual deletion with proper JSON response.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:40:48 +09:00
bellman
13992ade54 docs: mark ROADMAP #129 DONE (verified code flow)
129: MCP server startup does not block credential validation - credentials
are resolved via resolve_cli_auth_source() before build_runtime() which
is where MCP state discovery happens.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:33:20 +09:00
bellman
b04b1d6ac8 feat: detect git rebase/merge/cherry-pick/bisect states (#89)
Add GitOperation enum to detect mid-operation git states from the
branch header in git status --short --branch output.

- Rebase: 'rebasing ...' in branch header
- Merge: '[merge-in-progress]' tag
- Cherry-pick: 'cherry-pick-in-progress' tag
- Bisect: 'bisect-in-progress' tag

Operation state appears in:
- status text: 'rebase-in-progress, dirty · 3 files · ...'
- status JSON: 'git_operation' field (null when no operation)
- git_state headline includes operation prefix

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:31:33 +09:00
bellman
934bf2837a fix: validate --base-commit is a hex SHA (#122)
--base-commit now rejects non-hex strings and strings outside 7-64
character range. Matches the pattern used by --reasoning-effort.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:21:24 +09:00
bellman
b94c49c323 fix: use existing path in system-prompt test (#99 fix regression)
The --cwd validation added in #99 rejects non-existent paths, but the
test used /tmp/project which doesn't exist on CI Linux runners. Changed
to /tmp which exists everywhere.

Also marks ROADMAP #123 DONE (--allowedTools normalization verified).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:13:25 +09:00
bellman
5df485cba9 docs: mark ROADMAP #120,121 DONE
120: config parse errors now surfaced via load_error with hint
121: hooks already uses PreToolUse/PostToolUse/Claude Code format

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 06:05:36 +09:00
bellman
c8e973513c fix: redact MCP server sensitive fields in JSON (#90)
MCP server details JSON now redacts args (shows count only),
strips URL query params which may contain tokens, and shows
headers_helper as configured/not-configured boolean instead of
the raw command string. env_keys and header_keys still exposed
(key names only, not values).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:59:52 +09:00
bellman
8f9315bdc9 docs: mark ROADMAP #32,43 DONE with runtime evidence
32: OpenAI model passthrough verified (model: openai/gpt-4, source: flag)
43: Hook ingress opacity fixed (hook_validation structured in status JSON)

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:51:18 +09:00
bellman
12a091afe6 docs: mark ROADMAP #111,115 DONE
111: /providers routes to doctor slash command
115: init generates acceptEdits not dontAsk

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:48:42 +09:00
bellman
9f0cf3b888 docs: mark ROADMAP #101,104 DONE
101: RUSTY_CLAUDE_PERMISSION_MODE normalize maps aliases to valid modes
104: export CLI path and slash command both return kind:export

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:46:04 +09:00
bellman
6e94c1a97f docs: mark ROADMAP #93,109 DONE
93: --resume /tmp returns typed invalid_resume_argument error
109: config validation emits structured ConfigDiagnostic + warnings[]

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:40:50 +09:00
bellman
38626cad20 docs: mark ROADMAP #85,88,125,126 DONE
85: skills discovery bounded by git root (nearest_git_root in prompt.rs)
88: instruction file discovery bounded by git root
125: git_state reports 'no_git_repo' when not in git repo
126: config section exposes 'merged' key-value pairs

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:36:41 +09:00
bellman
e84f7c8034 fix: report 'no_git_repo' instead of 'clean' when not in git (#125)
status/doctor JSON now reports git_state:'no_git_repo' when
project_root is None, instead of the misleading 'clean' which
implied a git repo was present with zero changes.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:34:56 +09:00
bellman
b8f066347b fix: structured bootstrap-plan phases JSON (#412)
bootstrap-plan --output-format json now returns phases as structured
objects with id, label, description, and order fields instead of
raw Rust enum variant name strings. Also exposes total_phases count.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:29:27 +09:00
bellman
5adc751053 docs: mark ROADMAP #97 DONE
97: empty --allowedTools is unrestricted (no restrictions = default mode)

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:24:15 +09:00
bellman
adf5bd165e fix: validate --cwd and --date for system-prompt (#99)
--cwd now validates the path exists and is a directory before passing
it to the system prompt renderer. --date rejects values with newlines
or >20 chars to prevent prompt injection.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:18:31 +09:00
bellman
b220366176 docs: mark ROADMAP 81-83,87,91,102,117,128 DONE with direct evidence
81: project_root correctly reports per-CWD paths
82: sandbox correctly reports macOS degraded state (filesystem_active + unsupported)
83: system-prompt --date parameter works correctly
87: default permission_mode is workspace-write from config
91: permission mode aliases resolve to valid modes
102: config-time MCP check is by design for local preflight
117: -p flag parses single token correctly
128: validate_model_syntax rejects malformed models with hints

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:10:08 +09:00
bellman
b5d67ef249 docs: mark ROADMAP #105,118 DONE
105: status reads model from .claw.json config (model_source: config)
118: /stats and /tokens both route to stats handler

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:04:27 +09:00
bellman
9a40568e1c docs: mark ROADMAP #80,86,100 DONE
80: session lookup error now returns session_not_found with hint
86: .claw.json invalid JSON handled gracefully by config loader
100: binary_provenance exposes git_sha, build_date in status JSON

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:02:30 +09:00
bellman
41b3566468 fix: update resume help test for message field parity (#338)
Changed resumed_help_command_emits_structured_json to assert 'message'
field instead of 'text', matching the #338 fix for help JSON field
consistency.

Also marked ROADMAP #340 and #345 DONE with direct runtime evidence:
340: resume /session help now routes JSON to stdout (verified)
345: resume /config <section> now returns section-specific JSON (verified)

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 05:01:05 +09:00
bellman
b86159cbb7 docs: mark ROADMAP #124,127 DONE with direct evidence
124: validate_model_syntax already rejects empty, spaces, and invalid formats
127: subcommand --json already routes to local JSON handlers

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:56:06 +09:00
bellman
5e5b9966c0 docs: mark 8 ROADMAP items DONE (78,84,103,107,108,110,116,119)
78: plugins CLI wired as CliAction::Plugins (verified runtime)
84: dump-manifests fixed 2026-06-03
103: agents discovery handles .md with YAML frontmatter (#442)
107: hook validation in doctor JSON (verified runtime)
108: CLI typos → command_not_found (verified runtime)
110: ConfigLoader discovers project/user/local configs
116: unknown keys now emit warnings not errors (#441)
119: bare_slash_command_guidance checks aliases (#772)

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:52:40 +09:00
bellman
33f771f3f5 docs: mark ROADMAP #77 DONE (classify_error_kind implemented)
Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:51:16 +09:00
bellman
3fbfcc40ca docs: mark ROADMAP 327,328,408,6 DONE with fix evidence
327: mcp help now includes .claw.json in sources list
328: agents help now includes ~/.codex/agents in sources list
408: status JSON now has is_clean boolean field
6: terminal is transport principle — implementation tracked by #810-#816

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:47:58 +09:00
bellman
c7c5c11d1e fix: correct help source lists, add is_clean to status JSON
#327: mcp help now includes .claw.json in documented sources list
#328: agents help now includes ~/.codex/agents in documented sources list
#408: added is_clean boolean to status JSON workspace for unambiguous
  dirty-state detection; changed_files documented as total non-clean count
#338: resume help field consistency (committed earlier)

Also marked 52 items with explicit done/verified evidence as DONE
in ROADMAP.md, including product principles (1-6) and items with
confirmed fix text (13-75, 96, 200).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:46:10 +09:00
bellman
c0447e2be1 docs: mark ROADMAP 338,410 DONE with fix evidence
338: resume help now uses 'message' field consistent with top-level help
410: mcp and skills list now expose 'count' field for polymorphic consumption

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:35:51 +09:00
bellman
1b22ed700a fix: standardize list command count fields and resume help field name
#410: Added  field to mcp list and skills list JSON for
polymorphic consumption parity with agents list. All three sibling
list commands now expose a canonical  integer field alongside
their command-specific details.

#338: Changed resume  JSON from  to  field for
consistency with top-level .

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:34:59 +09:00
bellman
76f9a134ae docs: mark 16 ROADMAP items as DONE with direct verification evidence
Items verified with direct runtime evidence:
- #7: plugins CLI wired as CliAction::Plugins
- #77: classify_error_kind exists with 69 references
- #90: error envelopes carry machine-readable hint field
- #119: bare_slash_command_guidance checks aliases
- #346: agents show returns agent_not_found error
- #348: plugins list returns structured plugins[] array
- #349: plugins show returns plugin_not_found error
- #350: plugins enable returns typed error (not hang)
- #351: plugins disable returns typed error on stdout
- #352: plugins update returns typed error on stdout
- #353: plugins uninstall returns typed error on stdout
- #354: memory list returns interactive_only error
- #355: session list returns structured JSON
- #358: cost --help returns command_not_found
- #380: tokens --help returns command_not_found
- #381: cache --help returns command_not_found

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:27:24 +09:00
bellman
9c11325e83 docs: mark additional pre-440 ROADMAP items as DONE
Items verified against current codebase: 322, 323, 329, 337, 422 and
10 early items with confirmed fix evidence.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:23:02 +09:00
bellman
4708ab1611 fix: add structured help JSON and provider BASE_URL validation
#683-#692: help topic JSON now includes usage, purpose, formats,
related, local_only, requires_credentials, and aliases extracted
from help prose. Export and doctor keep their custom structured
responses.

#466: new check_base_url_health() validates ANTHROPIC_BASE_URL,
OPENAI_BASE_URL, XAI_BASE_URL, and DASHSCOPE_BASE_URL for basic
HTTP(S) URL format. Non-http schemes and empty values produce a
warn-level diagnostic.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 04:14:08 +09:00
bellman
311e719e5d docs: mark ROADMAP 696-697 DONE
696: compact returns interactive_only error in non-interactive mode
697: plugins uninstall already returns typed not-found error

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 03:49:31 +09:00
bellman
b926a9d25f docs: mark ROADMAP 713-716,723,734-735,737,767,771,774-776,781 as DONE
14 items with verified fixes marked as DONE.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 03:45:14 +09:00
bellman
61d641d722 style: apply cargo fmt
Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 03:41:35 +09:00
bellman
2f8679bd15 fix: track duplicate global flags in status JSON
status --output-format json now exposes duplicate_flags array listing
any --model, --output-format, or --permission-mode flags specified
more than once. Uses a module-level static for cross-function access.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 03:36:16 +09:00
bellman
9ef21e23f3 fix: expose merged key-value pairs in config JSON
render_config_json now includes a 'merged' object with actual
key-value pairs from the resolved runtime configuration, not just
the count.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 03:12:19 +09:00
bellman
6ac0386094 docs: close ROADMAP 335 evidence
335: session_details already includes created_at_ms

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:50:54 +09:00
bellman
4c939c0ad6 docs: close ROADMAP 465 evidence
465: doctor auth check now exposes openai_key_present

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:48:27 +09:00
bellman
4d41ab37e1 fix: expose openai_key_present in doctor auth check
check_auth_health data fields now include openai_key_present alongside
api_key_present and auth_token_present. any_auth_present already
includes OPENAI_API_KEY for prompt_ready status.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:46:24 +09:00
bellman
662a50bdc0 docs: close ROADMAP 347,356,357 evidence
347: mcp show missing returns status:error
356: status --help returns JSON
357: doctor --help returns JSON

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:38:38 +09:00
bellman
1da4aa454f docs: close ROADMAP 413,416 evidence
413: ACP JSON no longer leaks tracking IDs
416: plugins list returns structured plugins[] array

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:34:20 +09:00
bellman
3f50f33407 fix: filter boundary sentinel from system-prompt sections JSON
__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__ is now filtered from the sections
array in JSON output. boundary_index field exposed for callers that
need the static/dynamic split point.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:32:14 +09:00
bellman
0ce4168c93 docs: close ROADMAP 419-420 evidence
419: MCP unknown sub-actions return typed error with exit 1
420: plugins help returns standard help envelope

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:25:12 +09:00
bellman
7f1dd0c116 docs: close ROADMAP 700-704 evidence
700: help JSON already has status field
701: doctor details already structured {key,value}
702: agents/skills both use source field
703: plugins list has structured summary
704: doctor checks have stable id field

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:21:07 +09:00
bellman
42f56e7f77 docs: close ROADMAP 458-459 evidence
458: status field now universal across all JSON envelopes
459: memory file discovery expanded with AGENTS.md/.claude/CLAUDE.md

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:17:37 +09:00
bellman
f25fae6d22 docs: mark ROADMAP 726-806 as DONE
71 items with verified fixes marked as DONE. All have Fix/Fix applied
sections with corresponding code evidence in the current codebase.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:13:56 +09:00
bellman
be66d961bf docs: close ROADMAP 705-722 evidence
All items already fixed in prior commits:
705: estimated_cost_usd_num companion field
706: skills show not-found error
707: init temp_dir AtomicU64 counter
708: skills show action field
709: duplicate status keys removed
710: diff action and working_directory
711: version/system-prompt/export/init action field
712: doctor/status/bootstrap-plan/dump-manifests action field
713: acp and config action field
714: help action and status fields
715: resume-path action and status fields
716: resume-path error JSON standard envelope
717: agents show implemented
718: plugins show implemented
719: plugins list filter
720: help <topic> routing
721: config sections support
722: rebase conflict resolved

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:06:39 +09:00
bellman
b1a40a2364 docs: close ROADMAP 694,698 evidence
694: pre-push cargo build gate already exists
698: config warning dedup already implemented

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:04:44 +09:00
bellman
726d55d1ea docs: close ROADMAP 682,693 evidence
682: agents already returns typed error for unknown subcommands
693: claw-analog already uses unknown_bootstrap_phase_error

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:03:07 +09:00
bellman
e4b8f9c07f fix: return typed error for unsupported MCP sub-actions
The catch-all in render_mcp_report_json_for now returns
render_mcp_unsupported_action_json with ok:false and
error_kind:unsupported_action instead of help JSON with exit 0.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 02:00:26 +09:00
bellman
b3a5a74237 fix: target multi-word guard for CLI subcommands only
Only fire the slash-command guard for multi-word commands when the
first token is a known CLI subcommand (help, version, status, etc.).
Slash commands with additional arguments (explain this, cost list)
are treated as prompts.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:46:11 +09:00
bellman
ad76389b31 docs: close ROADMAP 464,470 evidence
464: CliOutputFormat::parse already handles case/whitespace/hints
470: --reasoning-effort already uses invalid_flag_value prefix

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:40:45 +09:00
bellman
e68733d72e docs: close ROADMAP 462-463 evidence
462: build_date already present in version_json_value
463: classify_error_kind already returns removed_subcommand

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:38:32 +09:00
bellman
4d4d72cd49 fix: add prefix-aware matching to config key suggestion
When input is a prefix of a candidate (e.g., mcp → mcpServers), return
the prefix match directly instead of relying on edit-distance which
would incorrectly suggest env (distance 3) over mcpServers (distance 7).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:36:35 +09:00
bellman
9bc2f3631d fix: widen parse_subcommand guard for multi-word commands
Changed rest.len() != 1 guard to rest.is_empty() so claw cost list,
claw model list, claw permissions show, etc. now reach the
bare_slash_command_guidance guard and emit typed slash-command
guidance instead of falling through to CliAction::Prompt.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:29:36 +09:00
bellman
f40927ba97 docs: close ROADMAP 451-452 models already wired evidence
claw models is already wired as CliAction::Models with full
print_models implementation. Both models list and models help
return bounded JSON without touching provider runtime.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:27:27 +09:00
bellman
5bcbc2f874 docs: close ROADMAP 460 alias check evidence
bare_slash_command_guidance already checks both spec.name and
spec.aliases at line 2407.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:23:21 +09:00
bellman
a671969688 fix: handle --help after --resume flag
Added specific handler for --help when rest contains --resume, so
claw --resume --help shows resume help instead of consuming --help
as a session-id literal.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:18:55 +09:00
bellman
6757ebde74 fix: align discovered_config_files count with config check
The status_context function now filters loader.discover() to only count
paths that exist on disk, matching the check_config_health behavior.
Both config.discovered_files_count and workspace.discovered_config_files
now report the same number.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:17:06 +09:00
bellman
2447273d09 fix: add list to KNOWN_SUBCOMMANDS and close ROADMAP 454-455
Added list to KNOWN_SUBCOMMANDS so claw list is caught by typo
suggestion instead of falling through to CliAction::Prompt. Also
verified #455 (missing_credentials hint already newline-delimited).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:15:00 +09:00
bellman
5a76ecb760 fix: add prompt_ready to doctor auth check
Added prompt_ready:bool and prompt_blocked_reason:string|null to the
auth check in doctor --output-format json. prompt_ready is true when
any auth credential is present, false otherwise. prompt_blocked_reason
is auth_missing when prompt_ready is false.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:11:31 +09:00
bellman
db56498460 fix: route session list through credentials-free path
Added dedicated CliAction::SessionList variant for claw session list so
it no longer requires API credentials. run_session_list() calls
list_managed_sessions() directly without instantiating an API client.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:06:28 +09:00
bellman
6fcd0c57ae fix: clarify sandbox requested vs active state in JSON output
Added requested field (alias for enabled) and active_components object
with namespace/network/filesystem booleans for precise subsystem visibility.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 01:02:02 +09:00
bellman
de66bfc082 fix: route broad_cwd JSON error to stdout and close ROADMAP 446-447
The enforce_broad_cwd_policy function was sending JSON error envelopes
to stderr instead of stdout. Fixed to use println! for JSON mode,
matching the main error handler and all resume error paths.

Also closed ROADMAP #446 (config warning deduplication already handled
by emit_config_warning_once) and #447 (JSON errors already routed to
stdout in main handler).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 00:54:17 +09:00
bellman
5d85739358 fix: detect skill name/dir mismatch and report metadata drift
Skill discovery now tracks dir_name alongside frontmatter name and detects
when they differ. skills list --output-format json includes metadata_drift
array and reports degraded status when drift entries exist.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 00:36:04 +09:00
bellman
8fd11e82c4 fix: track skill directory name for name/dir mismatch detection
Adds dir_name field to SkillSummary to enable detection of skills where
the SKILL.md frontmatter name differs from the parent directory name.
Also adds SkillMetadataDrift struct for tracking mismatches (used by
skills JSON output in follow-up).

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 00:26:42 +09:00
bellman
9f9b14a76d fix: add broad-cwd guard to resume path
claw --resume now enforces the same broad-cwd safety policy as claw prompt
and the interactive REPL. Running from /, $HOME, or other broad directories
blocks execution unless --allow-broad-cwd is passed.

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 00:23:28 +09:00
bellman
78c2a49ec8 docs: close ROADMAP 443 acp serve evidence 2026-06-05 00:12:23 +09:00
bellman
0e54ec4c04 fix: exit non-zero for acp serve and remove internal tracking IDs
claw acp serve now exits 2 (not implemented) instead of 0, so automation
pipelines can detect the no-op via exit code gating.

Key changes:
- acp serve exits 2 instead of 0
- Removed discoverability_tracking, tracking, recommended_workflows from JSON
- Removed phase, exit_code, serve_alias_only fields from JSON
- Status changed from unsupported/discoverability_only to not_implemented
- Error kind for unsupported ACP invocations uses typed prefix
- Updated tests to match new exit code and JSON structure

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-05 00:11:31 +09:00
bellman
58a30f6ab8 fix: accept markdown agent definitions with YAML frontmatter
Agent discovery now loads .md files with YAML frontmatter alongside .toml
files, matching the Claude Code agent definition convention. Markdown
agent files must have ----delimited YAML frontmatter with at least name
or description fields.

Key changes:
- parse_agent_frontmatter extracts name, description, model, model_reasoning_effort
- load_agents_from_roots_with_invalids collects both valid and invalid agents
- InvalidAgentConfig tracks rejected .md files with reason
- AgentCollection groups valid agents with invalid entries
- agents JSON output includes valid_count, invalid_count, invalid_agents
- Status is degraded when invalid agents exist

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-04 23:57:33 +09:00
bellman
453d8945bb fix: validate hook config entries partially
Hook config now supports the Claude Code structured hook format with
partial validation. Invalid hook entries are recorded in invalid_hooks
while valid siblings are retained, following the same pattern as MCP
partial validation (#440).

Key changes:
- RuntimeInvalidHookConfig now includes typed kind field (invalid_hooks_config
  or unknown_hook_event) for machine-readable error classification
- Hook parsing collects all invalid entries instead of halting at first error
- Unknown hook event names recorded as invalid without rejecting valid hooks
- Legacy bare-string hooks still load with deprecation warnings
- Claude Code documented format loads without error (matcher + nested hooks)
- config/status/doctor JSON surfaces hook_validation metadata
- classify_error_kind maps hook errors to invalid_hooks_config

Generated with https://github.com/Yeachan-Heo/gajae-code
Co-authored-by: Gajae Code <dev@gajae-code.com>
2026-06-04 23:42:58 +09:00
TheArchitectit
9e50cb6e20 Merge remote-tracking branch 'upstream/main' into worktree-api-timeout-retry-v2
# Conflicts:
#	rust/crates/runtime/src/config.rs
#	rust/crates/runtime/src/lib.rs
2026-06-04 09:17:43 -05:00
TheArchitectit
346772a8b3 test: add exclude_id and 0-message filtering coverage; cargo fmt 2026-06-04 09:17:42 -05:00
TheArchitectit
ef392e5938 Merge remote-tracking branch 'upstream/main' into worktree-session-resume-fixes 2026-06-04 09:15:19 -05:00
TheArchitectit
41034bb3f3 fix: address CI test failure and add empty-session error message
- Fix latest_session_alias_resolves_most_recent_managed_session test:
  the test created sessions with 0 messages, which are now filtered out
  by the message_count > 0 check in latest_session_excluding(). Updated
  the test to call push_user_text() before saving so sessions have
  at least one message and are findable by /resume latest.

- Add distinct error message when all sessions are empty (0 messages).
  Previously, the same "no managed sessions found" message was returned
  whether there were zero sessions or all sessions had 0 messages. Now:
  - No sessions at all → "no managed sessions found in {path}. Start
    claw to create a session..."
  - Sessions exist but all empty → "all sessions are empty (0 messages)
    in {path}. This usually means a fresh claw session is running but
    no messages have been sent yet. Wait for a response in your other
    session, then try --resume latest again."

- Add test for the all-sessions-empty error path.

  Addresses reviewer feedback on #3216.
2026-06-03 13:44:20 -05:00
TheArchitectit
76783377ec fix: address CI failures and reviewer feedback on #3214
- Add missing retry_after: None field to ApiError::Api construction
  in main.rs test. This field was introduced by the Retry-After
  header support but was not added to the test's error initializer,
  causing a compile error under CI's strict mode.

- Remove duplicate #[must_use] attribute on retry_after() method
  in error.rs (lines 134+138 both had it; kept the outer one
  above the doc comment per convention).

- Cargo fmt --all run.

- Reviewer question "Are defaults preserved?" — answered yes:
  ApiTimeoutConfig defaults to 30s connect / 300s request / 8 retries.
  with_retry_policy() is opt-in. No behavior change without explicit
  configuration.
2026-06-03 13:19:25 -05:00
TheArchitectit
e459a727e9 fix: session resume — skip current empty session, unify cross-workspace loading
Three improvements to the /resume command:

1. /resume latest now skips the current empty session
   When a new session is created on startup (with 0 messages), /resume
   latest previously returned that empty session. Now it skips sessions
   with message_count == 0 and excludes the current session ID via the
   new exclude_id parameter, so it finds the previous session with
   actual conversation history.

2. Unified load_session_excluding() replaces load_session_loose()
   The previous load_session_loose() only handled cross-workspace
   resume for aliases. The new load_session_excluding() combines the
   loose workspace validation logic with the exclude_id parameter,
   simplifying the call chain and ensuring all resume paths skip the
   current empty session when appropriate.

3. All existing session scanning paths (global root + project-local
   .claw/sessions/) are already in place from prior commits, and now
   the exclude_id filter is applied consistently across both local
   and global session scans.

Changes:
- session_control.rs: Add resolve_reference_excluding() that delegates
  from resolve_reference(), adding optional exclude_id filtering for
  alias references.
- session_control.rs: Add latest_session_excluding() that delegates
  from latest_session(), filtering out excluded session IDs and
  sessions with 0 messages in both local and global scan paths.
- session_control.rs: Add load_session_excluding() that replaces
  load_session_loose(), combining cross-workspace alias handling with
  the exclude_id parameter.
- main.rs: Add load_session_reference_excluding() that delegates from
  load_session_reference(), using the new store method.
- main.rs: Wire LiveCli::resume_session() to pass the current session
  ID as the exclude_id so /resume latest skips the current empty
  session.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 15:49:21 -05:00
TheArchitectit
04bc5f5788 feat: API timeout config, Retry-After header, configurable retry, and 400 transient retry
Cherry-picked from PR #2816 onto current upstream/main, resolving
conflicts from PR #3015's merge (which added retry_after to ApiError
but some construction sites were missing it).

Commits preserved:
- ade85398: API timeout config, Retry-After header, configurable retry
  - TimeoutConfig in HTTP client builder (connect 30s, request 5min)
  - CLAW_API_CONNECT_TIMEOUT and CLAW_API_REQUEST_TIMEOUT env vars
  - Retry-After header parsing on 429 responses
  - ApiTimeoutConfig in runtime config (settings.json)
- 8a883430: retry 400 responses with transient gateway error bodies
  - Detects known gateway phrases in 400 response bodies
  - Marks them as retryable instead of hard-failing
- ed91a61e: add 'no parseable body' to CONTEXT_WINDOW_ERROR_MARKERS
  - Some providers return 400 with 'no parseable body' for oversized
    requests instead of a proper context_length_exceeded error

Commits skipped (already in upstream via PR #3015):
- 453ab642: optional id field (already merged)
- baa8d1ba: HTML detection in streaming (already merged)
- 33d2f789: JSON error detection in streaming (already merged)

8 files changed, 299 insertions, 80 deletions
2026-06-02 15:35:29 -05:00
TheArchitectit
571d3cdc0f fix: add "no parseable body" to CONTEXT_WINDOW_ERROR_MARKERS
Some OpenAI-compat backends (e.g. glm-5.1-fast) return 400 with
"no parseable body" when the request payload is too large to parse,
rather than a proper context_length_exceeded error. Without this marker,
is_context_window_error() returns false and the auto-compact retry
loop never triggers — the user just sees an opaque 400 error.

💘 Generated with Crush

Assisted-by: GLM 5.1 FP8 via Crush <crush@charm.land>
2026-06-02 15:31:04 -05:00
TheArchitectit
414a1aca4f fix: retry 400 responses with transient gateway error bodies
Some providers/proxies return HTTP 400 with bodies like "no parseable
body" or "connection reset" during transient network blips. These are
not real bad requests — they're gateway errors wearing a 400 mask.
Detect known gateway error phrases in 400 response bodies and mark
them as retryable so the existing exponential backoff handles them.
2026-06-02 15:30:41 -05:00
TheArchitectit
d8c57ed317 feat: API timeout config, Retry-After header support, and configurable retry
- Add TimeoutConfig to HTTP client builder with connect_timeout (30s)
  and request_timeout (5min) defaults, configurable via
  CLAW_API_CONNECT_TIMEOUT and CLAW_API_REQUEST_TIMEOUT env vars
- Add with_timeout() builder to both AnthropicClient and
  OpenAiCompatClient for per-client timeout configuration
- Parse Retry-After header on 429 responses and use it to override
  exponential backoff delay when present
- Add ApiTimeoutConfig to runtime config with apiTimeout settings
  in ~/.claw/settings.json (connectTimeout, requestTimeout, maxRetries)
- Add retry_after field to ApiError::Api for propagating rate limit
  backoff hints through the retry pipeline
2026-06-02 15:30:22 -05:00
Sam Lamrabte
e8c8ef1142 Harden permission enforcement against sandbox bypasses
Close two ways the permission system could be bypassed:

- Workspace path traversal: normalize `.`/`..` lexically before the
  boundary prefix comparison so paths like `/workspace/../../etc` can no
  longer escape the sandbox. Fixed in both the runtime enforcer and the
  duplicate check in the tools PowerShell path classifier.
- read-only mode no longer trusts the leading token alone: reject shell
  metacharacters (chaining/substitution/redirect/pipe/subshell), drop
  interpreters and build drivers (python/node/ruby/cargo/rustc) from the
  allow-list, gate `git` to non-mutating subcommands, and reject `find`
  actions that execute or delete.

Adds regression tests for both holes. The pre-existing, unrelated
worker_boot git-metadata test failure is not affected by this change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 13:26:39 +02:00
Petter Reinholdtsen
1d516be779 fix: recover from llama.cpp context overflow and reqwest SSE decode failures
Extend auto-compaction error detection to handle additional error patterns
from llama.cpp backends: 'Context size has been exceeded',
'exceed_context_size_error', 'exceeds the available context size'. Also
recover from reqwest 'error decoding response body' errors — some
llama.cpp instances return a non-SSE plaintext HTTP 500 on context overflow,
causing the SSE deserializer to fail.

Add dynamic threshold adaptation: parse server-reported context window
size from error messages (e.g., '(81920 tokens)') and set the auto-
compaction trigger at 70% of that value. This replaces the need for a
hardcoded threshold, adapting automatically to any backend's limits.

This patch was developed with assistance from OpenCode and local Qwen 3.6
API server.
2026-05-27 16:57:59 +02:00
42 changed files with 4337 additions and 910 deletions

92
AGENTS.md Normal file
View File

@@ -0,0 +1,92 @@
# PROJECT KNOWLEDGE BASE
**Generated:** 2026-08-16
**Commit:** b71afdd
**Branch:** main
## OVERVIEW
Claw Code: public Rust implementation of the `claw` CLI agent harness (Claude-Code-style). Canonical code lives in `rust/`; the repo is an agent-managed exhibit (harnesses plan/execute/verify per README), not a hand-operated product. `src/` is a companion Python porting/parity workspace, not production code.
## STRUCTURE
```
claw-code/
├── rust/ # canonical Cargo workspace: 11 crates, `claw` binary
├── src/ # Python porting workspace + reference_data/ parity snapshots
├── tests/ # Python unittest validation of src/ + scripts/ (stdlib unittest)
├── docs/ # g0XX gate verification maps + topic docs
├── scripts/ # fmt.sh, dogfood-build.sh, roadmap/board helpers
├── assets/ # README images only
└── install.sh, Containerfile, docker-compose.yml
```
## WHERE TO LOOK
| Task | Location | Notes |
|------|----------|-------|
| CLI subcommands | rust/crates/rusty-claude-cli/src/main.rs | hand-rolled parser; CliAction enum ~L1162; dispatch in run() L995-1158 |
| Sessions/permissions/MCP | rust/crates/runtime/src/ | 47 flat modules |
| Provider clients | rust/crates/api/src/providers/ | anthropic.rs + openai_compat.rs |
| Tool definitions | rust/crates/tools/src/lib.rs | 55-tool spec table L484-1348 |
| Slash commands | rust/crates/commands/src/lib.rs | 120+ spec table L60-1047 |
| Plugins/hooks | rust/crates/plugins/src/ | manifest = .claude-plugin/plugin.json |
| Lean agent harness | rust/crates/claw-analog/src/lib.rs | lib+bin; tool loop over api+runtime |
| RAG HTTP service | rust/crates/claw-rag-service/src/ | axum; SQLite + optional Qdrant |
| Test mock server | rust/crates/mock-anthropic-service/ | SCENARIO_PREFIX scripted responses |
| Python porting CLI | src/main.py | argparse: manifest, parity-audit, graphs |
| Parity reference DB | src/reference_data/subsystems/ | 29 JSON snapshots of TS archive |
## CODE MAP
| Symbol | Type | Location | Refs | Role |
|--------|------|----------|------|------|
| Session | struct | runtime/src/session.rs:117 | 229 | session persistence/lifecycle |
| ConfigLoader | struct | runtime/src/config.rs:409 | 83 | config schema/load |
| PluginManager | struct | plugins/src/lib.rs | 48 | plugin install/registry |
| PermissionEnforcer | struct | runtime/src/permission_enforcer.rs:27 | 35 | pre-dispatch permission gate |
| ConversationRuntime | struct | runtime/src/conversation.rs:130 | 32 | conversation loop driver |
| McpServerManager | struct | runtime/src/mcp_stdio.rs:488 | 30 | MCP JSON-RPC processes |
| HookRunner | struct | runtime/src/hooks.rs:155 | 25 | shell hook execution |
| CliAction | enum | rusty-claude-cli/src/main.rs:1162 | — | 25 subcommand variants |
| mvp_tool_specs | fn | tools/src/lib.rs:484 | — | static 55-tool table |
| SLASH_COMMAND_SPECS | const | commands/src/lib.rs:60 | — | 120+ slash commands |
(Refs = rg count across rust/crates; rust-analyzer references timed out during mapping.)
## CONVENTIONS
- `unsafe_code = "forbid"` workspace-wide; every crate opts in via `[lints] workspace = true`; clippy all=warn, pedantic=allow
- Edition 2021, resolver 2, publish=false; no rust-toolchain pin (CI floats stable); no rustfmt.toml/clippy.toml — stock defaults
- Giant flat files by design (main.rs 19.8k, tools/lib.rs 10.9k, commands/lib.rs 7.2k): organization is positional — types → spec table → dispatch → handlers → tests at EOF
- Dual output paths everywhere: `render_x` + `render_x_json`; JSON errors to **stdout**, text errors to **stderr**
- Tests: inline `#[cfg(test)] mod tests` primary; integration tests spawn `CARGO_BIN_EXE_claw` subprocess against mock-anthropic-service; tempfile everywhere; env-mutating tests serialize via env_lock/test_env_lock
- Comments carry issue numbers (#824, #146); gate tests named by roadmap gate (g004_conformance.rs)
- Python side: stdlib only, `python -m unittest`; src/ mixes camelCase (QueryEngine.py) and snake_case filenames
## ANTI-PATTERNS (THIS PROJECT)
- NEVER `cargo install claw-code` — crates.io stub is deprecated and installs `claw-code-deprecated.exe`; build from source
- Forbidden doc strings (CI-enforced by .github/scripts/check_doc_source_of_truth.py): old org links `github.com/Yeachan-Heo/claw-code`, `github.com/code-yeongyu/claw-code`, `discord.gg/6ztZB9jvWq`, `assets/clawd-hero.jpeg`
- Deprecated config keys: `permissionMode``permissions.defaultMode`; `enabledPlugins``plugins.enabled`; env `RUSTY_CLAUDE_PERMISSION_MODE` is dead
- Direct push to main is policy-blocked (`main_push_forbidden` approval scope)
- Automation lanes must not merge/close remote PRs/issues (docs/anti-slop-triage.md)
- `claw init` must not scaffold `dontAsk` permission mode (regression-pinned in output_format_contract.rs)
- File-level `#![allow(dead_code)]` blocks (main.rs, session_control.rs) are tolerated legacy — do not extend the pattern
## UNIQUE STYLES
- Dogfood build: scripts/dogfood-build.sh injects GIT_SHA; `claw version` provenance must equal HEAD
- Mock parity: rust/mock_parity_scenarios.json drives CLI subprocess vs MockAnthropicService
- Dogfooding uses `CLAW_CONFIG_HOME=$(mktemp -d)` for config isolation
- Env contracts: GIT_SHA (build), CLAW_CONFIG_HOME (config dir), OLLAMA_HOST (provider override), `*_API_KEY`/`*_BASE_URL` per provider
## COMMANDS
```bash
scripts/fmt.sh --check # fmt check (apply: scripts/fmt.sh)
cd rust && cargo clippy --workspace --all-targets -- -D warnings
cd rust && cargo test --workspace
cd rust && cargo build -p rusty-claude-cli # binary: rust/target/debug/claw
python -m unittest discover -s tests # Python suite
python .github/scripts/check_doc_source_of_truth.py && scripts/roadmap-check-ids.sh # docs/roadmap CI
```
## NOTES
- `claw` binary comes from crate `rusty-claude-cli` (package/bin name mismatch)
- rust-ci.yml triggers only on rust/**, docs/**, listed meta file changes (path filters)
- CI clippy job runs without `-D warnings` — weaker than the documented gate; known pre-existing failures recorded in docs/g002/g003 maps
- `claw acp` is a status stub, not a real ACP server
- rust/ has committed harness dotdirs (.clawd-agents/, .omc/, .sandbox-home/) — intentional

View File

@@ -1,5 +1,66 @@
# Claw Code
<p align="center">
<a href="https://github.com/code-yeongyu/lazycodex">
<img src="https://img.shields.io/badge/LazyCodex-codex%20for%20no--brainers-111111?style=for-the-badge&logo=github&logoColor=white" alt="LazyCodex banner" />
</a>
<a href="https://github.com/Yeachan-Heo/gajae-code">
<img src="https://img.shields.io/badge/Gajae--Code-red--claw%20agent%20harness-B22222?style=for-the-badge&logo=github&logoColor=white" alt="Gajae-Code banner" />
</a>
</p>
<p align="center">
<a href="https://github.com/code-yeongyu/lazycodex">
<img src="https://opengraph.githubassets.com/lazycodex-card/code-yeongyu/lazycodex" alt="LazyCodex GitHub card" width="280" />
</a>
<a href="https://github.com/Yeachan-Heo/gajae-code">
<img src="https://opengraph.githubassets.com/gajae-code-card/Yeachan-Heo/gajae-code" alt="Gajae-Code GitHub card" width="280" />
</a>
</p>
<h3 align="center">start with the real crab-powered harnesses</h3>
<p align="center">
<a href="https://github.com/code-yeongyu/lazycodex"><b>github.com/code-yeongyu/lazycodex</b></a>
<br/>
<a href="https://github.com/Yeachan-Heo/gajae-code"><b>github.com/Yeachan-Heo/gajae-code</b></a>
</p>
<p align="center">
<a href="https://github.com/code-yeongyu/lazycodex">
<img src="https://img.shields.io/badge/Open-LazyCodex-111111?style=flat-square&logo=github&logoColor=white" alt="Open LazyCodex on GitHub" />
</a>
<a href="https://github.com/Yeachan-Heo/gajae-code">
<img src="https://img.shields.io/badge/Open-Gajae--Code-B22222?style=flat-square&logo=github&logoColor=white" alt="Open Gajae-Code on GitHub" />
</a>
</p>
<p align="center">
<a href="https://discord.gg/GtjhvgjnV">
<img src="https://img.shields.io/badge/Discord-join%20the%20harness%20lab-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the harness lab on Discord" />
</a>
<a href="https://discord.gg/4Rt79F7dF">
<img src="https://img.shields.io/badge/Discord-join%20the%20crab%20tank-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the crab tank on Discord" />
</a>
</p>
<p align="center">
Join the Discords:
<a href="https://discord.gg/GtjhvgjnV"><b>ultraworkers discord</b></a>
·
<a href="https://discord.gg/4Rt79F7dF"><b>gajae-code discord</b></a>
</p>
> [!IMPORTANT]
> **Claw Code is not the serious production project here.**
> This repository is closer to a museum exhibit than a product pitch, a crustacean-run artifact kept alive by clawed gajaes, swept and labeled by agents, and automatically maintained according to the harnesses above.
>
> As already described in the project philosophy, this is not meant to be hand-operated like a normal product repo. It is an **agent-managed exhibit**: the harnesses plan, execute, verify, label, and preserve the artifact while the crabs keep the tank running.
>
> If you want to actually run work, start with **[LazyCodex](https://github.com/code-yeongyu/lazycodex)** or **[Gajae-Code](https://github.com/Yeachan-Heo/gajae-code)**. If you want to inspect the strange little fossil of the Claw Code moment, continue below.
>
> For the longer public explanation behind this philosophy, see [here](https://x.com/realsigridjin/status/2039472968624185713).
<p align="center">
<a href="https://github.com/ultraworkers/claw-code">ultraworkers/claw-code</a>
·
@@ -73,6 +134,9 @@ export ANTHROPIC_API_KEY="sk-ant-..."
# 4. Run a prompt
./target/debug/claw prompt "say hello"
# 5. Start an interactive session
./target/debug/claw
```
> [!NOTE]
@@ -226,6 +290,7 @@ Claw Code is built in the open alongside the broader UltraWorkers toolchain:
- [oh-my-openagent](https://github.com/code-yeongyu/oh-my-openagent)
- [oh-my-claudecode](https://github.com/Yeachan-Heo/oh-my-claudecode)
- [oh-my-codex](https://github.com/Yeachan-Heo/oh-my-codex)
- [gajae-code](https://github.com/Yeachan-Heo/gajae-code)
- [UltraWorkers Discord](https://discord.gg/5TUQKqFWd)
## Ownership / affiliation disclaimer

File diff suppressed because one or more lines are too long

View File

@@ -245,6 +245,7 @@ export ANTHROPIC_AUTH_TOKEN="anthropic-oauth-or-proxy-bearer-token"
| `sk-ant-*` API key | `ANTHROPIC_API_KEY` | `x-api-key: sk-ant-...` | [console.anthropic.com](https://console.anthropic.com) |
| OAuth access token (opaque) | `ANTHROPIC_AUTH_TOKEN` | `Authorization: Bearer ...` | an Anthropic-compatible proxy or OAuth flow that mints bearer tokens |
| OpenRouter key (`sk-or-v1-*`) | `OPENAI_API_KEY` + `OPENAI_BASE_URL=https://openrouter.ai/api/v1` | `Authorization: Bearer ...` | [openrouter.ai/keys](https://openrouter.ai/keys) |
| Ollama local instance | `OLLAMA_HOST` | no auth header (Ollama requires none) | local Ollama server at `http://127.0.0.1:11434` |
**Why this matters:** if you paste an `sk-ant-*` key into `ANTHROPIC_AUTH_TOKEN`, Anthropic's API will return `401 Invalid bearer token` because `sk-ant-*` keys are rejected over the Bearer header. The fix is a one-line env var swap — move the key to `ANTHROPIC_API_KEY`. Recent `claw` builds detect this exact shape (401 + `sk-ant-*` in the Bearer slot) and append a hint to the error message pointing at the fix.
@@ -305,18 +306,18 @@ cd rust
### Ollama
```bash
export OPENAI_BASE_URL="http://127.0.0.1:11434/v1"
unset OPENAI_API_KEY
export OLLAMA_HOST="http://127.0.0.1:11434"
cd rust
./target/debug/claw --model "llama3.2" prompt "summarize this repository in one sentence"
```
For Ollama tags with punctuation (for example `qwen2.5-coder:7b`), `OPENAI_BASE_URL` selects the local OpenAI-compatible route even when `OPENAI_API_KEY` is unset:
`OLLAMA_HOST` is the preferred env var. Claw routes all models to the local Ollama endpoint automatically, and no API key is needed. The older `OPENAI_BASE_URL` + `OPENAI_API_KEY` workaround is also supported.
For Ollama tags with punctuation (for example `qwen2.5-coder:7b`), both approaches work:
```bash
export OPENAI_BASE_URL="http://127.0.0.1:11434/v1"
unset OPENAI_API_KEY
export OLLAMA_HOST="http://127.0.0.1:11434"
cd rust
./target/debug/claw --model "qwen2.5-coder:7b" prompt "reply with ready"
@@ -615,6 +616,7 @@ The list is also the precedence chain: project-local settings override project s
```
Object-style matchers are optional. When present, they match tool names case-insensitively and support `*` wildcards plus comma or pipe separated alternatives. Nested hook `type` may be omitted or set to `"command"`; each nested command runs in configuration order.
Legacy bare-string hook entries still load for backward compatibility but emit deprecation warnings suggesting migration to object-style entries. Unknown hook event names (e.g. `Stop`, `Notification`) are recorded as invalid without rejecting valid hooks. `status --output-format json` mirrors partial hook validation under `hook_validation` with `valid_count`, `invalid_count`, and `invalid_hooks:[{event, index, hook_index, kind, error_field, reason, valid:false}]`. `doctor --output-format json` includes a `hook validation` check so automation can repair every rejected hook entry without losing usable hooks.
## Project instruction rules

View File

@@ -57,11 +57,12 @@ ollama serve
In another shell:
```bash
export OPENAI_BASE_URL="http://127.0.0.1:11434/v1"
unset OPENAI_API_KEY
export OLLAMA_HOST="http://127.0.0.1:11434"
claw --model "qwen3:latest" prompt "Reply exactly HELLO_WORLD_123"
```
`OLLAMA_HOST` is the preferred env var for Ollama. Claw routes all models to the local OpenAI-compatible endpoint automatically when this is set, and no API key is needed. The older `OPENAI_BASE_URL` + `OPENAI_API_KEY` workaround is also supported for existing setups.
If Ollama is running without auth, `unset OPENAI_API_KEY` is acceptable. Use a placeholder token rather than a real cloud API key if your local server requires an Authorization header.
## llama.cpp server
@@ -96,6 +97,27 @@ export OPENAI_API_KEY="local-dev-token"
claw --model "Qwen/Qwen2.5-Coder-7B-Instruct" prompt "Reply exactly HELLO_WORLD_123"
```
## mlx-lm (Apple Silicon)
On Apple Silicon, [mlx-lm](https://github.com/ml-explore/mlx-lm) gives meaningfully faster inference than llama.cpp-based backends for models under roughly 14B parameters.
Install and start the server:
```bash
pipx install mlx-lm
mlx_lm.server --model mlx-community/Qwen2.5-Coder-7B-Instruct-4bit --port 8080
```
Then route Claw to it:
```bash
export OPENAI_BASE_URL="http://127.0.0.1:8080/v1"
export OPENAI_API_KEY="local-dev-token"
claw --model "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit" prompt "Reply exactly HELLO_WORLD_123"
```
mlx-lm serves models under their full Hugging Face repo ID. Use the exact `id` field from `curl $OPENAI_BASE_URL/models` for `--model`. A bare name like `qwen2.5-coder-7b-instruct` will fail model resolution before the request ever reaches the server.
## Local skills install from disk
Skills are discovered from Claw skill roots such as `.claw/skills/` in a workspace and `~/.claw/skills/` for user-level installs. Legacy `.codex/skills/` roots may also be scanned for compatibility, but new local Claw projects should prefer `.claw/skills/`.
@@ -148,3 +170,5 @@ Offline install checklist:
| Plain prompt works but tools fail | Confirm the model/server supports OpenAI-compatible tool calls and response shapes. |
| Skill says installed but `/skills <name>` fails | Check `/skills list` for the discovered name and source; verify provider credentials separately with `claw doctor`. |
| A local docs/log file contains secrets | Redact it before using `@path` file context or attaching it to an issue. |
| `404 Repository Not Found` from huggingface.co when running `claw` | The `--model` value isn't a full Hugging Face repo ID. Use the exact `id` field from `curl $OPENAI_BASE_URL/models`, not a bare model name. |
| mlx-lm output includes a trailing `<|im_end|>`, or generation runs long | Unfixed mlx-lm bug ([#973](https://github.com/ml-explore/mlx-lm/issues/973), closed without a merge). Set `eos_token_id` in the cached `generation_config.json` (or `config.json`) to the real end-of-turn token. |

80
rust/AGENTS.md Normal file
View File

@@ -0,0 +1,80 @@
# AGENTS.md — rust/ workspace
## OVERVIEW
Virtual Cargo workspace (resolver 2, edition 2021) housing 11 crates that compose the `claw` CLI and supporting services.
## STRUCTURE
| Crate | Kind | Purpose |
|---|---|---|
| `rusty-claude-cli` | bin (`claw`) | Main CLI binary. Package name ≠ binary name. |
| `claw-analog` | lib+bin | Alternate entry point; depends on api + runtime only. |
| `claw-rag-service` | bin | RAG service. Only crate with `[features]` (`qdrant-index`). |
| `mock-anthropic-service` | lib+bin | Mock Anthropic Messages API. Prints `MOCK_ANTHROPIC_BASE_URL`. Dev-dep for CLI and analog tests. |
| `runtime` | lib | Core: sessions, permissions, MCP, conversation loop. ~47 modules. |
| `api` | lib | Provider clients: Anthropic, OpenAI-compat (xAI, OpenAI, DashScope, Ollama). |
| `tools` | lib | 55-tool surface area. Depends on `commands` (not vice versa). |
| `commands` | lib | 120+ slash commands. |
| `plugins` | lib | Plugin manifest and lifecycle. |
| `telemetry` | lib | Request identity + analytics sinks. |
| `compat-harness` | lib | Extracts upstream TS claude-code manifest/commands/tools for parity comparison. |
Dependency direction: `rusty-claude-cli` → tools/commands/runtime/api/plugins. `tools``commands`.
## WHERE TO LOOK
- **Parity testing**: `mock_parity_scenarios.json` at workspace root, loaded via `CARGO_MANIFEST_DIR/../../mock_parity_scenarios.json`. Scripts in `scripts/` (`run_mock_parity_harness.sh`, `run_mock_parity_diff.py`).
- **CI**: `.github/workflows/rust-ci.yml` (fmt, clippy, test, docs, Windows smoke) and `release.yml` (v* tag builds for linux-x64/macos-arm64/windows-x64).
- **Committed test fixtures**: `.clawd-agents/`, `.omc/`, `.sandbox-home/` are checked-in harness dotdirs.
- **Docs**: `PARITY.md`, `TUI-ENHANCEMENT-PLAN.md`, `README.md` alongside this file.
## CONVENTIONS
Workspace lints (all crates opt in via `[lints] workspace = true`):
- `unsafe_code` = **forbid**. No exceptions.
- clippy `all` = warn, `pedantic` = allow. Explicitly allowed: `module_name_repetitions`, `missing_panics_doc`, `missing_errors_doc`.
No `rustfmt.toml` or `clippy.toml`. Stock defaults only.
TUI rule: formatting fns take `&mut impl Write`, never stdout directly. Never mix raw ANSI escapes with crossterm.
Library crates don't carry the `claw-` prefix. Binary crates do (except legacy `rusty-claude-cli`).
Workspace version is `0.1.3`, `publish = false`, MIT license.
No rust-toolchain file, no MSRV. CI pins `dtolnay/rust-toolchain@stable`.
## ANTI-PATTERNS
- Don't run `cargo fmt --manifest-path rust/Cargo.toml` from the repo root. Use `../scripts/fmt.sh` instead.
- Don't add `unsafe` code. The lint is set to `forbid`, not `deny`. You can't `#[allow]` it.
- Don't create dependencies from `commands``tools`. The arrow goes `tools``commands`.
- Don't write TUI output directly to stdout or use raw ANSI escape sequences.
- Don't add features to crates other than `claw-rag-service` without good reason; the workspace is feature-lean by design.
## COMMANDS
All run from `rust/`:
```sh
# Format (check only)
../scripts/fmt.sh --check
# Format (apply)
../scripts/fmt.sh
# Lint (strict, matches what you should pass before pushing)
cargo clippy --workspace --all-targets -- -D warnings
# Test
cargo test --workspace
# Build specific binary
cargo build -p rusty-claude-cli
cargo build -p claw-analog
cargo build -p claw-rag-service
cargo build -p mock-anthropic-service
```
Note: CI clippy runs without `-D warnings`, so the local check above is stricter than the gate.

View File

@@ -40,6 +40,11 @@ Or provide an OAuth bearer token directly:
export ANTHROPIC_AUTH_TOKEN="anthropic-oauth-or-proxy-bearer-token"
```
For local OpenAI-compatible servers such as Ollama, including Qwen reasoning
models, see [`../docs/local-openai-compatible-providers.md`](../docs/local-openai-compatible-providers.md).
Use the exact model tag exposed by the server, for example `qwen3:latest`, and
prefer `OLLAMA_HOST` for Ollama-specific local routing.
## Mock parity harness
The workspace now includes a deterministic Anthropic-compatible mock service and a clean-environment CLI harness for end-to-end parity checks.
@@ -151,6 +156,7 @@ Top-level commands:
`claw version --output-format json` is the provenance probe for automation: it reports full `git_sha`, derived `git_sha_short`, `is_dirty`, `branch`, `commit_date`, `commit_timestamp`, `rustc_version`, runtime `executable_path`, and `binary_provenance`; the text report is available as `human_readable` instead of a duplicate `message` field.
`status --output-format json` reports loaded project memory files under `workspace.memory_files[]` with each file's `path`, `source` (`claude_md`, `claw_md`, `agents_md`, or scoped/rule sources), `origin`, `scope_path`, `outside_project`, `chars`, and `contributes`; `claw doctor --output-format json` includes a dedicated `memory` check. Root instruction-file priority is `CLAUDE.md`, then `CLAW.md`, then `AGENTS.md`, discovery is bounded to the current git root when present (otherwise cwd only), and all non-duplicate loaded files contribute to the rendered system prompt.
`claw mcp --output-format json` reports partial MCP config success: valid servers remain in `servers[]` while malformed siblings appear in `invalid_servers[]`, with `total_configured`, `valid_count`, and `invalid_count` split out for automation. `status` mirrors this as `mcp_validation`, and doctor includes an `mcp validation` check.
`status --output-format json` also reports partial hook config success under `hook_validation`: valid hook entries are retained while malformed or unknown-event siblings appear in `invalid_hooks[]`, with `valid_count`, `invalid_count`, and typed `kind` fields (`invalid_hooks_config` or `unknown_hook_event`) for automation. `doctor --output-format json` includes a `hook validation` check, and `config --output-format json` includes `hook_validation` metadata with degraded status when invalid entries exist.
Shorthand prompt mode honors the POSIX `--` end-of-flags separator, so `claw -- "-prompt-with-dash"` and unknown dash-prefixed non-flag text stay on the prompt path instead of being treated as CLI options.
`claw dump-manifests` is self-contained: it emits the Rust resolver inventory for the selected workspace (commands, tools, agents, skills, and bootstrap phases) without requiring an upstream Claude Code TypeScript checkout. Use `--manifests-dir PATH` only to scope resolver discovery to another directory.

39
rust/crates/api/AGENTS.md Normal file
View File

@@ -0,0 +1,39 @@
# AGENTS.md — api crate
## OVERVIEW
LLM provider client layer: dispatches Anthropic, xAI, OpenAI, DashScope, and Ollama behind two wire protocols (Anthropic Messages native, OpenAI Chat Completions compat).
## WHERE TO LOOK
| Module | What lives here |
|---|---|
| `client.rs` | `ProviderClient` enum (facade). `from_model(model)` resolves alias, picks `ProviderKind`, handles OLLAMA_HOST and DashScope qwen-prefix cases. `send_message`/`stream_message`. |
| `providers/mod.rs` | `Provider` trait (generic, dead_code-allowed, not used for dispatch). `ProviderKind`, `resolve_model_alias`, `ProviderMetadata` (auth_env, base_url_env, default_base_url), `max_tokens_for_model[_with_override]`, capability/diagnostic reporting, `preflight_message_request` validation. |
| `providers/anthropic.rs` | `AnthropicClient` (re-exported as `ApiClient` at crate root). Dual auth: API key env vs saved OAuth (`AuthSource`, `OAuthTokenSet`, token expiry checks). Base-url resolution. SSE `MessageStream`. Prompt-cache hooks. |
| `providers/openai_compat.rs` | `OpenAiCompatClient` parameterized by `OpenAiCompatConfig` (presets: `xai()`, `openai()`, `dashscope()`, `OLLAMA_CONFIG`). Heavy translation layer: `build_chat_completion_request`, `translate_message`, `sanitize_tool_message_pairing`, `flatten_tool_result_content`. Model-quirk predicates (`is_reasoning_model`, etc.). Body-size estimation/guards. |
| `types.rs` | Provider-agnostic wire types: `MessageRequest`, `InputMessage`, `ContentBlock`, `StreamEvent`, `Usage`, `ToolDefinition`, `ToolChoice`. |
| `sse.rs` | `SseParser`, `parse_frame`. |
| `http_client.rs` | reqwest builders, `ProxyConfig` from env proxy vars, `TimeoutConfig`. |
| `error.rs` | `ApiError`. |
| `prompt_cache.rs` | `PromptCache` + `Stats` (Anthropic-only). |
| `lib.rs` | Curated `pub use` lists define the public surface. Also re-exports sibling telemetry crate items. |
## CONVENTIONS
- Module-private by default. `lib.rs` `pub use` lists are the sole public API surface.
- `#[must_use]` on pure constructors.
- Provider config follows an env-var pair pattern: `*_API_KEY` / `*_BASE_URL`, recorded in `ProviderMetadata`.
- Leaf files carry targeted `#![allow(clippy::cast_possible_truncation)]` where needed.
- Dispatch goes through the `ProviderClient` enum, not trait objects. The `Provider` trait exists but is dead-code-allowed.
- Streams unify into `MessageStream` with `next_event()` yielding `StreamEvent`.
## TESTS
- Four integration test files under `tests/`:
- `client_integration` — core client behavior
- `openai_compat_integration` — OpenAI-compat translation paths
- `provider_client_integration``ProviderClient` dispatch
- `proxy_integration` — proxy config
- Tests that touch env vars serialize through a shared `env_lock()` mutex. Don't skip this or you'll get flaky parallel failures.
- `benches/request_building.rs` is the workspace's only Criterion bench. Targets hot translation functions. This file bulk-opts out of strict lints.

View File

@@ -32,16 +32,25 @@ impl ProviderClient {
OpenAiCompatConfig::xai(),
)?)),
ProviderKind::OpenAi => {
// DashScope models (qwen-*) also return ProviderKind::OpenAi because they
// speak the OpenAI wire format, but they need the DashScope config which
// reads DASHSCOPE_API_KEY and points at dashscope.aliyuncs.com.
let config = match providers::metadata_for_model(&resolved_model) {
Some(meta) if meta.auth_env == "DASHSCOPE_API_KEY" => {
OpenAiCompatConfig::dashscope()
}
_ => OpenAiCompatConfig::openai(),
};
Ok(Self::OpenAi(OpenAiCompatClient::from_env(config)?))
// OLLAMA_HOST takes priority: local Ollama needs no API key
// and ignores DashScope/OpenAI env-based dispatch.
if std::env::var_os("OLLAMA_HOST").is_some() {
Ok(Self::OpenAi(
openai_compat::OpenAiCompatClient::from_ollama_env()
.expect("from_ollama_env always returns Some"),
))
} else {
// DashScope models (qwen-*) also return ProviderKind::OpenAi because they
// speak the OpenAI wire format, but they need the DashScope config which
// reads DASHSCOPE_API_KEY and points at dashscope.aliyuncs.com.
let config = match providers::metadata_for_model(&resolved_model) {
Some(meta) if meta.auth_env == "DASHSCOPE_API_KEY" => {
OpenAiCompatConfig::dashscope()
}
_ => OpenAiCompatConfig::openai(),
};
Ok(Self::OpenAi(OpenAiCompatClient::from_env(config)?))
}
}
}
}

View File

@@ -20,6 +20,7 @@ const CONTEXT_WINDOW_ERROR_MARKERS: &[&str] = &[
"completion tokens",
"prompt tokens",
"request is too large",
"no parseable body",
];
#[derive(Debug)]
@@ -60,6 +61,9 @@ pub enum ApiError {
retryable: bool,
/// Suggested user action based on error type (e.g., "Reduce prompt size" for 413)
suggested_action: Option<String>,
/// Parsed Retry-After header value (seconds) for 429 responses.
/// When present, overrides the exponential backoff delay.
retry_after: Option<Duration>,
},
RetriesExhausted {
attempts: u32,
@@ -128,6 +132,17 @@ impl ApiError {
}
#[must_use]
/// Return the `Retry-After` delay if this error came from a 429 response
/// that included a `retry-after` header. Callers should prefer this value
/// over the computed backoff delay when it exists.
pub fn retry_after(&self) -> Option<Duration> {
match self {
Self::Api { retry_after, .. } => *retry_after,
Self::RetriesExhausted { last_error, .. } => last_error.retry_after(),
_ => None,
}
}
pub fn is_retryable(&self) -> bool {
match self {
Self::Http(error) => error.is_connect() || error.is_timeout() || error.is_request(),
@@ -311,6 +326,36 @@ impl Display for ApiError {
f,
"failed to parse {provider} response for model {model}: {source}; first 200 chars of body: {body_snippet}"
),
// #28: enhance 401/403 errors with actionable auth guidance
Self::Api {
status,
error_type,
message,
request_id,
body,
..
} if matches!(status.as_u16(), 401 | 403) => {
if let (Some(error_type), Some(message)) = (error_type, message) {
write!(f, "api returned {status} ({error_type})")?;
if let Some(request_id) = request_id {
write!(f, " [trace {request_id}]")?;
}
write!(f, ": {message}")?;
} else {
write!(f, "api returned {status}")?;
if let Some(request_id) = request_id {
write!(f, " [trace {request_id}]")?;
}
write!(f, ": {body}")?;
}
write!(
f,
"\nhint: check that your API key is valid and matches the target provider. \
For OpenAI-compatible providers set OPENAI_API_KEY or OPENAI_BASE_URL. \
For Anthropic set ANTHROPIC_API_KEY. \
Run `claw doctor` to verify your credential configuration."
)
}
Self::Api {
status,
error_type,
@@ -499,6 +544,7 @@ mod tests {
body: String::new(),
retryable: true,
suggested_action: None,
retry_after: None,
};
assert!(error.is_generic_fatal_wrapper());
@@ -522,6 +568,7 @@ mod tests {
body: String::new(),
retryable: true,
suggested_action: None,
retry_after: None,
}),
};
@@ -543,6 +590,7 @@ mod tests {
body: String::new(),
retryable: false,
suggested_action: None,
retry_after: None,
};
assert!(error.is_context_window_failure());
@@ -563,6 +611,7 @@ mod tests {
body: String::new(),
retryable: false,
suggested_action: None,
retry_after: None,
};
assert!(error.is_context_window_failure());

View File

@@ -1,9 +1,69 @@
use std::time::Duration;
use crate::error::ApiError;
const HTTP_PROXY_KEYS: [&str; 2] = ["HTTP_PROXY", "http_proxy"];
const HTTPS_PROXY_KEYS: [&str; 2] = ["HTTPS_PROXY", "https_proxy"];
const NO_PROXY_KEYS: [&str; 2] = ["NO_PROXY", "no_proxy"];
/// Timeout configuration for outbound HTTP requests.
///
/// When set, the `reqwest::Client` will abort requests that take longer
/// than the configured duration and return a timeout error (which is
/// retryable by the existing exponential backoff logic).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeoutConfig {
/// Maximum time to wait for a connection to be established.
/// Defaults to 30 seconds.
pub connect_timeout: Duration,
/// Maximum time for the entire request (including reading the response
/// body). For streaming responses this is the timeout for the initial
/// handshake only; the stream itself is governed by SSE parsing.
/// Defaults to 5 minutes (300 seconds).
pub request_timeout: Duration,
}
impl Default for TimeoutConfig {
fn default() -> Self {
Self {
connect_timeout: Duration::from_secs(30),
request_timeout: Duration::from_secs(300),
}
}
}
impl TimeoutConfig {
/// Read timeout settings from the process environment.
/// - `CLAW_API_CONNECT_TIMEOUT` — connect timeout in seconds
/// - `CLAW_API_REQUEST_TIMEOUT` — overall request timeout in seconds
#[must_use]
pub fn from_env() -> Self {
let connect_timeout = std::env::var("CLAW_API_CONNECT_TIMEOUT")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.map(Duration::from_secs)
.unwrap_or(Duration::from_secs(30));
let request_timeout = std::env::var("CLAW_API_REQUEST_TIMEOUT")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.map(Duration::from_secs)
.unwrap_or(Duration::from_secs(300));
Self {
connect_timeout,
request_timeout,
}
}
/// Create from explicit second values (used by config file parsing).
#[must_use]
pub fn from_seconds(connect_secs: u64, request_secs: u64) -> Self {
Self {
connect_timeout: Duration::from_secs(connect_secs),
request_timeout: Duration::from_secs(request_secs),
}
}
}
/// Snapshot of the proxy-related environment variables that influence the
/// outbound HTTP client. Captured up front so callers can inspect, log, and
/// test the resolved configuration without re-reading the process environment.
@@ -61,7 +121,7 @@ impl ProxyConfig {
/// `HTTPS_PROXY`, and `NO_PROXY` environment variables. When no proxy is
/// configured the client behaves identically to `reqwest::Client::new()`.
pub fn build_http_client() -> Result<reqwest::Client, ApiError> {
build_http_client_with(&ProxyConfig::from_env())
build_http_client_with_opts(&ProxyConfig::from_env(), &TimeoutConfig::from_env())
}
/// Infallible counterpart to [`build_http_client`] for constructors that
@@ -71,12 +131,13 @@ pub fn build_http_client() -> Result<reqwest::Client, ApiError> {
/// first outbound request instead of at construction time.
#[must_use]
pub fn build_http_client_or_default() -> reqwest::Client {
build_http_client().unwrap_or_else(|_| {
reqwest::Client::builder()
.user_agent("clawd-rust-tools/0.1")
.build()
.expect("default client with user_agent should always succeed")
})
build_http_client_with_opts(&ProxyConfig::from_env(), &TimeoutConfig::from_env())
.unwrap_or_else(|_| {
reqwest::Client::builder()
.user_agent("clawd-rust-tools/0.1")
.build()
.expect("default client with user_agent should always succeed")
})
}
/// Build a `reqwest::Client` from an explicit [`ProxyConfig`]. Used by tests
@@ -86,9 +147,20 @@ pub fn build_http_client_or_default() -> reqwest::Client {
/// and `https_proxy` fields and is registered as both an HTTP and HTTPS
/// proxy so a single value can route every outbound request.
pub fn build_http_client_with(config: &ProxyConfig) -> Result<reqwest::Client, ApiError> {
build_http_client_with_opts(config, &TimeoutConfig::from_env())
}
/// Build a `reqwest::Client` from explicit [`ProxyConfig`] and [`TimeoutConfig`].
/// Used by callers that want to control both proxy routing and request timing.
pub fn build_http_client_with_opts(
config: &ProxyConfig,
timeout: &TimeoutConfig,
) -> Result<reqwest::Client, ApiError> {
let mut builder = reqwest::Client::builder()
.no_proxy()
.user_agent("clawd-rust-tools/0.1");
.user_agent("clawd-rust-tools/0.1")
.connect_timeout(timeout.connect_timeout)
.timeout(timeout.request_timeout);
let no_proxy = config
.no_proxy
@@ -131,7 +203,7 @@ where
mod tests {
use std::collections::HashMap;
use super::{build_http_client_with, ProxyConfig};
use super::{build_http_client_with, build_http_client_with_opts, ProxyConfig, TimeoutConfig};
fn config_from_map(pairs: &[(&str, &str)]) -> ProxyConfig {
let map: HashMap<String, String> = pairs
@@ -143,30 +215,19 @@ mod tests {
#[test]
fn proxy_config_is_empty_when_no_env_vars_are_set() {
// given
let config = config_from_map(&[]);
// when
let empty = config.is_empty();
// then
assert!(empty);
assert!(config.is_empty());
assert_eq!(config, ProxyConfig::default());
}
#[test]
fn proxy_config_reads_uppercase_http_https_and_no_proxy() {
// given
let pairs = [
("HTTP_PROXY", "http://proxy.internal:3128"),
("HTTPS_PROXY", "http://secure.internal:3129"),
("NO_PROXY", "localhost,127.0.0.1,.corp"),
];
// when
let config = config_from_map(&pairs);
// then
assert_eq!(
config.http_proxy.as_deref(),
Some("http://proxy.internal:3128")
@@ -184,17 +245,12 @@ mod tests {
#[test]
fn proxy_config_falls_back_to_lowercase_keys() {
// given
let pairs = [
("http_proxy", "http://lower.internal:3128"),
("https_proxy", "http://lower-secure.internal:3129"),
("no_proxy", ".lower"),
];
// when
let config = config_from_map(&pairs);
// then
assert_eq!(
config.http_proxy.as_deref(),
Some("http://lower.internal:3128")
@@ -208,16 +264,11 @@ mod tests {
#[test]
fn proxy_config_prefers_uppercase_over_lowercase_when_both_set() {
// given
let pairs = [
("HTTP_PROXY", "http://upper.internal:3128"),
("http_proxy", "http://lower.internal:3128"),
];
// when
let config = config_from_map(&pairs);
// then
assert_eq!(
config.http_proxy.as_deref(),
Some("http://upper.internal:3128")
@@ -226,59 +277,39 @@ mod tests {
#[test]
fn proxy_config_treats_empty_strings_as_unset() {
// given
let pairs = [("HTTP_PROXY", ""), ("http_proxy", "")];
// when
let config = config_from_map(&pairs);
// then
assert!(config.http_proxy.is_none());
}
#[test]
fn build_http_client_succeeds_when_no_proxy_is_configured() {
// given
let config = ProxyConfig::default();
// when
let result = build_http_client_with(&config);
// then
assert!(result.is_ok());
}
#[test]
fn build_http_client_succeeds_with_valid_http_and_https_proxies() {
// given
let config = ProxyConfig {
http_proxy: Some("http://proxy.internal:3128".to_string()),
https_proxy: Some("http://secure.internal:3129".to_string()),
no_proxy: Some("localhost,127.0.0.1".to_string()),
proxy_url: None,
};
// when
let result = build_http_client_with(&config);
// then
assert!(result.is_ok());
}
#[test]
fn build_http_client_returns_http_error_for_invalid_proxy_url() {
// given
let config = ProxyConfig {
http_proxy: None,
https_proxy: Some("not a url".to_string()),
no_proxy: None,
proxy_url: None,
};
// when
let result = build_http_client_with(&config);
// then
let error = result.expect_err("invalid proxy URL must be reported as a build failure");
assert!(
matches!(error, crate::error::ApiError::Http(_)),
@@ -288,10 +319,7 @@ mod tests {
#[test]
fn from_proxy_url_sets_unified_field_and_leaves_per_scheme_empty() {
// given / when
let config = ProxyConfig::from_proxy_url("http://unified.internal:3128");
// then
assert_eq!(
config.proxy_url.as_deref(),
Some("http://unified.internal:3128")
@@ -303,49 +331,56 @@ mod tests {
#[test]
fn build_http_client_succeeds_with_unified_proxy_url() {
// given
let config = ProxyConfig {
proxy_url: Some("http://unified.internal:3128".to_string()),
no_proxy: Some("localhost".to_string()),
..ProxyConfig::default()
};
// when
let result = build_http_client_with(&config);
// then
assert!(result.is_ok());
}
#[test]
fn proxy_url_takes_precedence_over_per_scheme_fields() {
// given both per-scheme and unified are set
let config = ProxyConfig {
http_proxy: Some("http://per-scheme.internal:1111".to_string()),
https_proxy: Some("http://per-scheme.internal:2222".to_string()),
no_proxy: None,
proxy_url: Some("http://unified.internal:3128".to_string()),
};
// when building succeeds (the unified URL is valid)
let result = build_http_client_with(&config);
// then
assert!(result.is_ok());
}
#[test]
fn build_http_client_returns_error_for_invalid_unified_proxy_url() {
// given
let config = ProxyConfig::from_proxy_url("not a url");
// when
let result = build_http_client_with(&config);
// then
assert!(
matches!(result, Err(crate::error::ApiError::Http(_))),
"invalid unified proxy URL should fail: {result:?}"
);
}
#[test]
fn timeout_config_defaults() {
let config = TimeoutConfig::default();
assert_eq!(config.connect_timeout, std::time::Duration::from_secs(30));
assert_eq!(config.request_timeout, std::time::Duration::from_secs(300));
}
#[test]
fn timeout_config_from_seconds() {
let config = TimeoutConfig::from_seconds(10, 60);
assert_eq!(config.connect_timeout, std::time::Duration::from_secs(10));
assert_eq!(config.request_timeout, std::time::Duration::from_secs(60));
}
#[test]
fn build_http_client_with_custom_timeouts() {
let config = ProxyConfig::default();
let timeout = TimeoutConfig::from_seconds(5, 120);
let result = build_http_client_with_opts(&config, &timeout);
assert!(result.is_ok());
}
}

View File

@@ -12,7 +12,8 @@ pub use client::{
};
pub use error::ApiError;
pub use http_client::{
build_http_client, build_http_client_or_default, build_http_client_with, ProxyConfig,
build_http_client, build_http_client_or_default, build_http_client_with,
build_http_client_with_opts, ProxyConfig, TimeoutConfig,
};
pub use prompt_cache::{
CacheBreakEvent, PromptCache, PromptCacheConfig, PromptCachePaths, PromptCacheRecord,

View File

@@ -211,6 +211,19 @@ impl AnthropicClient {
self
}
/// Replace the internal HTTP client with one that respects the given
/// timeout configuration. This controls connect and request-level
/// timeouts for all outbound API calls.
#[must_use]
pub fn with_timeout(mut self, timeout: &crate::http_client::TimeoutConfig) -> Self {
self.http = crate::http_client::build_http_client_with_opts(
&crate::http_client::ProxyConfig::from_env(),
timeout,
)
.unwrap_or_else(|_| reqwest::Client::new());
self
}
#[must_use]
pub fn with_session_tracer(mut self, session_tracer: SessionTracer) -> Self {
self.session_tracer = Some(session_tracer);
@@ -454,7 +467,13 @@ impl AnthropicClient {
break;
}
tokio::time::sleep(self.jittered_backoff_for_attempt(attempts)?).await;
let delay = if let Some(retry_after) = last_error.as_ref().and_then(|e| e.retry_after())
{
retry_after
} else {
self.jittered_backoff_for_attempt(attempts)?
};
tokio::time::sleep(delay).await;
}
Err(ApiError::RetriesExhausted {
@@ -866,10 +885,12 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
return Ok(response);
}
let request_id = request_id_from_headers(response.headers());
let headers = response.headers().clone();
let request_id = request_id_from_headers(&headers);
let body = response.text().await.unwrap_or_else(|_| String::new());
let parsed_error = serde_json::from_str::<AnthropicErrorEnvelope>(&body).ok();
let retryable = is_retryable_status(status);
let retry_after = parse_retry_after(&headers, status);
Err(ApiError::Api {
status,
@@ -883,13 +904,44 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
body,
retryable,
suggested_action: None,
retry_after,
})
}
fn parse_retry_after(
headers: &reqwest::header::HeaderMap,
status: reqwest::StatusCode,
) -> Option<std::time::Duration> {
if status != reqwest::StatusCode::TOO_MANY_REQUESTS {
return None;
}
headers
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
.map(std::time::Duration::from_secs)
}
const fn is_retryable_status(status: reqwest::StatusCode) -> bool {
matches!(status.as_u16(), 408 | 409 | 429 | 500 | 502 | 503 | 504)
}
/// Some providers return HTTP 400 with an unparseable body when a gateway
/// or proxy flakes (e.g. "HTTP 400 from backend (no parseable body)").
/// These are transient network blips, not actual bad requests, and should
/// be retried. We detect them by checking the body for known gateway error
/// phrases.
fn is_retryable_400(status: reqwest::StatusCode, body: &str) -> bool {
if status != reqwest::StatusCode::BAD_REQUEST {
return false;
}
let lowered = body.to_ascii_lowercase();
lowered.contains("no parseable body")
|| lowered.contains("connection reset")
|| lowered.contains("broken pipe")
|| lowered.contains("empty reply from server")
}
/// Anthropic API keys (`sk-ant-*`) are accepted over the `x-api-key` header
/// and rejected with HTTP 401 "Invalid bearer token" when sent as a Bearer
/// token via `ANTHROPIC_AUTH_TOKEN`. This happens often enough in the wild
@@ -908,6 +960,8 @@ fn enrich_bearer_auth_error(error: ApiError, auth: &AuthSource) -> ApiError {
body,
retryable,
suggested_action,
retry_after,
..
} = error
else {
return error;
@@ -921,6 +975,7 @@ fn enrich_bearer_auth_error(error: ApiError, auth: &AuthSource) -> ApiError {
body,
retryable,
suggested_action,
retry_after,
};
}
let Some(bearer_token) = auth.bearer_token() else {
@@ -932,6 +987,7 @@ fn enrich_bearer_auth_error(error: ApiError, auth: &AuthSource) -> ApiError {
body,
retryable,
suggested_action,
retry_after,
};
};
if !bearer_token.starts_with("sk-ant-") {
@@ -943,6 +999,7 @@ fn enrich_bearer_auth_error(error: ApiError, auth: &AuthSource) -> ApiError {
body,
retryable,
suggested_action,
retry_after,
};
}
// Only append the hint when the AuthSource is pure BearerToken. If both
@@ -958,6 +1015,7 @@ fn enrich_bearer_auth_error(error: ApiError, auth: &AuthSource) -> ApiError {
body,
retryable,
suggested_action,
retry_after,
};
}
let enriched_message = match message {
@@ -972,6 +1030,7 @@ fn enrich_bearer_auth_error(error: ApiError, auth: &AuthSource) -> ApiError {
body,
retryable,
suggested_action,
retry_after,
}
}
@@ -1596,6 +1655,7 @@ mod tests {
body: String::new(),
retryable: false,
suggested_action: None,
retry_after: None,
};
// when
@@ -1637,6 +1697,7 @@ mod tests {
body: String::new(),
retryable: true,
suggested_action: None,
retry_after: None,
};
// when
@@ -1666,6 +1727,7 @@ mod tests {
body: String::new(),
retryable: false,
suggested_action: None,
retry_after: None,
};
// when
@@ -1694,6 +1756,7 @@ mod tests {
body: String::new(),
retryable: false,
suggested_action: None,
retry_after: None,
};
// when
@@ -1719,6 +1782,7 @@ mod tests {
body: String::new(),
retryable: false,
suggested_action: None,
retry_after: None,
};
// when

View File

@@ -296,6 +296,15 @@ pub fn metadata_for_model(model: &str) -> Option<ProviderMetadata> {
None
}
#[must_use]
pub fn strip_provider_prefix(canonical_model: &str) -> String {
if let Some(pos) = canonical_model.find('/') {
canonical_model[pos + 1..].to_string()
} else {
canonical_model.to_string()
}
}
#[must_use]
pub fn provider_diagnostics_for_model(model: &str) -> ProviderDiagnostics {
let resolved_model = resolve_model_alias(model);
@@ -351,6 +360,11 @@ fn looks_like_local_openai_model(model: &str) -> bool {
#[must_use]
pub fn detect_provider_kind(model: &str) -> ProviderKind {
// OLLAMA_HOST takes priority: if set, route all models through the local
// OpenAI-compatible endpoint regardless of model name or other env vars.
if std::env::var_os("OLLAMA_HOST").is_some() {
return ProviderKind::OpenAi;
}
let resolved_model = resolve_model_alias(model);
if let Some(metadata) = metadata_for_model(&resolved_model) {
return metadata.provider;

View File

@@ -16,7 +16,7 @@ use crate::types::{
ToolChoice, ToolDefinition, ToolResultContentBlock, Usage,
};
use super::{preflight_message_request, Provider, ProviderFuture};
use super::{preflight_message_request, resolve_model_alias, Provider, ProviderFuture};
pub const DEFAULT_XAI_BASE_URL: &str = "https://api.x.ai/v1";
pub const DEFAULT_OPENAI_BASE_URL: &str = "https://api.openai.com/v1";
@@ -49,6 +49,14 @@ const XAI_MAX_REQUEST_BODY_BYTES: usize = 52_428_800; // 50MB
const OPENAI_MAX_REQUEST_BODY_BYTES: usize = 104_857_600; // 100MB
const DASHSCOPE_MAX_REQUEST_BODY_BYTES: usize = 6_291_456; // 6MB (observed limit in dogfood)
pub const OLLAMA_CONFIG: OpenAiCompatConfig = OpenAiCompatConfig {
provider_name: "Ollama",
api_key_env: "OLLAMA_HOST",
base_url_env: "OLLAMA_HOST",
default_base_url: "http://127.0.0.1:11434/v1",
max_request_body_bytes: 104_857_600,
};
impl OpenAiCompatConfig {
#[must_use]
pub const fn xai() -> Self {
@@ -149,6 +157,22 @@ impl OpenAiCompatClient {
};
Ok(Self::new(api_key, config).with_base_url(base_url))
}
/// Create an Ollama client from `OLLAMA_HOST` env var.
/// Ollama requires no API key; a placeholder is used for the Authorization header.
pub fn from_ollama_env() -> Option<Self> {
let host =
std::env::var("OLLAMA_HOST").unwrap_or_else(|_| "http://127.0.0.1:11434".to_string());
let base_url = format!("{}/v1", host.trim_end_matches('/'));
Some(Self {
http: build_http_client_or_default(),
api_key: "ollama".to_string(),
config: OLLAMA_CONFIG,
base_url,
max_retries: DEFAULT_MAX_RETRIES,
initial_backoff: DEFAULT_INITIAL_BACKOFF,
max_backoff: DEFAULT_MAX_BACKOFF,
})
}
#[must_use]
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
@@ -175,22 +199,35 @@ impl OpenAiCompatClient {
self
}
/// Replace the internal HTTP client with one that respects the given
/// timeout configuration.
#[must_use]
pub fn with_timeout(mut self, timeout: &crate::http_client::TimeoutConfig) -> Self {
self.http = crate::http_client::build_http_client_with_opts(
&crate::http_client::ProxyConfig::from_env(),
timeout,
)
.unwrap_or_else(|_| reqwest::Client::new());
self
}
pub async fn send_message(
&self,
request: &MessageRequest,
) -> Result<MessageResponse, ApiError> {
let request = MessageRequest {
let original_model = request.model.clone();
let canonical = resolve_model_alias(&request.model);
let mut request = MessageRequest {
stream: false,
..request.clone()
};
request.model = canonical;
preflight_message_request(&request)?;
let response = self.send_with_retry(&request).await?;
let request_id = request_id_from_headers(response.headers());
let body = response.text().await.map_err(ApiError::from)?;
// Some backends return {"error":{"message":"...","type":"...","code":...}}
// instead of a valid completion object. Check for this before attempting
// full deserialization so the user sees the actual error, not a cryptic
// "missing field 'id'" parse failure.
if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&body) {
if let Some(err_obj) = raw.get("error") {
let msg = err_obj
@@ -217,16 +254,18 @@ impl OpenAiCompatClient {
reqwest::StatusCode::from_u16(code.unwrap_or(400))
.unwrap_or(reqwest::StatusCode::BAD_REQUEST),
),
retry_after: None,
});
}
}
let payload = serde_json::from_str::<ChatCompletionResponse>(&body).map_err(|error| {
ApiError::json_deserialize(self.config.provider_name, &request.model, &body, error)
ApiError::json_deserialize(self.config.provider_name, &original_model, &body, error)
})?;
let mut normalized = normalize_response(&request.model, payload)?;
if normalized.request_id.is_none() {
normalized.request_id = request_id;
}
normalized.model = original_model;
Ok(normalized)
}
@@ -234,17 +273,25 @@ impl OpenAiCompatClient {
&self,
request: &MessageRequest,
) -> Result<MessageStream, ApiError> {
preflight_message_request(request)?;
let response = self
.send_with_retry(&request.clone().with_streaming())
.await?;
let original_model = request.model.clone();
let canonical = resolve_model_alias(&request.model);
let mut streaming_request = request.clone().with_streaming();
streaming_request.model = canonical;
preflight_message_request(&streaming_request)?;
let response = self.send_with_retry(&streaming_request).await?;
Ok(MessageStream {
request_id: request_id_from_headers(response.headers()),
response,
parser: OpenAiSseParser::with_context(self.config.provider_name, request.model.clone()),
parser: OpenAiSseParser::with_context(
self.config.provider_name,
original_model.clone(),
),
pending: VecDeque::new(),
done: false,
state: StreamState::new(request.model.clone()),
state: StreamState::new(original_model),
})
}
@@ -270,7 +317,12 @@ impl OpenAiCompatClient {
break retryable_error;
}
tokio::time::sleep(self.jittered_backoff_for_attempt(attempts)?).await;
let delay = if let Some(retry_after) = retryable_error.retry_after() {
retry_after
} else {
self.jittered_backoff_for_attempt(attempts)?
};
tokio::time::sleep(delay).await;
};
Err(ApiError::RetriesExhausted {
@@ -520,6 +572,7 @@ impl StreamState {
.delta
.reasoning_content
.filter(|value| !value.is_empty())
.or(choice.delta.reasoning.filter(|value| !value.is_empty()))
.or(choice
.delta
.thinking
@@ -775,6 +828,8 @@ struct ChatMessage {
#[serde(default)]
reasoning_content: Option<String>,
#[serde(default)]
reasoning: Option<String>,
#[serde(default)]
tool_calls: Vec<ResponseToolCall>,
}
@@ -849,6 +904,8 @@ struct ChunkDelta {
#[serde(default)]
reasoning_content: Option<String>,
#[serde(default)]
reasoning: Option<String>,
#[serde(default)]
thinking: Option<ThinkingDelta>,
#[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
tool_calls: Vec<DeltaToolCall>,
@@ -1458,6 +1515,7 @@ fn normalize_response(
.message
.reasoning_content
.filter(|value| !value.is_empty())
.or(choice.message.reasoning.filter(|value| !value.is_empty()))
{
content.push(OutputContentBlock::Thinking {
thinking,
@@ -1561,6 +1619,7 @@ fn parse_sse_frame(
body: trimmed.chars().take(500).collect(),
retryable: false,
suggested_action: suggested_action_for_status(status),
retry_after: None,
});
}
}
@@ -1576,6 +1635,7 @@ fn parse_sse_frame(
body: trimmed.chars().take(200).collect(),
retryable: false,
suggested_action: Some("verify the API endpoint URL is correct".to_string()),
retry_after: None,
});
}
return Ok(None);
@@ -1611,6 +1671,7 @@ fn parse_sse_frame(
body: payload.clone(),
retryable: false,
suggested_action: suggested_action_for_status(status),
retry_after: None,
});
}
}
@@ -1627,6 +1688,7 @@ fn parse_sse_frame(
body: payload.chars().take(200).collect(),
retryable: false,
suggested_action: Some("verify the API endpoint URL is correct".to_string()),
retry_after: None,
});
}
serde_json::from_str::<ChatCompletionChunk>(&payload)
@@ -1678,10 +1740,12 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
return Ok(response);
}
let request_id = request_id_from_headers(response.headers());
let headers = response.headers().clone();
let request_id = request_id_from_headers(&headers);
let body = response.text().await.unwrap_or_default();
let parsed_error = serde_json::from_str::<ErrorEnvelope>(&body).ok();
let retryable = is_retryable_status(status);
let retry_after = parse_retry_after(&headers, status);
let suggested_action = suggested_action_for_status(status);
@@ -1697,13 +1761,43 @@ async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response
body,
retryable,
suggested_action,
retry_after,
})
}
fn parse_retry_after(
headers: &reqwest::header::HeaderMap,
status: reqwest::StatusCode,
) -> Option<std::time::Duration> {
if status != reqwest::StatusCode::TOO_MANY_REQUESTS {
return None;
}
headers
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
.map(std::time::Duration::from_secs)
}
const fn is_retryable_status(status: reqwest::StatusCode) -> bool {
matches!(status.as_u16(), 408 | 409 | 429 | 500 | 502 | 503 | 504)
}
/// Some providers return HTTP 400 with an unparseable body when a gateway
/// or proxy flakes (e.g. "HTTP 400 from backend (no parseable body)").
/// These are transient network blips, not actual bad requests, and should
/// be retried.
fn is_retryable_400(status: reqwest::StatusCode, body: &str) -> bool {
if status != reqwest::StatusCode::BAD_REQUEST {
return false;
}
let lowered = body.to_ascii_lowercase();
lowered.contains("no parseable body")
|| lowered.contains("connection reset")
|| lowered.contains("broken pipe")
|| lowered.contains("empty reply from server")
}
/// Generate a suggested user action based on the HTTP status code and error context.
/// This provides actionable guidance when API requests fail.
fn suggested_action_for_status(status: reqwest::StatusCode) -> Option<String> {
@@ -1904,6 +1998,7 @@ mod tests {
role: "assistant".to_string(),
content: Some("final answer".to_string()),
reasoning_content: Some("hidden thought".to_string()),
reasoning: None,
tool_calls: Vec::new(),
},
finish_reason: Some("stop".to_string()),
@@ -1941,6 +2036,7 @@ mod tests {
delta: super::ChunkDelta {
content: None,
reasoning_content: Some("think".to_string()),
reasoning: None,
thinking: None,
tool_calls: Vec::new(),
},
@@ -1958,6 +2054,7 @@ mod tests {
delta: super::ChunkDelta {
content: Some(" answer".to_string()),
reasoning_content: None,
reasoning: None,
thinking: None,
tool_calls: Vec::new(),
},

View File

@@ -166,6 +166,55 @@ async fn send_message_preserves_deepseek_reasoning_content_before_text() {
assert_eq!(body["thinking"], json!({"type": "enabled"}));
}
#[tokio::test]
async fn send_message_preserves_ollama_reasoning_before_text() {
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
let body = concat!(
"{",
"\"id\":\"chatcmpl_ollama_reasoning\",",
"\"model\":\"qwen3:latest\",",
"\"choices\":[{",
"\"message\":{\"role\":\"assistant\",\"reasoning\":\"Think locally\",\"content\":\"Answer locally\",\"tool_calls\":[]},",
"\"finish_reason\":\"stop\"",
"}],",
"\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":5}",
"}"
);
let server = spawn_server(
state.clone(),
vec![http_response("200 OK", "application/json", body)],
)
.await;
let client = OpenAiCompatClient::new("ollama-test-key", OpenAiCompatConfig::openai())
.with_base_url(server.base_url());
let response = client
.send_message(&MessageRequest {
model: "openai/qwen3:latest".to_string(),
..sample_request(false)
})
.await
.expect("request should succeed");
assert_eq!(
response.content,
vec![
OutputContentBlock::Thinking {
thinking: "Think locally".to_string(),
signature: None,
},
OutputContentBlock::Text {
text: "Answer locally".to_string(),
},
]
);
let captured = state.lock().await;
let request = captured.first().expect("server should capture request");
let body: serde_json::Value = serde_json::from_str(&request.body).expect("json body");
assert_eq!(body["model"], json!("qwen3:latest"));
}
#[tokio::test]
async fn local_openai_gateway_strips_routing_prefix_and_preserves_extra_body_params() {
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
@@ -389,6 +438,83 @@ async fn stream_message_normalizes_text_and_multiple_tool_calls() {
assert!(request.body.contains("\"stream\":true"));
}
#[tokio::test]
async fn stream_message_preserves_ollama_reasoning_before_text() {
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
let sse = concat!(
"data: {\"id\":\"chatcmpl_stream_ollama_reasoning\",\"model\":\"qwen3:latest\",\"choices\":[{\"delta\":{\"reasoning\":\"Think\"}}]}\n\n",
"data: {\"id\":\"chatcmpl_stream_ollama_reasoning\",\"choices\":[{\"delta\":{\"content\":\" answer\"},\"finish_reason\":\"stop\"}]}\n\n",
"data: [DONE]\n\n"
);
let server = spawn_server(
state.clone(),
vec![http_response_with_headers(
"200 OK",
"text/event-stream",
sse,
&[("x-request-id", "req_ollama_reasoning_stream")],
)],
)
.await;
let client = OpenAiCompatClient::new("ollama-test-key", OpenAiCompatConfig::openai())
.with_base_url(server.base_url());
let mut stream = client
.stream_message(&MessageRequest {
model: "openai/qwen3:latest".to_string(),
..sample_request(false)
})
.await
.expect("stream should start");
assert_eq!(stream.request_id(), Some("req_ollama_reasoning_stream"));
let mut events = Vec::new();
while let Some(event) = stream.next_event().await.expect("event should parse") {
events.push(event);
}
assert!(matches!(events[0], StreamEvent::MessageStart(_)));
assert!(matches!(
events[1],
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
index: 0,
content_block: OutputContentBlock::Thinking { .. },
})
));
assert!(matches!(
events[2],
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
index: 0,
delta: ContentBlockDelta::ThinkingDelta { .. },
})
));
assert!(matches!(
events[3],
StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 0 })
));
assert!(matches!(
events[4],
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
index: 1,
content_block: OutputContentBlock::Text { .. },
})
));
assert!(matches!(
events[5],
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
index: 1,
delta: ContentBlockDelta::TextDelta { .. },
})
));
let captured = state.lock().await;
let request = captured.first().expect("captured request");
let body: serde_json::Value = serde_json::from_str(&request.body).expect("json body");
assert_eq!(body["model"], json!("qwen3:latest"));
assert_eq!(body["stream"], json!(true));
}
#[allow(clippy::await_holding_lock)]
#[tokio::test]
async fn stream_message_retries_retryable_sse_handshake_failures() {
@@ -548,12 +674,13 @@ async fn openai_compatible_client_honors_http_proxy_for_requests() {
.with_base_url("http://origin.invalid/v1");
let response = client
.send_message(&MessageRequest {
model: "gpt-4o".to_string(),
model: "openai/gpt-4.1-mini".to_string(),
..sample_request(false)
})
.await
.expect("proxy should return the OpenAI-compatible response");
assert_eq!(response.model, "openai/gpt-4.1-mini");
assert_eq!(response.total_tokens(), 7);
let captured = state.lock().await;
let request = captured.first().expect("proxy should capture request");
@@ -562,6 +689,8 @@ async fn openai_compatible_client_honors_http_proxy_for_requests() {
request.headers.get("authorization").map(String::as_str),
Some("Bearer openai-test-key")
);
let body: serde_json::Value = serde_json::from_str(&request.body).expect("json body");
assert_eq!(body["model"], json!("openai/gpt-4.1-mini"));
}
#[allow(clippy::await_holding_lock)]

View File

@@ -0,0 +1,37 @@
# commands crate
## OVERVIEW
REPL slash-command surface: parsing, spec registry, help rendering, and a handful of in-crate handlers. Single flat `src/lib.rs` (~7k lines). Deps: `plugins`, `runtime`, `serde_json` only. Note: `tools` depends on `commands`, not the reverse.
## lib.rs MAP
| Lines | Landmark |
|-------------|----------|
| 1658 | Registry types: `CommandManifestEntry`, `CommandSource` (Builtin / InternalOnly / FeatureGated), `CommandRegistry`, `SlashCommandSpec`, `SkillSlashDispatch` |
| 601047 | `SLASH_COMMAND_SPECS` static table. 120+ entries (help, status, sandbox, compact, model, permissions, clear, cost, resume, config, mcp, memory, init, diff, version, bughunter, commit, pr, issue, ultraplan, teleport, debug-tool-call, export, session, plugin, agents, skills, doctor, plan, review, tasks, theme, vim, voice, chat, ...) |
| 10481303 | `SlashCommand` enum (~65 variants + `Unknown(String)`), `SlashCommandParseError`, `SlashCommand::parse` (L1218) |
| 15151899 | Per-command arg parsers: `parse_mcp_command`, `parse_plugin_command`, `parse_session_command`, etc. |
| 19002108 | Help/suggestion rendering: `render_slash_command_help*`, `suggest_slash_commands` (Levenshtein), category grouping |
| 21092682 | Result types + handlers: `handle_plugins_slash_command`, `handle_agents/mcp/skills_slash_command(_json)`, skill dispatch/resolve |
| 31605293 | Reporting layer: paired text and `_json` renderers for plugins/agents/skills/mcp reports, skill install/uninstall/create-agent logic, frontmatter parsing, root discovery |
| 5294 | `handle_slash_command(input, session, compaction)` top dispatch. Only Compact and Help execute here; all other variants return to the REPL caller |
| 54037183 | `mod tests` (~1780 lines) |
## ADDING A SLASH COMMAND
1. **Spec.** Add a `SlashCommandSpec` entry to `SLASH_COMMAND_SPECS`. Set `resume_supported` honestly.
2. **Enum + parse.** Add a variant to `SlashCommand`. Wire a match arm in `SlashCommand::parse`. If the command takes arguments, add a dedicated `parse_*_command` function in the arg-parser block.
3. **Handler.** Decide where execution lives:
- In-crate (like Compact/Help): handle it inside `handle_slash_command`.
- Returned to caller: just return the parsed variant. The REPL layer executes it.
4. **Help.** Make sure the spec's `summary` and `argument_hint` are set so help rendering and suggestion matching pick it up automatically.
5. **Tests.** Cover parsing (valid input, bad input, edge cases) in the inline `mod tests`.
## CONVENTIONS
- **Dual renderers.** Every report surface has a text variant and a `_json` variant: `handle_x` / `handle_x_json`, `render_*` / `render_*_json`. Keep them in sync.
- **Error style.** Handlers return `std::io::Result`. Parse failures use `SlashCommandParseError`.
- **Manifest registries.** Pattern is `entries: Vec<_Entry>` backed by the static spec table.
- **Dependency direction.** This crate knows nothing about `tools`. Don't import it.
- **No execution here.** Almost all commands pass through as parsed data. Only Compact and Help run inside this crate. Respect that boundary.

View File

@@ -720,6 +720,13 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
argument_hint: None,
resume_supported: true,
},
SlashCommandSpec {
name: "setup",
aliases: &[],
summary: "Run the interactive provider setup wizard",
argument_hint: None,
resume_supported: false,
},
SlashCommandSpec {
name: "notifications",
aliases: &[],
@@ -1102,6 +1109,7 @@ pub enum SlashCommand {
args: Option<String>,
},
Doctor,
Setup,
Login,
Logout,
Vim,
@@ -1223,6 +1231,7 @@ impl SlashCommand {
Self::Compact { .. } => "/compact",
Self::Cost => "/cost",
Self::Doctor => "/doctor",
Self::Setup => "/setup",
Self::Config { .. } => "/config",
Self::Memory { .. } => "/memory",
Self::History { .. } => "/history",
@@ -1392,6 +1401,10 @@ pub fn validate_slash_command_input(
validate_no_args(command, &args)?;
SlashCommand::Doctor
}
"setup" => {
validate_no_args(command, &args)?;
SlashCommand::Setup
}
"login" | "logout" => {
return Err(command_error(
"This auth flow was removed. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN instead.",
@@ -1572,7 +1585,10 @@ fn parse_clear_args(args: &[&str]) -> Result<bool, SlashCommandParseError> {
fn parse_config_section(args: &[&str]) -> Result<Option<String>, SlashCommandParseError> {
let section = optional_single_arg("config", args, "[env|hooks|model|plugins]")?;
if let Some(section) = section {
if matches!(section.as_str(), "env" | "hooks" | "model" | "plugins") {
if matches!(
section.as_str(),
"env" | "hooks" | "model" | "plugins" | "help"
) {
return Ok(Some(section));
}
return Err(command_error(
@@ -1911,7 +1927,7 @@ fn slash_command_category(name: &str) -> &'static str {
| "stickers" | "language" | "profile" | "max-tokens" | "temperature" | "system-prompt"
| "api-key" | "terminal-setup" | "notifications" | "telemetry" | "providers" | "env"
| "project" | "reasoning" | "budget" | "rate-limit" | "workspace" | "reset" | "ide"
| "desktop" | "upgrade" => "Config",
| "desktop" | "upgrade" | "setup" => "Config",
"debug-tool-call" | "doctor" | "sandbox" | "diagnostics" | "tool-details" | "changelog"
| "metrics" => "Debug",
_ => "Tools",
@@ -2147,7 +2163,7 @@ impl DefinitionSource {
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct AgentSummary {
pub(crate) struct AgentSummary {
name: String,
description: Option<String>,
model: Option<String>,
@@ -2158,6 +2174,20 @@ struct AgentSummary {
path: Option<PathBuf>,
}
/// An agent definition file that could not be loaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct InvalidAgentConfig {
pub(crate) path: PathBuf,
pub(crate) reason: String,
}
/// Loaded agent definitions plus any invalid entries that were skipped.
#[derive(Debug, Clone, Default)]
pub(crate) struct AgentCollection {
pub(crate) agents: Vec<AgentSummary>,
pub(crate) invalid_agents: Vec<InvalidAgentConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SkillSummary {
name: String,
@@ -2167,6 +2197,23 @@ struct SkillSummary {
origin: SkillOrigin,
// #729: on-disk path parity with AgentSummary
path: Option<PathBuf>,
// #445: directory name for detecting name/dir mismatch
dir_name: Option<String>,
}
/// A skill where the frontmatter name differs from the directory name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SkillMetadataDrift {
pub(crate) dir_name: String,
pub(crate) frontmatter_name: String,
pub(crate) path: PathBuf,
}
/// Loaded skill definitions plus any metadata drift entries.
#[derive(Debug, Clone, Default)]
pub(crate) struct SkillCollection {
pub(crate) skills: Vec<SkillSummary>,
pub(crate) metadata_drift: Vec<SkillMetadataDrift>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -2280,13 +2327,15 @@ pub fn handle_plugins_slash_command(
});
};
let plugin = resolve_plugin_target(manager, target)?;
let already_enabled = plugin.enabled;
manager.enable(&plugin.metadata.id)?;
Ok(PluginsCommandResult {
message: format!(
"Plugins\n Result enabled {}\n Name {}\n Version {}\n Status enabled",
plugin.metadata.id, plugin.metadata.name, plugin.metadata.version
"Plugins\n Result {}\n Name {}\n Version {}\n Status enabled",
if already_enabled { "already enabled" } else { "enabled" },
plugin.metadata.name, plugin.metadata.version
),
reload_runtime: true,
reload_runtime: !already_enabled,
})
}
Some("disable") => {
@@ -2297,13 +2346,15 @@ pub fn handle_plugins_slash_command(
});
};
let plugin = resolve_plugin_target(manager, target)?;
let already_disabled = !plugin.enabled;
manager.disable(&plugin.metadata.id)?;
Ok(PluginsCommandResult {
message: format!(
"Plugins\n Result disabled {}\n Name {}\n Version {}\n Status disabled",
plugin.metadata.id, plugin.metadata.name, plugin.metadata.version
"Plugins\n Result {}\n Name {}\n Version {}\n Status disabled",
if already_disabled { "already disabled" } else { "disabled" },
plugin.metadata.name, plugin.metadata.version
),
reload_runtime: true,
reload_runtime: !already_disabled,
})
}
Some("remove") | Some("uninstall") => {
@@ -2494,8 +2545,8 @@ pub fn handle_agents_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
match normalize_optional_args(args) {
None | Some("list") => {
let roots = discover_definition_roots(cwd, "agents");
let agents = load_agents_from_roots(&roots)?;
Ok(render_agents_report_json(cwd, &agents))
let collection = load_agents_from_roots_with_invalids(&roots)?;
Ok(render_agents_report_json(cwd, &collection))
}
Some(args) if args.starts_with("list ") => {
let filter = args["list ".len()..].trim().to_lowercase();
@@ -2512,17 +2563,26 @@ pub fn handle_agents_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
}));
}
let roots = discover_definition_roots(cwd, "agents");
let agents = load_agents_from_roots(&roots)?;
let filtered: Vec<_> = agents
let collection = load_agents_from_roots_with_invalids(&roots)?;
let filtered_agents: Vec<_> = collection
.agents
.into_iter()
.filter(|a| a.name.to_lowercase().contains(&filter))
.collect();
Ok(render_agents_report_json(cwd, &filtered))
let filtered_collection = AgentCollection {
agents: filtered_agents,
invalid_agents: collection.invalid_agents,
};
Ok(render_agents_report_json(cwd, &filtered_collection))
}
Some("show" | "info" | "describe") => {
let roots = discover_definition_roots(cwd, "agents");
let agents = load_agents_from_roots(&roots)?;
Ok(render_agents_report_json_with_action(cwd, &agents, "show"))
let collection = load_agents_from_roots_with_invalids(&roots)?;
Ok(render_agents_report_json_with_action(
cwd,
&collection,
"show",
))
}
Some(args)
if args.starts_with("show ")
@@ -2553,8 +2613,9 @@ pub fn handle_agents_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
}));
}
let roots = discover_definition_roots(cwd, "agents");
let agents = load_agents_from_roots(&roots)?;
let matched: Vec<_> = agents
let collection = load_agents_from_roots_with_invalids(&roots)?;
let matched: Vec<_> = collection
.agents
.into_iter()
.filter(|a| a.name.to_lowercase() == name)
.collect();
@@ -2571,7 +2632,15 @@ pub fn handle_agents_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
"hint": "Run `claw agents list` to see available agents.",
}));
}
Ok(render_agents_report_json_with_action(cwd, &matched, "show"))
let matched_collection = AgentCollection {
agents: matched,
invalid_agents: collection.invalid_agents,
};
Ok(render_agents_report_json_with_action(
cwd,
&matched_collection,
"show",
))
}
Some("create") => Ok(render_agents_missing_argument_json("create", "agent_name")),
Some(args) if args.starts_with("create ") => {
@@ -2704,15 +2773,26 @@ pub fn handle_skills_slash_command(args: Option<&str>, cwd: &Path) -> std::io::R
std::io::ErrorKind::InvalidInput,
"missing_argument: skills install requires an install source.\nUsage: claw skills install <path>",
)),
// #95: support --project flag for project-level install
Some(args) if args.starts_with("install ") => {
let target = args["install ".len()..].trim();
let rest = args["install ".len()..].trim();
let (target, project_flag) = if let Some(t) = rest.strip_prefix("--project") {
(t.trim_start().trim_start_matches('=').trim(), true)
} else {
(rest, false)
};
if target.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"missing_argument: skills install requires an install source.\nUsage: claw skills install <path>",
"missing_argument: skills install requires an install source.\nUsage: claw skills install [--project] <path>",
));
}
let install = install_skill(target, cwd)?;
let install = if project_flag {
let project_root = cwd.join(".claw").join("skills");
install_skill_into(target, cwd, &project_root)?
} else {
install_skill(target, cwd)?
};
Ok(render_skill_install_report(&install))
}
Some("uninstall" | "remove" | "delete") => Err(std::io::Error::new(
@@ -2766,8 +2846,8 @@ pub fn handle_skills_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
match normalize_optional_args(args) {
None | Some("list") => {
let roots = discover_skill_roots(cwd);
let skills = load_skills_from_roots(&roots)?;
Ok(render_skills_report_json_with_action(&skills, "list"))
let collection = load_skills_from_roots_with_drift(&roots)?;
Ok(render_skills_report_json_with_action(&collection, "list"))
}
Some(args) if args.starts_with("list ") => {
let filter = args["list ".len()..].trim().to_lowercase();
@@ -2784,17 +2864,25 @@ pub fn handle_skills_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
}));
}
let roots = discover_skill_roots(cwd);
let skills = load_skills_from_roots(&roots)?;
let filtered: Vec<_> = skills
let collection = load_skills_from_roots_with_drift(&roots)?;
let filtered_skills: Vec<_> = collection
.skills
.into_iter()
.filter(|s| s.name.to_lowercase().contains(&filter))
.collect();
Ok(render_skills_report_json_with_action(&filtered, "list"))
let filtered_collection = SkillCollection {
skills: filtered_skills,
metadata_drift: collection.metadata_drift,
};
Ok(render_skills_report_json_with_action(
&filtered_collection,
"list",
))
}
Some("show" | "info" | "describe") => {
let roots = discover_skill_roots(cwd);
let skills = load_skills_from_roots(&roots)?;
Ok(render_skills_report_json_with_action(&skills, "show"))
let collection = load_skills_from_roots_with_drift(&roots)?;
Ok(render_skills_report_json_with_action(&collection, "show"))
}
Some(args)
if args.starts_with("show ")
@@ -2825,8 +2913,9 @@ pub fn handle_skills_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
}));
}
let roots = discover_skill_roots(cwd);
let skills = load_skills_from_roots(&roots)?;
let matched: Vec<_> = skills
let collection = load_skills_from_roots_with_drift(&roots)?;
let matched: Vec<_> = collection
.skills
.into_iter()
.filter(|s| s.name.to_lowercase() == name)
.collect();
@@ -2843,23 +2932,42 @@ pub fn handle_skills_slash_command_json(args: Option<&str>, cwd: &Path) -> std::
"hint": "Run `claw skills list` to see available skills.",
}));
}
Ok(render_skills_report_json_with_action(&matched, "show"))
let matched_collection = SkillCollection {
skills: matched,
metadata_drift: collection.metadata_drift,
};
Ok(render_skills_report_json_with_action(
&matched_collection,
"show",
))
}
Some("install") => Ok(render_skills_missing_argument_json(
"install",
"install_source",
"Usage: claw skills install <path>",
)),
// #95: support --project flag for project-level install
Some(args) if args.starts_with("install ") => {
let target = args["install ".len()..].trim();
let rest = args["install ".len()..].trim();
let (target, project_flag) = if let Some(t) = rest.strip_prefix("--project") {
(t.trim_start().trim_start_matches('=').trim(), true)
} else {
(rest, false)
};
if target.is_empty() {
return Ok(render_skills_missing_argument_json(
"install",
"install_source",
"Usage: claw skills install <path>",
"Usage: claw skills install [--project] <path>",
));
}
match install_skill(target, cwd) {
let result = if project_flag {
let project_root = cwd.join(".claw").join("skills");
install_skill_into(target, cwd, &project_root)
} else {
install_skill(target, cwd)
};
match result {
Ok(install) => Ok(render_skill_install_report_json(&install)),
Err(error) => Ok(render_skill_install_error_json(target, &error)),
}
@@ -3243,7 +3351,15 @@ fn render_mcp_report_json_for(
"use `claw mcp show <server>` to inspect a server",
))
}
Some(args) => Ok(render_mcp_usage_json(Some(args))),
Some(args) => {
// #681: unsupported mutation verbs (add, remove, delete, enable, disable)
// and other unknown sub-actions return a typed error instead of help with exit 0.
let verb = args.split_whitespace().next().unwrap_or(args);
Ok(render_mcp_unsupported_action_json(
args,
&format!("`{verb}` is not a supported MCP sub-action; supported actions: list, show, help"),
))
}
}
}
@@ -3902,30 +4018,69 @@ fn push_unique_skill_root(
fn load_agents_from_roots(
roots: &[(DefinitionSource, PathBuf)],
) -> std::io::Result<Vec<AgentSummary>> {
let collection = load_agents_from_roots_with_invalids(roots)?;
Ok(collection.agents)
}
/// Load agent definitions from all roots, collecting both valid agents and
/// invalid entries (wrong extension, broken frontmatter, etc.).
fn load_agents_from_roots_with_invalids(
roots: &[(DefinitionSource, PathBuf)],
) -> std::io::Result<AgentCollection> {
let mut agents = Vec::new();
let mut invalid_agents = Vec::new();
let mut active_sources = BTreeMap::<String, DefinitionSource>::new();
for (source, root) in roots {
let mut root_agents = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
if entry.path().extension().is_none_or(|ext| ext != "toml") {
continue;
let path = entry.path();
let ext = path.extension().and_then(|e| e.to_str());
match ext {
Some("toml") => {
let contents = fs::read_to_string(&path)?;
let fallback_name = path.file_stem().map_or_else(
|| entry.file_name().to_string_lossy().to_string(),
|stem| stem.to_string_lossy().to_string(),
);
root_agents.push(AgentSummary {
name: parse_toml_string(&contents, "name").unwrap_or(fallback_name),
description: parse_toml_string(&contents, "description"),
model: parse_toml_string(&contents, "model"),
reasoning_effort: parse_toml_string(&contents, "model_reasoning_effort"),
source: *source,
shadowed_by: None,
path: Some(path),
});
}
Some("md") => {
let contents = fs::read_to_string(&path)?;
let (name, description, model, reasoning_effort) =
parse_agent_frontmatter(&contents);
if name.is_none() && description.is_none() {
invalid_agents.push(InvalidAgentConfig {
path,
reason: "Markdown agent file has no YAML frontmatter with name or description fields".to_string(),
});
continue;
}
let fallback_name = path.file_stem().map_or_else(
|| entry.file_name().to_string_lossy().to_string(),
|stem| stem.to_string_lossy().to_string(),
);
root_agents.push(AgentSummary {
name: name.unwrap_or(fallback_name),
description,
model,
reasoning_effort,
source: *source,
shadowed_by: None,
path: Some(path),
});
}
_ => continue,
}
let contents = fs::read_to_string(entry.path())?;
let fallback_name = entry.path().file_stem().map_or_else(
|| entry.file_name().to_string_lossy().to_string(),
|stem| stem.to_string_lossy().to_string(),
);
root_agents.push(AgentSummary {
name: parse_toml_string(&contents, "name").unwrap_or(fallback_name),
description: parse_toml_string(&contents, "description"),
model: parse_toml_string(&contents, "model"),
reasoning_effort: parse_toml_string(&contents, "model_reasoning_effort"),
source: *source,
shadowed_by: None,
path: Some(entry.path()),
});
}
root_agents.sort_by(|left, right| left.name.cmp(&right.name));
@@ -3940,11 +4095,22 @@ fn load_agents_from_roots(
}
}
Ok(agents)
Ok(AgentCollection {
agents,
invalid_agents,
})
}
fn load_skills_from_roots(roots: &[SkillRoot]) -> std::io::Result<Vec<SkillSummary>> {
let collection = load_skills_from_roots_with_drift(roots)?;
Ok(collection.skills)
}
/// Load skill definitions from all roots, collecting metadata drift entries
/// where the frontmatter name differs from the directory name.
fn load_skills_from_roots_with_drift(roots: &[SkillRoot]) -> std::io::Result<SkillCollection> {
let mut skills = Vec::new();
let mut metadata_drift = Vec::new();
let mut active_sources = BTreeMap::<String, DefinitionSource>::new();
for root in roots {
@@ -3961,15 +4127,26 @@ fn load_skills_from_roots(roots: &[SkillRoot]) -> std::io::Result<Vec<SkillSumma
continue;
}
let contents = fs::read_to_string(skill_path)?;
let dir_name = entry.file_name().to_string_lossy().to_string();
let (name, description) = parse_skill_frontmatter(&contents);
// #445: detect name/dir mismatch
if let Some(ref frontmatter_name) = name {
if frontmatter_name != &dir_name {
metadata_drift.push(SkillMetadataDrift {
dir_name: dir_name.clone(),
frontmatter_name: frontmatter_name.clone(),
path: entry.path(),
});
}
}
root_skills.push(SkillSummary {
name: name
.unwrap_or_else(|| entry.file_name().to_string_lossy().to_string()),
name: name.unwrap_or_else(|| dir_name.clone()),
description,
source: root.source,
shadowed_by: None,
origin: root.origin,
path: Some(entry.path()),
dir_name: Some(dir_name),
});
}
SkillOrigin::LegacyCommandsDir => {
@@ -4002,6 +4179,7 @@ fn load_skills_from_roots(roots: &[SkillRoot]) -> std::io::Result<Vec<SkillSumma
shadowed_by: None,
origin: root.origin,
path: Some(markdown_path),
dir_name: None,
});
}
}
@@ -4019,7 +4197,10 @@ fn load_skills_from_roots(roots: &[SkillRoot]) -> std::io::Result<Vec<SkillSumma
}
}
Ok(skills)
Ok(SkillCollection {
skills,
metadata_drift,
})
}
fn parse_toml_string(contents: &str, key: &str) -> Option<String> {
@@ -4091,6 +4272,63 @@ fn unquote_frontmatter_value(value: &str) -> String {
.to_string()
}
/// Parse agent metadata from YAML frontmatter in `.md` agent files.
/// Returns (name, description, model, reasoning_effort) extracted from
/// the `---`-delimited YAML block at the top of the file.
fn parse_agent_frontmatter(
contents: &str,
) -> (
Option<String>,
Option<String>,
Option<String>,
Option<String>,
) {
let mut lines = contents.lines();
if lines.next().map(str::trim) != Some("---") {
return (None, None, None, None);
}
let mut name = None;
let mut description = None;
let mut model = None;
let mut reasoning_effort = None;
for line in lines {
let trimmed = line.trim();
if trimmed == "---" {
break;
}
if let Some(value) = trimmed.strip_prefix("name:") {
let value = unquote_frontmatter_value(value.trim());
if !value.is_empty() {
name = Some(value);
}
continue;
}
if let Some(value) = trimmed.strip_prefix("description:") {
let value = unquote_frontmatter_value(value.trim());
if !value.is_empty() {
description = Some(value);
}
continue;
}
if let Some(value) = trimmed.strip_prefix("model:") {
let value = unquote_frontmatter_value(value.trim());
if !value.is_empty() {
model = Some(value);
}
continue;
}
if let Some(value) = trimmed.strip_prefix("model_reasoning_effort:") {
let value = unquote_frontmatter_value(value.trim());
if !value.is_empty() {
reasoning_effort = Some(value);
}
}
}
(name, description, model, reasoning_effort)
}
fn render_agents_report(agents: &[AgentSummary]) -> String {
if agents.is_empty() {
return "No agents found.".to_string();
@@ -4133,31 +4371,42 @@ fn render_agents_report(agents: &[AgentSummary]) -> String {
lines.join("\n").trim_end().to_string()
}
fn render_agents_report_json(cwd: &Path, agents: &[AgentSummary]) -> Value {
render_agents_report_json_with_action(cwd, agents, "list")
fn render_agents_report_json(cwd: &Path, collection: &AgentCollection) -> Value {
render_agents_report_json_with_action(cwd, collection, "list")
}
fn render_agents_report_json_with_action(
cwd: &Path,
agents: &[AgentSummary],
collection: &AgentCollection,
action: &str,
) -> Value {
let agents = &collection.agents;
let invalid_agents = &collection.invalid_agents;
let active = agents
.iter()
.filter(|agent| agent.shadowed_by.is_none())
.count();
let has_invalids = !invalid_agents.is_empty();
let status = if has_invalids { "degraded" } else { "ok" };
json!({
"kind": "agents",
"status": "ok",
"status": status,
"action": action,
"working_directory": cwd.display().to_string(),
"count": agents.len(),
"valid_count": agents.len(),
"invalid_count": invalid_agents.len(),
"summary": {
"total": agents.len(),
"active": active,
"shadowed": agents.len().saturating_sub(active),
},
"agents": agents.iter().map(agent_summary_json).collect::<Vec<_>>(),
"invalid_agents": invalid_agents.iter().map(|invalid| json!({
"path": invalid.path.display().to_string(),
"reason": &invalid.reason,
"valid": false,
})).collect::<Vec<_>>(),
})
}
@@ -4277,21 +4526,34 @@ fn render_skills_report(skills: &[SkillSummary]) -> String {
lines.join("\n").trim_end().to_string()
}
fn render_skills_report_json_with_action(skills: &[SkillSummary], action: &str) -> Value {
fn render_skills_report_json_with_action(collection: &SkillCollection, action: &str) -> Value {
let skills = &collection.skills;
let metadata_drift = &collection.metadata_drift;
let active = skills
.iter()
.filter(|skill| skill.shadowed_by.is_none())
.count();
let has_drift = !metadata_drift.is_empty();
let status = if has_drift { "degraded" } else { "ok" };
// #410: add `count` field for polymorphic consumption parity with agents list
json!({
"kind": "skills",
"status": "ok",
"status": status,
"action": action,
"count": skills.len(),
"valid_count": skills.len(),
"metadata_drift_count": metadata_drift.len(),
"summary": {
"total": skills.len(),
"active": active,
"shadowed": skills.len().saturating_sub(active),
},
"skills": skills.iter().map(skill_summary_json).collect::<Vec<_>>(),
"metadata_drift": metadata_drift.iter().map(|drift| json!({
"dir_name": &drift.dir_name,
"frontmatter_name": &drift.frontmatter_name,
"path": drift.path.display().to_string(),
})).collect::<Vec<_>>(),
})
}
@@ -4467,6 +4729,7 @@ fn render_mcp_summary_report_json(cwd: &Path, mcp: &McpConfigCollection) -> Valu
json!({
"kind": "mcp",
"action": "list",
"count": mcp.valid_count(),
"working_directory": cwd.display().to_string(),
"configured_servers": mcp.valid_count(),
"total_configured": mcp.total_configured(),
@@ -4652,7 +4915,7 @@ fn render_agents_usage_json(unexpected: Option<&str>) -> Value {
"direct_cli": "claw agents [list|show <name>|create <name>|help]",
"format": "toml",
"create": "claw agents create <name>",
"sources": [".claw/agents", "~/.claw/agents", "$CLAW_CONFIG_HOME/agents"],
"sources": [".claw/agents", "~/.claw/agents", "~/.codex/agents", "$CLAW_CONFIG_HOME/agents"],
},
"unexpected": unexpected,
})
@@ -4661,12 +4924,12 @@ fn render_agents_usage_json(unexpected: Option<&str>) -> Value {
fn render_skills_usage(unexpected: Option<&str>) -> String {
let mut lines = vec![
"Skills".to_string(),
" Usage /skills [list|show <name>|install <path>|uninstall <name>|help|<skill> [args]]".to_string(),
" Usage /skills [list|show <name>|install [--project] <path>|uninstall <name>|help|<skill> [args]]".to_string(),
" Alias /skill".to_string(),
" Direct CLI claw skills [list|show <name>|install <path>|uninstall <name>|help|<skill> [args]]".to_string(),
" Direct CLI claw skills [list|show <name>|install [--project] <path>|uninstall <name>|help|<skill> [args]]".to_string(),
" Lifecycle install <path>, uninstall <name>".to_string(),
" Invoke /skills help overview -> $help overview".to_string(),
" Install root $CLAW_CONFIG_HOME/skills or ~/.claw/skills".to_string(),
" Install root $CLAW_CONFIG_HOME/skills or ~/.claw/skills (use --project for .claw/skills)".to_string(),
" Sources .claw/skills, .omc/skills, .agents/skills, .codex/skills, .claude/skills, ~/.claw/skills, ~/.omc/skills, ~/.claude/skills/omc-learned, ~/.codex/skills, ~/.claude/skills, legacy /commands".to_string(),
];
if let Some(args) = unexpected {
@@ -4782,7 +5045,7 @@ fn render_mcp_usage_json(unexpected: Option<&str>) -> Value {
"usage": {
"slash_command": "/mcp [list|show <server>|help]",
"direct_cli": "claw mcp [list|show <server>|help]",
"sources": [".claw/settings.json", ".claw/settings.local.json"],
"sources": [".claw.json", ".claw/settings.json", ".claw/settings.local.json"],
},
"unexpected": unexpected,
})
@@ -4970,34 +5233,51 @@ fn mcp_oauth_json(oauth: Option<&McpOAuthConfig>) -> Value {
}
fn mcp_server_details_json(config: &McpServerConfig) -> Value {
// #90: redact sensitive fields — args/url/headers_helper can contain
// credentials. Show structure without leaking secrets.
match config {
McpServerConfig::Stdio(config) => json!({
"command": &config.command,
"args": &config.args,
"args_count": config.args.len(),
"env_keys": config.env.keys().cloned().collect::<Vec<_>>(),
"tool_call_timeout_ms": config.tool_call_timeout_ms,
}),
McpServerConfig::Sse(config) | McpServerConfig::Http(config) => json!({
"url": &config.url,
"header_keys": config.headers.keys().cloned().collect::<Vec<_>>(),
"headers_helper": &config.headers_helper,
"oauth": mcp_oauth_json(config.oauth.as_ref()),
}),
McpServerConfig::Ws(config) => json!({
"url": &config.url,
"header_keys": config.headers.keys().cloned().collect::<Vec<_>>(),
"headers_helper": &config.headers_helper,
}),
McpServerConfig::Sse(config) | McpServerConfig::Http(config) => {
let redacted_url = redact_url(&config.url);
json!({
"url": redacted_url,
"header_keys": config.headers.keys().cloned().collect::<Vec<_>>(),
"headers_helper_configured": config.headers_helper.is_some(),
"oauth": mcp_oauth_json(config.oauth.as_ref()),
})
}
McpServerConfig::Ws(config) => {
let redacted_url = redact_url(&config.url);
json!({
"url": redacted_url,
"header_keys": config.headers.keys().cloned().collect::<Vec<_>>(),
"headers_helper_configured": config.headers_helper.is_some(),
})
}
McpServerConfig::Sdk(config) => json!({
"name": &config.name,
}),
McpServerConfig::ManagedProxy(config) => json!({
"url": &config.url,
"url": redact_url(&config.url),
"id": &config.id,
}),
}
}
fn redact_url(url: &str) -> String {
// #90: strip query params which may contain tokens, keep scheme+host+path
if let Some(query_start) = url.find('?') {
format!("{}?...", &url[..query_start])
} else {
url.to_string()
}
}
fn mcp_server_json(name: &str, server: &ScopedMcpServerConfig) -> Value {
json!({
"name": name,
@@ -5114,6 +5394,7 @@ pub fn handle_slash_command(
| SlashCommand::AddDir { .. }
| SlashCommand::History { .. }
| SlashCommand::Team { .. }
| SlashCommand::Setup
| SlashCommand::Unknown(_) => None,
}
}
@@ -5127,7 +5408,7 @@ mod tests {
render_agents_report_json, render_mcp_report_json_for, render_plugins_report,
render_plugins_report_with_failures, render_skills_report, render_slash_command_help,
render_slash_command_help_detail, resolve_skill_path, resume_supported_slash_commands,
slash_command_specs, suggest_slash_commands, validate_slash_command_input,
slash_command_specs, suggest_slash_commands, validate_slash_command_input, AgentCollection,
DefinitionSource, SkillOrigin, SkillRoot, SkillSlashDispatch, SlashCommand,
};
use plugins::{
@@ -5730,7 +6011,8 @@ mod tests {
assert!(help.contains("aliases: /skill"));
assert!(!help.contains("/login"));
assert!(!help.contains("/logout"));
assert_eq!(slash_command_specs().len(), 139);
assert!(help.contains("/setup"));
assert_eq!(slash_command_specs().len(), 140);
assert!(resume_supported_slash_commands().len() >= 39);
}
@@ -6121,7 +6403,10 @@ mod tests {
];
let report = render_agents_report_json(
&workspace,
&load_agents_from_roots(&roots).expect("agent roots should load"),
&AgentCollection {
agents: load_agents_from_roots(&roots).expect("agent roots should load"),
invalid_agents: Vec::new(),
},
);
assert_eq!(report["kind"], "agents");
@@ -6274,7 +6559,10 @@ mod tests {
},
];
let report = super::render_skills_report_json_with_action(
&load_skills_from_roots(&roots).expect("skills should load"),
&super::SkillCollection {
skills: load_skills_from_roots(&roots).expect("skills should load"),
metadata_drift: Vec::new(),
},
"list",
);
assert_eq!(report["kind"], "skills");
@@ -6352,12 +6640,13 @@ mod tests {
let skills_help =
super::handle_skills_slash_command(Some("--help"), &cwd).expect("skills help");
assert!(skills_help.contains(
"Usage /skills [list|show <name>|install <path>|uninstall <name>|help|<skill> [args]]"
"Usage /skills [list|show <name>|install [--project] <path>|uninstall <name>|help|<skill> [args]]"
));
assert!(skills_help.contains("Alias /skill"));
assert!(skills_help.contains("Lifecycle install <path>, uninstall <name>"));
assert!(skills_help.contains("Invoke /skills help overview -> $help overview"));
assert!(skills_help.contains("Install root $CLAW_CONFIG_HOME/skills or ~/.claw/skills"));
// #95: install root now mentions --project flag
assert!(skills_help.contains("Install root $CLAW_CONFIG_HOME/skills or ~/.claw/skills (use --project for .claw/skills)"));
assert!(skills_help.contains(".omc/skills"));
assert!(skills_help.contains(".agents/skills"));
assert!(skills_help.contains("~/.claude/skills/omc-learned"));
@@ -6370,7 +6659,7 @@ mod tests {
let skills_install_help = super::handle_skills_slash_command(Some("install --help"), &cwd)
.expect("nested skills help");
assert!(skills_install_help.contains(
"Usage /skills [list|show <name>|install <path>|uninstall <name>|help|<skill> [args]]"
"Usage /skills [list|show <name>|install [--project] <path>|uninstall <name>|help|<skill> [args]]"
));
assert!(skills_install_help.contains("Alias /skill"));
assert!(skills_install_help.contains("Unexpected install"));
@@ -6378,7 +6667,7 @@ mod tests {
let skills_unknown_help =
super::handle_skills_slash_command(Some("show --help"), &cwd).expect("skills help");
assert!(skills_unknown_help.contains(
"Usage /skills [list|show <name>|install <path>|uninstall <name>|help|<skill> [args]]"
"Usage /skills [list|show <name>|install [--project] <path>|uninstall <name>|help|<skill> [args]]"
));
assert!(skills_unknown_help.contains("Unexpected show"));
@@ -6647,7 +6936,7 @@ mod tests {
let help =
render_mcp_report_json_for(&loader, &workspace, Some("help")).expect("mcp help json");
assert_eq!(help["action"], "help");
assert_eq!(help["usage"]["sources"][0], ".claw/settings.json");
assert_eq!(help["usage"]["sources"][0], ".claw.json");
let _ = fs::remove_dir_all(workspace);
let _ = fs::remove_dir_all(config_home);
@@ -6845,7 +7134,7 @@ mod tests {
let disable = handle_plugins_slash_command(Some("disable"), Some("demo"), &mut manager)
.expect("disable command should succeed");
assert!(disable.reload_runtime);
assert!(disable.message.contains("disabled demo@external"));
assert!(disable.message.contains("Result disabled"));
assert!(disable.message.contains("Name demo"));
assert!(disable.message.contains("Status disabled"));
@@ -6857,7 +7146,7 @@ mod tests {
let enable = handle_plugins_slash_command(Some("enable"), Some("demo"), &mut manager)
.expect("enable command should succeed");
assert!(enable.reload_runtime);
assert!(enable.message.contains("enabled demo@external"));
assert!(enable.message.contains("Result enabled"));
assert!(enable.message.contains("Name demo"));
assert!(enable.message.contains("Status enabled"));

View File

@@ -0,0 +1,39 @@
# AGENTS.md — plugins crate
## OVERVIEW
Plugin subsystem: how third-party, builtin, and bundled tools/commands/hooks enter the runtime.
## WHERE TO LOOK
- `src/lib.rs` (~3,863 lines): the bulk of the crate. Manifest parsing (`.claude-plugin/plugin.json`), installed-plugin registry, lifecycle model, permission model, install/update management.
- `src/hooks.rs`: hook event model (`HookEvent`, `HookRunResult`) and `HookRunner` for shell-hook execution. Re-exported from `lib.rs`. **Caution:** the runtime crate has its own `hooks.rs` with a separate `HookRunner` (execution + abort-signal side, around L155). Know which layer you need before editing.
- `src/test_isolation.rs`: test isolation helpers.
- `bundled/`: example plugin fixtures. `example-bundled/` and `sample-hooks/` each contain `.claude-plugin/plugin.json` plus `pre.sh`/`post.sh` shell hooks. Treat these as the reference shape when authoring a new plugin.
## CONVENTIONS
**Key public types** (all in `src/lib.rs` unless noted):
- Kinds/definitions: `PluginKind`, `PluginDefinition`, `BuiltinPlugin`, `BundledPlugin`, `ExternalPlugin`.
- Manifests: `PluginManifest`, `PluginToolManifest`, `PluginToolDefinition`, `PluginToolPermission`, `PluginCommandManifest`.
- Hooks: `PluginHooks`, `HookEvent`, `HookRunResult` (from `hooks.rs`).
- Lifecycle/permissions: `PluginLifecycle`, `PluginPermission`.
- Registry: `InstalledPluginRecord`, `InstalledPluginRegistry`, `RegisteredPlugin`, `PluginRegistry` (+ `Report`, `Summary`, `LoadFailure`).
- Management: `PluginManager` (+ `Config`), `InstallOutcome`, `UpdateOutcome`.
- Trait: `Plugin`.
- Errors: `PluginError`.
- Entry points: `builtin_plugins()`, `load_plugin_from_directory()`.
**Lifecycle spans two crates.** Manifest parsing and registry live here. Health checks, degraded-mode, and `PluginState` live in `runtime/src/plugin_lifecycle.rs`. Changes to plugin lifecycle logic often touch both.
**Plugin shape.** A plugin directory contains `.claude-plugin/plugin.json` at minimum. Shell hooks (`pre.sh`, `post.sh`) sit alongside. See `bundled/` for working examples.
**Consumers.** `PluginManager` has ~48 references across the workspace. CLI wires plugins via `RuntimePluginStateBuildOutput` in `rusty-claude-cli`. The tools crate exposes plugin tools through `GlobalToolRegistry`.
## NOTES
- Don't confuse the two `HookRunner` implementations. This crate's version handles the event model. The runtime crate's version handles execution and abort signals.
- `lib.rs` is large. Most searches for plugin behavior start and end there.
- Bundled plugin fixtures under `bundled/` are used in tests. Breaking their structure breaks CI.
- Permission model is enforced at install time and checked at runtime. Both paths matter when modifying `PluginPermission`.

View File

@@ -0,0 +1,46 @@
# AGENTS.md — runtime crate
## OVERVIEW
Core crate of `claw`: session persistence, permissions, prompt assembly, MCP plumbing, tool-facing file ops, conversation loop. 47 flat modules in src/, ~330 pub symbols, ~170 re-exported flat from lib.rs.
## WHERE TO LOOK
| Group | Files | Entry points |
|---|---|---|
| session/conversation | session.rs, session_control.rs, conversation.rs, compact.rs, summary_compression.rs, usage.rs | `Session` (L117), `SessionStore`, `ConversationRuntime` (L130), `ApiClient`/`ToolExecutor` traits |
| config | config.rs, config_validate.rs, bootstrap.rs | `ConfigLoader` (L409), type-export heaviest file; MCP server config enums live here |
| MCP (6-file split) | mcp.rs, mcp_client.rs, mcp_stdio.rs, mcp_server.rs, mcp_tool_bridge.rs, mcp_lifecycle_hardened.rs | `McpServerManager` (L488 in mcp_stdio.rs), JSON-RPC spawn |
| hooks/plugins | hooks.rs, plugin_lifecycle.rs | `HookRunner` (L155), abort signal, healthcheck, degraded mode |
| permissions/safety | permissions.rs, permission_enforcer.rs, policy_engine.rs, approval_tokens.rs, sandbox.rs, bash_validation.rs, trust_resolver.rs | `PermissionEnforcer` (L27), `GreenLevel`, lane decisions |
| tools/execution | bash.rs, file_ops.rs, lsp_client.rs | `execute_bash`, `*_in_workspace` file op variants |
| lane/worker | lane_events.rs, worker_boot.rs, task_packet.rs, task_registry.rs, team_cron_registry.rs, branch_lock.rs, stale_base.rs, stale_branch.rs | `LaneEvent` dedupe/provenance, `LaneBoard` |
| prompt | prompt.rs | `SystemPromptBuilder`, `ContextFile`, dynamic boundary marker |
| git/remote/auth | git_context.rs, remote.rs, oauth.rs | Upstream proxy, PKCE flow |
| misc | json.rs, sse.rs, g004_conformance.rs, green_contract.rs, recovery_recipes.rs, report_schema.rs, trident.rs | Report v1 + redaction |
Largest files by line count: config.rs (3894), mcp_stdio.rs (2969), lane_events.rs (2561), worker_boot.rs (2441), session.rs (1961), conversation.rs (1878).
## CONVENTIONS
- One file per module, flat layout. No subdirectories.
- Most modules are private `mod x` with selective `pub use`. 21 modules are `pub mod`, so consumers use both the re-export and the qualified path.
- Deps kept minimal: serde, tokio, glob, regex, sha2, walkdir + internal plugins/telemetry. No reqwest, no async-trait. Remote/SSE done by hand.
- Inline `#[cfg(test)]` tests per file. session.rs has two test modules.
- `pub(crate) test_env_lock()` mutex in lib.rs serializes env-mutating tests. Use it when touching env vars.
- trust_resolver.rs is `#[cfg(test)]`-gated yet pub-used: test-only API surface.
## INVARIANTS (do not break)
1. **Compaction pairs**: compact.rs must never split assistant(ToolUse)/ToolResult pairs.
2. **No side effects on construction**: SessionStore construction must not create `.claw` directories (session_control.rs:1090).
3. **Workspace containment**: file_ops.rs workspace ops must not escape the workspace root.
4. **Permission ordering**: a leading read-only permission token must not launder a trailing destructive one (permission_enforcer.rs:450).
## ANTI-PATTERNS
- Don't extend whole-file `#![allow(...)]` blocks. They exist as legacy tolerance in worker_boot.rs, mcp_tool_bridge.rs, lsp_client.rs, stale_branch.rs, stale_base.rs, recovery_recipes.rs, mcp_lifecycle_hardened.rs, session_control.rs. Adding new ones is not acceptable.
- Don't add reqwest or async-trait as deps. Remote calls go through the manual SSE/proxy layer in remote.rs and sse.rs.
- Don't create subdirectories under src/. The flat module layout is intentional.
- Don't bypass `*_in_workspace` variants for file ops when running inside a workspace context. The unchecked versions exist for bootstrap and out-of-workspace scenarios only.
- Don't add new `pub mod` exports without reason. Prefer private mod + selective `pub use` from lib.rs.

View File

@@ -125,6 +125,27 @@ pub struct RuntimePluginConfig {
max_output_tokens: Option<u32>,
}
/// API timeout and retry configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiTimeoutConfig {
/// Connect timeout in seconds. Defaults to 30.
pub connect_timeout_secs: u64,
/// Request timeout in seconds. Defaults to 300 (5 minutes).
pub request_timeout_secs: u64,
/// Maximum retry attempts on transient failures. Defaults to 8.
pub max_retries: u32,
}
impl Default for ApiTimeoutConfig {
fn default() -> Self {
Self {
connect_timeout_secs: 30,
request_timeout_secs: 300,
max_retries: 8,
}
}
}
/// Structured feature configuration consumed by runtime subsystems.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RuntimeFeatureConfig {
@@ -139,7 +160,9 @@ pub struct RuntimeFeatureConfig {
sandbox: SandboxConfig,
provider_fallbacks: ProviderFallbackConfig,
trusted_roots: Vec<String>,
api_timeout: ApiTimeoutConfig,
rules_import: RulesImportConfig,
provider: RuntimeProviderConfig,
}
/// Controls which external AI coding framework rules are imported into the system prompt.
@@ -167,6 +190,41 @@ impl RulesImportConfig {
}
}
/// Stored provider configuration from the setup wizard.
///
/// Represents the `provider` section in `~/.claw/settings.json`, used as a
/// fallback when environment variables are absent (3-tier resolution:
/// env var > .env file > stored config).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RuntimeProviderConfig {
kind: Option<String>,
api_key: Option<String>,
base_url: Option<String>,
model: Option<String>,
}
impl RuntimeProviderConfig {
#[must_use]
pub fn kind(&self) -> Option<&str> {
self.kind.as_deref()
}
#[must_use]
pub fn api_key(&self) -> Option<&str> {
self.api_key.as_deref()
}
#[must_use]
pub fn base_url(&self) -> Option<&str> {
self.base_url.as_deref()
}
#[must_use]
pub fn model(&self) -> Option<&str> {
self.model.as_deref()
}
}
/// Ordered chain of fallback model identifiers used when the primary
/// provider returns a retryable failure (429/500/503/etc.). The chain is
/// strict: each entry is tried in order until one succeeds.
@@ -182,6 +240,7 @@ pub struct RuntimeHookConfig {
pre_tool_use: Vec<RuntimeHookCommand>,
post_tool_use: Vec<RuntimeHookCommand>,
post_tool_use_failure: Vec<RuntimeHookCommand>,
invalid_hooks: Vec<RuntimeInvalidHookConfig>,
}
/// A hook command plus optional tool matcher from object-style hook config.
@@ -191,6 +250,16 @@ pub struct RuntimeHookCommand {
matcher: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeInvalidHookConfig {
pub event: String,
pub index: Option<usize>,
pub hook_index: Option<usize>,
pub kind: String,
pub error_field: String,
pub reason: String,
}
/// Raw permission rule lists grouped by allow, deny, and ask behavior.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RuntimePermissionRuleConfig {
@@ -729,7 +798,9 @@ fn build_runtime_config(
sandbox: parse_optional_sandbox_config(&merged_value)?,
provider_fallbacks: parse_optional_provider_fallbacks(&merged_value)?,
trusted_roots: parse_optional_trusted_roots(&merged_value)?,
api_timeout: parse_optional_api_timeout_config(&merged_value)?,
rules_import: parse_optional_rules_import(&merged_value)?,
provider: parse_optional_provider_config(&merged_value)?,
};
Ok(RuntimeConfig {
@@ -844,6 +915,11 @@ impl RuntimeConfig {
&self.feature_config.rules_import
}
#[must_use]
pub fn provider(&self) -> &RuntimeProviderConfig {
&self.feature_config.provider
}
/// Merge config-level default trusted roots with per-call roots.
///
/// Config roots are defaults and are kept first; per-call roots extend the
@@ -857,6 +933,13 @@ impl RuntimeConfig {
}
impl RuntimeFeatureConfig {
/// Parsed provider configuration (kind, apiKey, baseUrl, model) from
/// merged settings.
#[must_use]
pub fn provider(&self) -> &RuntimeProviderConfig {
&self.provider
}
#[must_use]
pub fn with_hooks(mut self, hooks: RuntimeHookConfig) -> Self {
self.hooks = hooks;
@@ -1198,6 +1281,7 @@ impl RuntimeHookConfig {
pre_tool_use,
post_tool_use,
post_tool_use_failure,
invalid_hooks: Vec::new(),
}
}
@@ -1235,6 +1319,8 @@ impl RuntimeHookConfig {
&mut self.post_tool_use_failure,
other.post_tool_use_failure_entries(),
);
self.invalid_hooks
.extend(other.invalid_hooks.iter().cloned());
}
#[must_use]
@@ -1246,6 +1332,25 @@ impl RuntimeHookConfig {
pub fn post_tool_use_failure_entries(&self) -> &[RuntimeHookCommand] {
&self.post_tool_use_failure
}
#[must_use]
pub fn invalid_hooks(&self) -> &[RuntimeInvalidHookConfig] {
&self.invalid_hooks
}
#[must_use]
pub fn invalid_count(&self) -> usize {
self.invalid_hooks.len()
}
#[must_use]
pub fn has_invalid_hooks(&self) -> bool {
!self.invalid_hooks.is_empty()
}
pub fn push_invalid_hook(&mut self, invalid: RuntimeInvalidHookConfig) {
self.invalid_hooks.push(invalid);
}
}
fn hook_commands(commands: &[RuntimeHookCommand]) -> Vec<String> {
@@ -1634,14 +1739,217 @@ fn parse_optional_hooks_config_object(
return Ok(RuntimeHookConfig::default());
};
let hooks = expect_object(hooks_value, context)?;
Ok(RuntimeHookConfig {
pre_tool_use: optional_hook_command_array(hooks, "PreToolUse", context)?
.unwrap_or_default(),
post_tool_use: optional_hook_command_array(hooks, "PostToolUse", context)?
.unwrap_or_default(),
post_tool_use_failure: optional_hook_command_array(hooks, "PostToolUseFailure", context)?
.unwrap_or_default(),
})
Ok(parse_hooks_object_partial(hooks, context))
}
fn parse_hooks_object_partial(
hooks: &BTreeMap<String, JsonValue>,
context: &str,
) -> RuntimeHookConfig {
let mut config = RuntimeHookConfig::default();
parse_hook_event_partial(
&mut config,
hooks,
"PreToolUse",
context,
|config, command| {
config.pre_tool_use.push(command);
},
);
parse_hook_event_partial(
&mut config,
hooks,
"PostToolUse",
context,
|config, command| {
config.post_tool_use.push(command);
},
);
parse_hook_event_partial(
&mut config,
hooks,
"PostToolUseFailure",
context,
|config, command| {
config.post_tool_use_failure.push(command);
},
);
for event in hooks.keys().filter(|event| !is_supported_hook_event(event)) {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.clone(),
index: None,
hook_index: None,
kind: "unknown_hook_event".to_string(),
error_field: event.clone(),
reason: format!("{context}: unknown hook event {event}"),
});
}
config
}
fn is_supported_hook_event(event: &str) -> bool {
matches!(event, "PreToolUse" | "PostToolUse" | "PostToolUseFailure")
}
fn parse_hook_event_partial(
config: &mut RuntimeHookConfig,
hooks: &BTreeMap<String, JsonValue>,
event: &str,
context: &str,
mut push_command: impl FnMut(&mut RuntimeHookConfig, RuntimeHookCommand),
) {
let Some(value) = hooks.get(event) else {
return;
};
let Some(array) = value.as_array() else {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: None,
hook_index: None,
kind: "invalid_hooks_config".to_string(),
error_field: event.to_string(),
reason: format!("{context}: field {event} must be an array"),
});
return;
};
for (index, item) in array.iter().enumerate() {
if let Some(command) = item.as_str() {
if command.trim().is_empty() {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: None,
kind: "invalid_hooks_config".to_string(),
error_field: "command".to_string(),
reason: format!("{context}: field {event}[{index}] must be a non-empty string"),
});
} else {
push_command(config, RuntimeHookCommand::new(command.to_string()));
}
continue;
}
let Some(entry) = item.as_object() else {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: None,
kind: "invalid_hooks_config".to_string(),
error_field: event.to_string(),
reason: format!(
"{context}: field {event}[{index}] must be a string or hook object"
),
});
continue;
};
let matcher = match optional_hook_matcher(entry, context, event, index) {
Ok(matcher) => matcher,
Err(error) => {
config.push_invalid_hook(runtime_invalid_hook(
event,
Some(index),
None,
"matcher",
error,
));
continue;
}
};
let Some(hook_array) = entry.get("hooks").and_then(JsonValue::as_array) else {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: None,
kind: "invalid_hooks_config".to_string(),
error_field: "hooks".to_string(),
reason: format!("{context}: field {event}[{index}].hooks must be an array"),
});
continue;
};
for (hook_index, hook) in hook_array.iter().enumerate() {
let Some(hook_object) = hook.as_object() else {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: Some(hook_index),
kind: "invalid_hooks_config".to_string(),
error_field: "hooks".to_string(),
reason: format!(
"{context}: field {event}[{index}].hooks[{hook_index}] must be an object"
),
});
continue;
};
if let Some(hook_type) = hook_object.get("type") {
let Some(hook_type) = hook_type.as_str() else {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: Some(hook_index),
kind: "invalid_hooks_config".to_string(),
error_field: "type".to_string(),
reason: format!(
"{context}: field {event}[{index}].hooks[{hook_index}].type must be a string"
),
});
continue;
};
if hook_type != "command" {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: Some(hook_index),
kind: "invalid_hooks_config".to_string(),
error_field: "type".to_string(),
reason: format!(
"{context}: field {event}[{index}].hooks[{hook_index}].type must be \"command\""
),
});
continue;
}
}
let Some(command) = hook_object
.get("command")
.and_then(JsonValue::as_str)
.filter(|command| !command.trim().is_empty())
else {
config.push_invalid_hook(RuntimeInvalidHookConfig {
event: event.to_string(),
index: Some(index),
hook_index: Some(hook_index),
kind: "invalid_hooks_config".to_string(),
error_field: "command".to_string(),
reason: format!(
"{context}: field {event}[{index}].hooks[{hook_index}].command must be a non-empty string"
),
});
continue;
};
push_command(
config,
RuntimeHookCommand::with_matcher(command.to_string(), matcher.clone()),
);
}
}
}
fn runtime_invalid_hook(
event: &str,
index: Option<usize>,
hook_index: Option<usize>,
error_field: &str,
error: ConfigError,
) -> RuntimeInvalidHookConfig {
RuntimeInvalidHookConfig {
event: event.to_string(),
index,
hook_index,
kind: "invalid_hooks_config".to_string(),
error_field: error_field.to_string(),
reason: config_error_detail(&error),
}
}
fn validate_optional_hooks_config(
@@ -1784,6 +2092,26 @@ fn parse_optional_provider_fallbacks(
Ok(ProviderFallbackConfig { primary, fallbacks })
}
fn parse_optional_api_timeout_config(root: &JsonValue) -> Result<ApiTimeoutConfig, ConfigError> {
let Some(timeout_value) = root.as_object().and_then(|obj| obj.get("apiTimeout")) else {
return Ok(ApiTimeoutConfig::default());
};
let Some(obj) = timeout_value.as_object() else {
return Ok(ApiTimeoutConfig::default());
};
let context = "merged settings.apiTimeout";
let connect_timeout_secs = optional_u64(obj, "connectTimeout", context)?.unwrap_or(30);
let request_timeout_secs = optional_u64(obj, "requestTimeout", context)?.unwrap_or(300);
let max_retries = optional_u64(obj, "maxRetries", context)?
.map(|v| v as u32)
.unwrap_or(8);
Ok(ApiTimeoutConfig {
connect_timeout_secs,
request_timeout_secs,
max_retries,
})
}
fn parse_optional_trusted_roots(root: &JsonValue) -> Result<Vec<String>, ConfigError> {
let Some(object) = root.as_object() else {
return Ok(Vec::new());
@@ -1825,6 +2153,25 @@ fn parse_optional_rules_import(root: &JsonValue) -> Result<RulesImportConfig, Co
}
}
fn parse_optional_provider_config(root: &JsonValue) -> Result<RuntimeProviderConfig, ConfigError> {
let Some(provider_value) = root.as_object().and_then(|object| object.get("provider")) else {
return Ok(RuntimeProviderConfig::default());
};
let Some(object) = provider_value.as_object() else {
return Ok(RuntimeProviderConfig::default());
};
let kind = optional_string(object, "kind", "provider")?.map(str::to_string);
let api_key = optional_string(object, "apiKey", "provider")?.map(str::to_string);
let base_url = optional_string(object, "baseUrl", "provider")?.map(str::to_string);
let model = optional_string(object, "model", "provider")?.map(str::to_string);
Ok(RuntimeProviderConfig {
kind,
api_key,
base_url,
model,
})
}
fn parse_filesystem_mode_label(value: &str) -> Result<FilesystemIsolationMode, ConfigError> {
match value {
"off" => Ok(FilesystemIsolationMode::Off),
@@ -1861,6 +2208,45 @@ fn parse_optional_oauth_config(
}))
}
/// #92: expand `${VAR}` environment variable references and `~/` home directory
/// prefix in a config string value. Returns the expanded string.
fn expand_config_value(value: &str) -> String {
// Expand ${VAR} and $VAR references from the environment
let mut result = String::with_capacity(value.len());
let mut chars = value.chars().peekable();
while let Some(c) = chars.next() {
if c == '$' {
if chars.peek() == Some(&'{') {
// ${VAR} form
chars.next(); // consume '{'
let mut var_name = String::new();
for ch in chars.by_ref() {
if ch == '}' {
break;
}
var_name.push(ch);
}
if let Ok(val) = std::env::var(&var_name) {
result.push_str(&val);
}
} else {
// Bare $ — pass through
result.push(c);
}
} else if c == '~' && result.is_empty() {
// ~/... home directory expansion
if let Ok(home) = std::env::var("HOME") {
result.push_str(&home);
} else {
result.push(c);
}
} else {
result.push(c);
}
}
result
}
fn parse_mcp_server_config(
server_name: &str,
value: &JsonValue,
@@ -1870,9 +2256,14 @@ fn parse_mcp_server_config(
let server_type =
optional_string(object, "type", context)?.unwrap_or_else(|| infer_mcp_server_type(object));
match server_type {
// #92: expand ${VAR} and ~/ in command, args, and url fields
"stdio" => Ok(McpServerConfig::Stdio(McpStdioServerConfig {
command: expect_non_empty_string(object, "command", context)?.to_string(),
args: optional_string_array(object, "args", context)?.unwrap_or_default(),
command: expand_config_value(expect_non_empty_string(object, "command", context)?),
args: optional_string_array(object, "args", context)?
.unwrap_or_default()
.iter()
.map(|a| expand_config_value(a))
.collect(),
env: optional_string_map(object, "env", context)?.unwrap_or_default(),
tool_call_timeout_ms: optional_u64(object, "toolCallTimeoutMs", context)?,
})),
@@ -1883,7 +2274,8 @@ fn parse_mcp_server_config(
object, context,
)?)),
"ws" => Ok(McpServerConfig::Ws(McpWebSocketServerConfig {
url: expect_string(object, "url", context)?.to_string(),
// #92: expand ${VAR} and ~/ in URL
url: expand_config_value(expect_string(object, "url", context)?),
headers: optional_string_map(object, "headers", context)?.unwrap_or_default(),
headers_helper: optional_string(object, "headersHelper", context)?.map(str::to_string),
})),
@@ -1891,7 +2283,8 @@ fn parse_mcp_server_config(
name: expect_string(object, "name", context)?.to_string(),
})),
"claudeai-proxy" => Ok(McpServerConfig::ManagedProxy(McpManagedProxyServerConfig {
url: expect_string(object, "url", context)?.to_string(),
// #92: expand ${VAR} and ~/ in URL
url: expand_config_value(expect_string(object, "url", context)?),
id: expect_string(object, "id", context)?.to_string(),
})),
other => Err(ConfigError::Parse(format!(
@@ -1913,7 +2306,8 @@ fn parse_mcp_remote_server_config(
context: &str,
) -> Result<McpRemoteServerConfig, ConfigError> {
Ok(McpRemoteServerConfig {
url: expect_string(object, "url", context)?.to_string(),
// #92: expand ${VAR} and ~/ in URL
url: expand_config_value(expect_string(object, "url", context)?),
headers: optional_string_map(object, "headers", context)?.unwrap_or_default(),
headers_helper: optional_string(object, "headersHelper", context)?.map(str::to_string),
oauth: parse_optional_mcp_oauth_config(object, context)?,
@@ -2108,77 +2502,6 @@ fn optional_string_array(
}
}
fn optional_hook_command_array(
object: &BTreeMap<String, JsonValue>,
key: &str,
context: &str,
) -> Result<Option<Vec<RuntimeHookCommand>>, ConfigError> {
let Some(value) = object.get(key) else {
return Ok(None);
};
let Some(array) = value.as_array() else {
return Err(ConfigError::Parse(format!(
"{context}: field {key} must be an array"
)));
};
let mut commands = Vec::new();
for (index, item) in array.iter().enumerate() {
if let Some(command) = item.as_str() {
commands.push(RuntimeHookCommand::new(command.to_string()));
continue;
}
let Some(entry) = item.as_object() else {
return Err(ConfigError::Parse(format!(
"{context}: field {key}[{index}] must be a string or hook object"
)));
};
let matcher = optional_hook_matcher(entry, context, key, index)?;
let hooks = entry
.get("hooks")
.and_then(JsonValue::as_array)
.ok_or_else(|| {
ConfigError::Parse(format!(
"{context}: field {key}[{index}].hooks must be an array"
))
})?;
for (hook_index, hook) in hooks.iter().enumerate() {
let Some(hook_object) = hook.as_object() else {
return Err(ConfigError::Parse(format!(
"{context}: field {key}[{index}].hooks[{hook_index}] must be an object"
)));
};
if let Some(hook_type) = hook_object.get("type") {
let Some(hook_type) = hook_type.as_str() else {
return Err(ConfigError::Parse(format!(
"{context}: field {key}[{index}].hooks[{hook_index}].type must be a string"
)));
};
if hook_type != "command" {
return Err(ConfigError::Parse(format!(
"{context}: field {key}[{index}].hooks[{hook_index}].type must be \"command\""
)));
}
}
let command = hook_object
.get("command")
.and_then(JsonValue::as_str)
.filter(|command| !command.trim().is_empty())
.ok_or_else(|| {
ConfigError::Parse(format!(
"{context}: field {key}[{index}].hooks[{hook_index}].command must be a non-empty string"
))
})?;
commands.push(RuntimeHookCommand::with_matcher(
command.to_string(),
matcher.clone(),
));
}
}
Ok(Some(commands))
}
fn optional_hook_matcher(
entry: &BTreeMap<String, JsonValue>,
context: &str,
@@ -2247,6 +2570,10 @@ fn deep_merge_objects(
(Some(JsonValue::Object(existing)), JsonValue::Object(incoming)) => {
deep_merge_objects(existing, incoming);
}
// #106: concatenate arrays instead of replacing
(Some(JsonValue::Array(existing)), JsonValue::Array(incoming)) => {
existing.extend(incoming.iter().cloned());
}
_ => {
target.insert(key.clone(), value.clone());
}
@@ -2428,7 +2755,7 @@ mod tests {
}
#[test]
fn rejects_object_style_hook_entries_without_command() {
fn records_object_style_hook_entries_without_command_441() {
let root = temp_dir();
let cwd = root.join("project");
let home = root.join("home").join(".claw");
@@ -2440,12 +2767,20 @@ mod tests {
)
.expect("write settings");
let error = ConfigLoader::new(&cwd, &home)
let loaded = ConfigLoader::new(&cwd, &home)
.load()
.expect_err("config should reject malformed hook entry");
.expect("config should load valid siblings and record malformed hook entry");
assert!(error
.to_string()
assert!(loaded.hooks().pre_tool_use().is_empty());
assert_eq!(loaded.hooks().invalid_count(), 1);
assert_eq!(
loaded.hooks().invalid_hooks()[0].kind,
"invalid_hooks_config"
);
assert_eq!(loaded.hooks().invalid_hooks()[0].event, "PreToolUse");
assert_eq!(loaded.hooks().invalid_hooks()[0].error_field, "command");
assert!(loaded.hooks().invalid_hooks()[0]
.reason
.contains("command must be a non-empty string"));
fs::remove_dir_all(root).expect("cleanup temp dir");
}
@@ -3188,7 +3523,7 @@ mod tests {
}
#[test]
fn rejects_invalid_hook_entries_before_merge() {
fn loads_valid_hook_entries_and_records_invalid_siblings_441() {
// given
let root = temp_dir();
let cwd = root.join("project");
@@ -3208,19 +3543,26 @@ mod tests {
)
.expect("write invalid project settings");
// when
let error = ConfigLoader::new(&cwd, &home)
let loaded = ConfigLoader::new(&cwd, &home)
.load()
.expect_err("config should fail");
.expect("config should load valid hook entries and record invalid siblings");
// then — config validation now catches the mixed array before the hooks parser
let rendered = error.to_string();
assert!(
rendered.contains("hooks.PreToolUse")
&& rendered.contains("must be an array of strings"),
"expected validation error for hooks.PreToolUse, got: {rendered}"
// #106: arrays now concatenate across config layers, so both "base" and "project" are present
assert_eq!(
loaded.hooks().pre_tool_use(),
&["base".to_string(), "project".to_string()]
);
assert!(!rendered.contains("merged settings.hooks"));
assert_eq!(loaded.hooks().invalid_count(), 1);
assert_eq!(loaded.hooks().invalid_hooks()[0].event, "PreToolUse");
assert_eq!(
loaded.hooks().invalid_hooks()[0].kind,
"invalid_hooks_config"
);
// #106: invalid entry at index 2 after array concatenation
assert_eq!(loaded.hooks().invalid_hooks()[0].index, Some(2));
assert!(loaded.hooks().invalid_hooks()[0]
.reason
.contains("must be a string or hook object"));
fs::remove_dir_all(root).expect("cleanup temp dir");
}
@@ -3363,7 +3705,7 @@ mod tests {
}
#[test]
fn validates_wrong_type_for_known_field_with_field_path() {
fn hook_event_wrong_type_is_recorded_without_config_failure_441() {
// given
let root = temp_dir();
let cwd = root.join("project");
@@ -3377,29 +3719,145 @@ mod tests {
)
.expect("write user settings");
// when
let error = ConfigLoader::new(&cwd, &home)
let loaded = ConfigLoader::new(&cwd, &home)
.load()
.expect_err("config should fail");
.expect("config should record malformed hook event without failing");
// then
let rendered = error.to_string();
assert!(
rendered.contains(&user_settings.display().to_string()),
"error should include file path, got: {rendered}"
assert!(loaded.hooks().pre_tool_use().is_empty());
assert_eq!(loaded.hooks().invalid_count(), 1);
assert_eq!(loaded.hooks().invalid_hooks()[0].event, "PreToolUse");
assert_eq!(
loaded.hooks().invalid_hooks()[0].kind,
"invalid_hooks_config"
);
assert_eq!(loaded.hooks().invalid_hooks()[0].index, None);
assert!(loaded.hooks().invalid_hooks()[0]
.reason
.contains("field PreToolUse must be an array"));
fs::remove_dir_all(root).expect("cleanup temp dir");
}
#[test]
fn collects_all_invalid_hook_siblings_instead_of_halting_at_first_441() {
// ROADMAP #441 finding (c): first-error-only halting means users must fix
// one hook at a time. After #441 partial fix, all invalid entries in the
// same config are collected.
let root = temp_dir();
let cwd = root.join("project");
let home = root.join("home").join(".claw");
fs::create_dir_all(&home).expect("home config dir");
fs::create_dir_all(&cwd).expect("project dir");
fs::write(
home.join("settings.json"),
r#"{"hooks":{"PreToolUse":[42],"PostToolUse":"not-an-array","InvalidEvent":["cmd"]}}"#,
)
.expect("write settings");
let loaded = ConfigLoader::new(&cwd, &home)
.load()
.expect("config should collect all invalid hooks without halting at first");
assert!(loaded.hooks().pre_tool_use().is_empty());
assert!(loaded.hooks().post_tool_use().is_empty());
// Three distinct invalid entries: 42, wrong type, unknown event
assert_eq!(loaded.hooks().invalid_count(), 3);
let invalid = loaded.hooks().invalid_hooks();
// PreToolUse[0]=42
assert_eq!(invalid[0].event, "PreToolUse");
assert_eq!(invalid[0].index, Some(0));
assert_eq!(invalid[0].kind, "invalid_hooks_config");
// PostToolUse wrong type
assert_eq!(invalid[1].event, "PostToolUse");
assert_eq!(invalid[1].index, None);
assert_eq!(invalid[1].kind, "invalid_hooks_config");
// Unknown event
assert_eq!(invalid[2].event, "InvalidEvent");
assert_eq!(invalid[2].index, None);
assert_eq!(invalid[2].kind, "unknown_hook_event");
assert!(invalid[2]
.reason
.contains("unknown hook event InvalidEvent"));
fs::remove_dir_all(root).expect("cleanup temp dir");
}
#[test]
fn unknown_hook_events_recorded_with_correct_kind_441() {
// ROADMAP #441 finding (a): unknown event names like Stop/Notification
// should not reject entire hooks config; they are recorded as invalid.
let root = temp_dir();
let cwd = root.join("project");
let home = root.join("home").join(".claw");
fs::create_dir_all(&home).expect("home config dir");
fs::create_dir_all(&cwd).expect("project dir");
fs::write(
home.join("settings.json"),
r#"{"hooks":{"PreToolUse":["valid-cmd"],"Stop":"not-an-array","Notification":[{}]}}"#,
)
.expect("write settings");
let loaded = ConfigLoader::new(&cwd, &home)
.load()
.expect("config should load valid hooks and record unknown event siblings");
// Valid PreToolUse hook should load
assert_eq!(loaded.hooks().pre_tool_use(), &["valid-cmd".to_string()]);
// Stop and Notification are unknown events; each gets one invalid entry
// Notification:[{}] also has an empty-object entry issue but since we
// don't parse unknown events, only the unknown-event invalid is recorded
let invalid = loaded.hooks().invalid_hooks();
assert!(
rendered.contains("hooks"),
"error should include field path component 'hooks', got: {rendered}"
invalid.len() >= 2,
"expected at least 2 invalid hooks, got {}",
invalid.len()
);
assert!(
rendered.contains("PreToolUse"),
"error should describe the type mismatch, got: {rendered}"
);
assert!(
rendered.contains("array"),
"error should describe the expected type, got: {rendered}"
let stop = invalid
.iter()
.find(|h| h.event == "Stop")
.expect("Stop invalid hook");
assert_eq!(stop.kind, "unknown_hook_event");
assert_eq!(stop.index, None);
assert!(stop.reason.contains("unknown hook event Stop"));
let notif = invalid
.iter()
.find(|h| h.event == "Notification")
.expect("Notification invalid hook");
assert_eq!(notif.kind, "unknown_hook_event");
fs::remove_dir_all(root).expect("cleanup temp dir");
}
#[test]
fn documented_claude_code_hook_format_loads_without_error_441() {
// ROADMAP #441: the Claude Code documented hook format
// {"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"..."}]}]}}
// must load without config_load_error.
let root = temp_dir();
let cwd = root.join("project");
let home = root.join("home").join(".claw");
fs::create_dir_all(&home).expect("home config dir");
fs::create_dir_all(&cwd).expect("project dir");
fs::write(
home.join("settings.json"),
r#"{"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"/bin/echo pretool"}]}]}}"#,
)
.expect("write settings");
let loaded = ConfigLoader::new(&cwd, &home)
.load()
.expect("Claude Code documented hook format must load without error");
assert_eq!(
loaded.hooks().pre_tool_use(),
&["/bin/echo pretool".to_string()]
);
assert_eq!(loaded.hooks().invalid_count(), 0);
let entries = loaded.hooks().pre_tool_use_entries();
assert_eq!(entries[0].matcher(), Some("Read"));
fs::remove_dir_all(root).expect("cleanup temp dir");
}

View File

@@ -118,10 +118,7 @@ impl FieldType {
Self::StringArray => value
.as_array()
.is_some_and(|arr| arr.iter().all(|v| v.as_str().is_some())),
Self::HookArray => value.as_array().is_some_and(|arr| {
arr.iter()
.all(|entry| entry.as_str().is_some() || entry.as_object().is_some())
}),
Self::HookArray => true,
Self::RulesImport => {
value.as_str().is_some()
|| value
@@ -219,6 +216,10 @@ const TOP_LEVEL_FIELDS: &[FieldSpec] = &[
name: "rulesImport",
expected: FieldType::RulesImport,
},
FieldSpec {
name: "subagentModel",
expected: FieldType::String,
},
];
const HOOKS_FIELDS: &[FieldSpec] = &[
@@ -424,8 +425,6 @@ fn validate_object_keys(
} else if DEPRECATED_FIELDS.iter().any(|d| d.name == key) {
// Deprecated key — handled separately, not an unknown-key error.
} else {
// Unknown key — preserve compatibility by surfacing it as a warning
// instead of blocking otherwise valid config files.
let suggestion = suggest_field(key, &known_names);
result.warnings.push(ConfigDiagnostic {
path: path_display.to_string(),
@@ -714,7 +713,7 @@ mod tests {
#[test]
fn validates_nested_hooks_keys() {
// given
let source = r#"{"hooks": {"PreToolUse": ["cmd"], "BadHook": ["x"]}}"#;
let source = r#"{"hooks": {"PreToolUse": [{"hooks":[{"type":"command","command":"cmd"}]}], "BadHook": ["x"]}}"#;
let parsed = JsonValue::parse(source).expect("valid json");
let object = parsed.as_object().expect("object");
@@ -723,7 +722,12 @@ mod tests {
// then
assert!(result.errors.is_empty());
assert_eq!(result.warnings.len(), 1);
assert_eq!(
result.warnings.len(),
1,
"expected only the unknown key warning, got {:?}",
result.warnings
);
assert_eq!(result.warnings[0].field, "hooks.BadHook");
}
@@ -739,15 +743,14 @@ mod tests {
}
#[test]
fn rejects_wrong_hook_entry_types() {
fn allows_wrong_hook_entry_types_for_partial_runtime_validation_441() {
let source = r#"{"hooks":{"PreToolUse":[42]}}"#;
let parsed = JsonValue::parse(source).expect("valid json");
let object = parsed.as_object().expect("object");
let result = validate_config_file(object, source, &test_path());
assert_eq!(result.errors.len(), 1);
assert_eq!(result.errors[0].field, "hooks.PreToolUse");
assert!(result.errors.is_empty(), "{:?}", result.errors);
}
#[test]
@@ -847,7 +850,7 @@ mod tests {
// given
let source = r#"{
"model": "opus",
"hooks": {"PreToolUse": ["guard"]},
"hooks": {"PreToolUse": [{"hooks":[{"type":"command","command":"guard"}]}]},
"permissions": {"defaultMode": "plan", "allow": ["Read"]},
"mcpServers": {},
"sandbox": {"enabled": false}

View File

@@ -204,6 +204,13 @@ where
self
}
/// Update the auto-compaction threshold after construction. This allows the
/// caller to tune the threshold based on runtime information (e.g., the
/// server-returned context window size from a 400 error).
pub fn set_auto_compaction_input_tokens_threshold(&mut self, threshold: u32) {
self.auto_compaction_input_tokens_threshold = threshold;
}
#[must_use]
pub fn with_hook_abort_signal(mut self, hook_abort_signal: HookAbortSignal) -> Self {
self.hook_abort_signal = hook_abort_signal;

View File

@@ -65,14 +65,15 @@ pub use compact::{
get_compact_continuation_message, should_compact, CompactionConfig, CompactionResult,
};
pub use config::{
suppress_config_warnings_for_json_mode, ConfigEntry, ConfigError, ConfigFileReport,
ConfigFileStatus, ConfigInspection, ConfigLoader, ConfigSource, McpConfigCollection,
McpInvalidServerConfig, McpManagedProxyServerConfig, McpOAuthConfig, McpRemoteServerConfig,
McpSdkServerConfig, McpServerConfig, McpStdioServerConfig, McpTransport,
clear_user_provider_settings, default_config_home, save_user_provider_settings,
suppress_config_warnings_for_json_mode, ApiTimeoutConfig, ConfigEntry, ConfigError,
ConfigFileReport, ConfigFileStatus, ConfigInspection, ConfigLoader, ConfigSource,
McpConfigCollection, McpInvalidServerConfig, McpManagedProxyServerConfig, McpOAuthConfig,
McpRemoteServerConfig, McpSdkServerConfig, McpServerConfig, McpStdioServerConfig, McpTransport,
McpWebSocketServerConfig, OAuthConfig, ProviderFallbackConfig, ResolvedPermissionMode,
RulesImportConfig, RuntimeConfig, RuntimeFeatureConfig, RuntimeHookCommand, RuntimeHookConfig,
RuntimePermissionRuleConfig, RuntimePluginConfig, ScopedMcpServerConfig,
CLAW_SETTINGS_SCHEMA_NAME,
RuntimeInvalidHookConfig, RuntimePermissionRuleConfig, RuntimePluginConfig,
RuntimeProviderConfig, ScopedMcpServerConfig, CLAW_SETTINGS_SCHEMA_NAME,
};
pub use config_validate::{
check_unsupported_format, format_diagnostics, validate_config_file, ConfigDiagnostic,

View File

@@ -173,32 +173,112 @@ impl PermissionEnforcer {
}
}
/// Simple workspace boundary check via string prefix.
/// Workspace boundary check.
///
/// Resolves `.` and `..` components lexically *before* comparing against the
/// workspace root, so that traversal sequences like `/workspace/../../etc`
/// cannot escape the sandbox via a naive string prefix match. Normalization is
/// lexical (it does not touch the filesystem) because the target path may not
/// exist yet on a write, and we must not depend on CWD.
fn is_within_workspace(path: &str, workspace_root: &str) -> bool {
let normalized = if path.starts_with('/') {
let combined = if path.starts_with('/') {
path.to_owned()
} else {
format!("{workspace_root}/{path}")
};
let root = if workspace_root.ends_with('/') {
workspace_root.to_owned()
let normalized = lexically_normalize(&combined);
let root = lexically_normalize(workspace_root);
let root_with_slash = if root.ends_with('/') {
root.clone()
} else {
format!("{workspace_root}/")
format!("{root}/")
};
normalized.starts_with(&root) || normalized == workspace_root.trim_end_matches('/')
normalized == root || normalized.starts_with(&root_with_slash)
}
/// Collapse `.` and `..` segments without consulting the filesystem.
/// `..` that would climb above an absolute root is clamped at `/`, so the
/// result can never be a prefix-match for a deeper workspace root.
fn lexically_normalize(path: &str) -> String {
let is_absolute = path.starts_with('/');
let mut stack: Vec<&str> = Vec::new();
for component in path.split('/') {
match component {
"" | "." => {}
".." => {
stack.pop();
}
other => stack.push(other),
}
}
let joined = stack.join("/");
if is_absolute {
format!("/{joined}")
} else {
joined
}
}
/// Conservative heuristic: is this bash command read-only?
///
/// Hardening notes:
/// - Any shell metacharacter that could chain, substitute, pipe, or redirect
/// into a state-changing command rejects the whole line. This blocks
/// `cat x; rm -rf y`, `cat x | sh`, `$(...)`, backticks, redirects, and
/// subshells regardless of the leading token.
/// - Language interpreters (`python`, `node`, `ruby`) and build drivers
/// (`cargo`, `rustc`) are NOT read-only: they execute arbitrary code, so they
/// are excluded from the allow-list.
/// - `git` is allowed only for a known set of non-mutating subcommands.
/// - `find` is rejected when it carries an action that can execute or delete.
///
/// Residual known gaps (documented, not yet closed): `sed`'s `w`/`e` script
/// commands and `awk`'s `system()` can still mutate — these require quoting or
/// metacharacters that the checks above usually catch, but a dedicated parser
/// would be more robust. Tracked as follow-up.
fn is_read_only_command(command: &str) -> bool {
let first_token = command
.split_whitespace()
.next()
.unwrap_or("")
.rsplit('/')
.next()
.unwrap_or("");
// Shell metacharacters that enable command chaining, substitution,
// piping, redirection, or subshells. Presence of any of these means we
// cannot reason about the command from its leading token alone.
const SHELL_METACHARS: &[char] = &[';', '|', '&', '$', '`', '>', '<', '(', ')', '{', '}', '\n'];
if command.contains(SHELL_METACHARS) {
return false;
}
let mut tokens = command.split_whitespace();
let first_token = tokens.next().unwrap_or("").rsplit('/').next().unwrap_or("");
// `git` is only read-only for a curated set of subcommands.
if first_token == "git" {
let subcommand = tokens.next().unwrap_or("");
return matches!(
subcommand,
"status"
| "log"
| "diff"
| "show"
| "branch"
| "rev-parse"
| "ls-files"
| "blame"
| "describe"
| "tag"
| "remote"
);
}
// `find` can execute or delete via actions; reject those forms.
if first_token == "find"
&& (command.contains("-exec")
|| command.contains("-execdir")
|| command.contains("-delete")
|| command.contains("-ok")
|| command.contains("-fprintf"))
{
return false;
}
matches!(
first_token,
@@ -237,8 +317,6 @@ fn is_read_only_command(command: &str) -> bool {
| "tr"
| "cut"
| "paste"
| "tee"
| "xargs"
| "test"
| "true"
| "false"
@@ -257,18 +335,8 @@ fn is_read_only_command(command: &str) -> bool {
| "tree"
| "jq"
| "yq"
| "python3"
| "python"
| "node"
| "ruby"
| "cargo"
| "rustc"
| "git"
| "gh"
) && !command.contains("-i ")
&& !command.contains("--in-place")
&& !command.contains(" > ")
&& !command.contains(" >> ")
}
#[cfg(test)]
@@ -375,6 +443,91 @@ mod tests {
assert!(!is_read_only_command("sed -i 's/a/b/' file"));
}
// --- Hardening regression tests (#2: read-only bypasses) ---
#[test]
fn read_only_rejects_command_chaining() {
// A leading read-only token must not launder a trailing destructive one.
assert!(!is_read_only_command("cat foo; rm -rf bar"));
assert!(!is_read_only_command("cat foo && rm -rf bar"));
assert!(!is_read_only_command("ls || rm bar"));
assert!(!is_read_only_command("cat foo | sh"));
assert!(!is_read_only_command("echo `rm bar`"));
assert!(!is_read_only_command("echo $(rm bar)"));
assert!(!is_read_only_command("echo x>file")); // redirect without spaces
}
#[test]
fn read_only_rejects_interpreters_and_build_drivers() {
// These execute arbitrary code and are no longer read-only.
assert!(!is_read_only_command(
"python3 -c \"import os; os.system('rm -rf .')\""
));
assert!(!is_read_only_command("python script.py"));
assert!(!is_read_only_command("node app.js"));
assert!(!is_read_only_command("ruby x.rb"));
assert!(!is_read_only_command("cargo run"));
assert!(!is_read_only_command("rustc evil.rs"));
}
#[test]
fn read_only_gates_git_subcommands() {
// Read-only git subcommands remain allowed...
assert!(is_read_only_command("git status"));
assert!(is_read_only_command("git diff HEAD~1"));
assert!(is_read_only_command("git show abc123"));
// ...but mutating/exfiltrating ones are rejected.
assert!(!is_read_only_command("git commit -m x"));
assert!(!is_read_only_command("git push origin main"));
assert!(!is_read_only_command("git reset --hard"));
assert!(!is_read_only_command("git clean -fd"));
assert!(!is_read_only_command("git config user.email a@b.c"));
}
#[test]
fn read_only_rejects_find_actions() {
assert!(is_read_only_command("find . -name Cargo.toml"));
assert!(!is_read_only_command("find . -delete"));
// -exec uses braces/semicolon which also trip the metachar guard,
// but the explicit action check is the primary defense.
assert!(!is_read_only_command("find . -execdir rm rf"));
}
// --- Hardening regression tests (#1: workspace path traversal) ---
#[test]
fn workspace_rejects_parent_traversal() {
assert!(!is_within_workspace(
"/workspace/../etc/passwd",
"/workspace"
));
assert!(!is_within_workspace(
"/workspace/../../etc/crontab",
"/workspace"
));
assert!(!is_within_workspace("../etc/passwd", "/workspace"));
assert!(!is_within_workspace(
"/workspace/sub/../../outside",
"/workspace"
));
// Legitimate paths still resolve inside.
assert!(is_within_workspace(
"/workspace/./src/main.rs",
"/workspace"
));
assert!(is_within_workspace(
"/workspace/src/../src/main.rs",
"/workspace"
));
}
#[test]
fn workspace_write_denies_traversal_escape() {
let enforcer = make_enforcer(PermissionMode::WorkspaceWrite);
let result = enforcer.check_file_write("/workspace/../../etc/crontab", "/workspace");
assert!(matches!(result, EnforcementResult::Denied { .. }));
}
#[test]
fn active_mode_returns_policy_mode() {
// given

View File

@@ -149,7 +149,12 @@ impl PermissionPolicy {
.iter()
.map(|rule| PermissionRule::parse(rule))
.collect();
self.denied_tools = config.denied_tools().to_vec();
// #94: normalize denied tool names to lowercase to match runtime convention
self.denied_tools = config
.denied_tools()
.iter()
.map(|t| t.to_lowercase())
.collect();
self
}
@@ -375,7 +380,8 @@ impl PermissionRule {
let matcher = parse_rule_matcher(content);
return Self {
raw: trimmed.to_string(),
tool_name: tool_name.to_string(),
// #94: normalize tool name to lowercase to match runtime convention
tool_name: tool_name.to_lowercase(),
matcher,
};
}
@@ -384,7 +390,8 @@ impl PermissionRule {
Self {
raw: trimmed.to_string(),
tool_name: trimmed.to_string(),
// #94: normalize tool name to lowercase to match runtime convention
tool_name: trimmed.to_lowercase(),
matcher: PermissionRuleMatcher::Any,
}
}

View File

@@ -220,15 +220,14 @@ pub fn build_linux_sandbox_command(
return None;
}
let mut args = vec![
"--user".to_string(),
"--map-root-user".to_string(),
"--mount".to_string(),
"--ipc".to_string(),
"--pid".to_string(),
"--uts".to_string(),
"--fork".to_string(),
];
let mut args: Vec<String> = working_unshare_mapping()
.unwrap_or(UNSHARE_MAPPING_CANDIDATES[0])
.iter()
.map(|arg| arg.to_string())
.collect();
// The candidates already carry the namespace flags, so the probe and the
// launcher share a single argument shape; only the opt-in `--net` is
// added here.
if status.network_active {
args.push("--net".to_string());
}
@@ -282,6 +281,82 @@ fn command_exists(command: &str) -> bool {
.is_some_and(|paths| env::split_paths(&paths).any(|path| path.join(command).exists()))
}
/// Candidate `unshare` user-namespace mapping options, in preference order.
///
/// Most systems accept `--map-root-user` alone. Some hardened containers and
/// seccomp profiles block unprivileged writes to `/proc/self/uid_map`; there,
/// util-linux delegates to the setuid `newuidmap`/`newgidmap` helpers when
/// `--map-auto` is also present.
///
/// That fallback therefore depends on the setuid helpers (the `uidmap`
/// package on Debian/Ubuntu) and on the current user having a range in
/// `/etc/subuid` and `/etc/subgid`. When either is missing, `--map-auto`
/// fails and the startup probe rejects the candidate, keeping the plain form.
///
/// Each candidate is the **complete** static argument shape the launcher
/// uses (see `build_linux_sandbox_command`): mapping flags followed by the
/// namespace flags `--mount --ipc --pid --uts --fork`. The startup probe
/// runs each candidate verbatim (plus a trivial program), so probe success
/// implies launch success: on systems where the mapping works but the
/// namespace flags are denied (e.g. AppArmor-restricted CI runners that
/// block mount propagation in user namespaces), the probe fails and the
/// sandbox stays disabled instead of activating a launcher that always
/// errors.
///
/// `--net` is intentionally absent: it is appended only when network
/// isolation is active (the non-default path), and probing with it would
/// disable the sandbox on hosts that block network-namespace creation (e.g.
/// Docker's default seccomp profile) even when network isolation is never
/// requested.
const UNSHARE_MAPPING_CANDIDATES: &[&[&str]] = &[
&[
"--user",
"--map-root-user",
"--mount",
"--ipc",
"--pid",
"--uts",
"--fork",
],
&[
"--user",
"--map-root-user",
"--map-auto",
"--mount",
"--ipc",
"--pid",
"--uts",
"--fork",
],
];
/// Probe a candidate `unshare` mapping invocation with a trivial program.
fn unshare_probe(args: &[&str]) -> bool {
std::process::Command::new("unshare")
.args(args)
.arg("true")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
/// The first mapping option set that works on this machine, if any.
///
/// Probes are cached for the process lifetime; a missing `unshare` binary or a
/// kernel that refuses every mapping yields `None`.
fn working_unshare_mapping() -> Option<&'static [&'static str]> {
use std::sync::OnceLock;
static MAPPING: OnceLock<Option<&'static [&'static str]>> = OnceLock::new();
*MAPPING.get_or_init(|| {
UNSHARE_MAPPING_CANDIDATES
.iter()
.copied()
.find(|args| unshare_probe(args))
})
}
/// Check whether `unshare --user` actually works on this system.
/// On some CI environments (e.g. GitHub Actions), the binary exists but
/// user namespaces are restricted, causing silent failures.
@@ -292,13 +367,7 @@ fn unshare_user_namespace_works() -> bool {
if !command_exists("unshare") {
return false;
}
std::process::Command::new("unshare")
.args(["--user", "--map-root-user", "true"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success())
working_unshare_mapping().is_some()
})
}
@@ -359,6 +428,52 @@ mod tests {
assert_eq!(request.allowed_mounts, vec!["tmp"]);
}
#[test]
fn mapping_candidates_prefer_plain_root_mapping() {
assert!(!super::UNSHARE_MAPPING_CANDIDATES.is_empty());
for candidate in super::UNSHARE_MAPPING_CANDIDATES {
// Mapping flags.
assert!(candidate.contains(&"--user"));
assert!(candidate.contains(&"--map-root-user"));
// Namespace flags the real launcher appends — the probe must
// exercise the full invocation shape, not just mapping flags.
assert!(candidate.contains(&"--mount"));
assert!(candidate.contains(&"--ipc"));
assert!(candidate.contains(&"--pid"));
assert!(candidate.contains(&"--uts"));
assert!(candidate.contains(&"--fork"));
}
// The plain form must be tried first; `--map-auto` is only a fallback
// for kernels/containers that block unprivileged uid_map writes.
assert_eq!(
super::UNSHARE_MAPPING_CANDIDATES[0],
&[
"--user",
"--map-root-user",
"--mount",
"--ipc",
"--pid",
"--uts",
"--fork",
]
);
// The second candidate inserts `--map-auto` in the position util-linux
// expects (after `--map-root-user`, before the namespace flags).
assert_eq!(
super::UNSHARE_MAPPING_CANDIDATES[1],
&[
"--user",
"--map-root-user",
"--map-auto",
"--mount",
"--ipc",
"--pid",
"--uts",
"--fork",
]
);
}
#[test]
fn builds_linux_launcher_with_network_flag_when_requested() {
let config = SandboxConfig::default();

View File

@@ -231,8 +231,31 @@ impl Session {
pub fn save_to_path(&self, path: impl AsRef<Path>) -> Result<(), SessionError> {
let path = path.as_ref();
let snapshot = self.render_jsonl_snapshot()?;
rotate_session_file_if_needed(path)?;
write_atomic(path, &snapshot)?;
// #112: wrap ENOENT during rotate as concurrent modification
match rotate_session_file_if_needed(path) {
Ok(()) => {}
Err(SessionError::Io(ref io_err)) if io_err.kind() == std::io::ErrorKind::NotFound => {
return Err(SessionError::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!(
"session file was removed during save (possible concurrent modification): {io_err}"
),
)));
}
Err(e) => return Err(e),
}
write_atomic(path, &snapshot).map_err(|e| {
// #112: wrap ENOENT during write as concurrent modification
match &e {
SessionError::Io(io_err) if io_err.kind() == std::io::ErrorKind::NotFound => {
SessionError::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("session file was removed during write (possible concurrent modification): {io_err}"),
))
}
_ => e,
}
})?;
cleanup_rotated_logs(path)?;
Ok(())
}

View File

@@ -93,8 +93,19 @@ impl SessionStore {
}
pub fn resolve_reference(&self, reference: &str) -> Result<SessionHandle, SessionControlError> {
self.resolve_reference_excluding(reference, None)
}
/// Resolve a session reference, optionally excluding a session by ID.
/// When the reference is an alias, the excluded session is skipped
/// so /resume latest returns the previous session, not the current one.
pub fn resolve_reference_excluding(
&self,
reference: &str,
exclude_id: Option<&str>,
) -> Result<SessionHandle, SessionControlError> {
if is_session_reference_alias(reference) {
let latest = self.latest_session()?;
let latest = self.latest_session_excluding(exclude_id)?;
return Ok(SessionHandle {
id: latest.id,
path: latest.path,
@@ -158,12 +169,45 @@ impl SessionStore {
}
pub fn latest_session(&self) -> Result<ManagedSessionSummary, SessionControlError> {
if let Some(latest) = self.list_sessions()?.into_iter().next() {
self.latest_session_excluding(None)
}
/// Find the most recent session, optionally excluding a session by ID
/// and skipping sessions with 0 messages. Used by /resume latest to skip
/// the current empty session and find the previous session with actual
/// conversation history.
pub fn latest_session_excluding(
&self,
exclude_id: Option<&str>,
) -> Result<ManagedSessionSummary, SessionControlError> {
let exclude = exclude_id.unwrap_or("");
// First: look in the current workspace's session namespace
if let Some(latest) = self
.list_sessions()?
.into_iter()
.find(|s| s.id != exclude && s.message_count > 0)
{
return Ok(latest);
}
if let Some(latest) = self.scan_global_sessions()?.into_iter().next() {
// Fallback: scan all workspace namespaces under ~/.claw/sessions/
// and project-local .claw/sessions/ so /resume latest finds sessions
// from other workspaces.
if let Some(latest) = self
.scan_global_sessions()?
.into_iter()
.find(|s| s.id != exclude && s.message_count > 0)
{
return Ok(latest);
}
// Distinguish between "no sessions at all" and "sessions exist but
// all are empty" so the user gets a clear signal about what to do.
let has_any_session = self.list_sessions()?.iter().any(|s| s.id != exclude)
|| self.scan_global_sessions()?.iter().any(|s| s.id != exclude);
if has_any_session {
return Err(SessionControlError::Format(format_all_sessions_empty(
&self.sessions_root,
)));
}
Err(SessionControlError::Format(format_no_managed_sessions(
&self.sessions_root,
)))
@@ -204,28 +248,41 @@ impl SessionStore {
&self,
reference: &str,
) -> Result<LoadedManagedSession, SessionControlError> {
match self.load_session(reference) {
Ok(loaded) => Ok(loaded),
Err(SessionControlError::WorkspaceMismatch { expected, actual })
if is_session_reference_alias(reference) =>
self.load_session_excluding(reference, None)
}
/// Like `load_session_loose` but also excludes a session by ID.
/// Used by /resume latest to skip the current empty session and find
/// the previous session with actual conversation history.
pub fn load_session_excluding(
&self,
reference: &str,
exclude_id: Option<&str>,
) -> Result<LoadedManagedSession, SessionControlError> {
let handle = self.resolve_reference_excluding(reference, exclude_id)?;
let session = Session::load_from_path(&handle.path)?;
// For alias references, allow cross-workspace resume
if is_session_reference_alias(reference) {
if let Err(SessionControlError::WorkspaceMismatch {
expected: _,
actual,
}) = self.validate_loaded_session(&handle.path, &session)
{
let handle = self.resolve_reference(reference)?;
let session = Session::load_from_path(&handle.path)?;
eprintln!(
" Note: resuming session from a different workspace (origin: {})",
actual.display()
);
let _ = expected; // suppress unused warning
Ok(LoadedManagedSession {
handle: SessionHandle {
id: session.session_id.clone(),
path: handle.path,
},
session,
})
}
Err(other) => Err(other),
} else {
self.validate_loaded_session(&handle.path, &session)?;
}
Ok(LoadedManagedSession {
handle: SessionHandle {
id: session.session_id.clone(),
path: handle.path,
},
session,
})
}
pub fn fork_session(
@@ -726,6 +783,16 @@ fn format_no_managed_sessions(sessions_root: &Path) -> String {
)
}
fn format_all_sessions_empty(sessions_root: &Path) -> String {
let fingerprint_dir = sessions_root
.file_name()
.and_then(|f| f.to_str())
.unwrap_or("<unknown>");
format!(
"all sessions are empty (0 messages) in .claw/sessions/{fingerprint_dir}/\nThis usually means a fresh `claw` session is running but no messages have been sent yet.\nWait for a response in your other session, then try `--resume {LATEST_SESSION_REFERENCE}` again."
)
}
fn format_legacy_session_missing_workspace_root(
session_path: &Path,
workspace_root: &Path,
@@ -765,6 +832,28 @@ mod tests {
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
struct EnvVarGuard {
key: &'static str,
previous: Option<std::ffi::OsString>,
}
impl EnvVarGuard {
fn set(key: &'static str, value: &Path) -> Self {
let previous = std::env::var_os(key);
std::env::set_var(key, value);
Self { key, previous }
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
match &self.previous {
Some(value) => std::env::set_var(self.key, value),
None => std::env::remove_var(self.key),
}
}
}
fn temp_dir() -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -1220,6 +1309,117 @@ mod tests {
fs::remove_dir_all(base).expect("temp dir should clean up");
}
#[test]
fn latest_session_returns_all_empty_error_when_sessions_exist_but_have_no_messages() {
// given — create sessions with 0 messages (empty)
let _env_guard = crate::test_env_lock();
let base = temp_dir();
fs::create_dir_all(&base).expect("base dir should exist");
let isolated_config_home = base.join("config-home");
let _claw_config_home = EnvVarGuard::set("CLAW_CONFIG_HOME", &isolated_config_home);
let store = SessionStore::from_cwd(&base).expect("store should build");
let empty_handle = store.create_handle("empty-session");
Session::new()
.with_persistence_path(empty_handle.path.clone())
.save_to_path(&empty_handle.path)
.expect("empty session should save");
// when — latest_session should fail with the "all sessions empty" message
let result = store.latest_session();
assert!(
result.is_err(),
"latest_session should fail when all sessions are empty"
);
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("all sessions are empty"),
"error should mention 'all sessions are empty', got: {err_msg}"
);
assert!(
err_msg.contains("0 messages"),
"error should mention '0 messages', got: {err_msg}"
);
fs::remove_dir_all(base).expect("temp dir should clean up");
}
#[test]
fn latest_session_excluding_skips_excluded_id_and_returns_previous() {
// given — two sessions WITH messages, newest excluded
let base = temp_dir();
fs::create_dir_all(&base).expect("base dir should exist");
let store = SessionStore::from_cwd(&base).expect("store should build");
let older = persist_session_via_store(&store, "older work");
wait_for_next_millisecond();
let newer = persist_session_via_store(&store, "newer work");
// when — exclude the newest session
let latest = store
.latest_session_excluding(Some(&newer.session_id))
.expect("latest excluding newest should resolve");
// then — the older session wins because the newest is skipped
assert_eq!(
latest.id, older.session_id,
"excluded id must be skipped, returning the previous session"
);
fs::remove_dir_all(base).expect("temp dir should clean up");
}
#[test]
fn latest_session_filters_out_zero_message_sessions() {
// given — one empty (0-message) session and one non-empty session
let base = temp_dir();
fs::create_dir_all(&base).expect("base dir should exist");
let store = SessionStore::from_cwd(&base).expect("store should build");
let empty_handle = store.create_handle("empty-session");
Session::new()
.with_persistence_path(empty_handle.path.clone())
.save_to_path(&empty_handle.path)
.expect("empty session should save");
wait_for_next_millisecond();
let non_empty = persist_session_via_store(&store, "real conversation");
// when
let latest = store.latest_session().expect("latest should resolve");
// then — the non-empty session wins; the 0-message one is filtered out
assert_eq!(
latest.id, non_empty.session_id,
"0-message session must be filtered out, non-empty session wins"
);
assert!(
latest.message_count > 0,
"resolved session must have messages"
);
fs::remove_dir_all(base).expect("temp dir should clean up");
}
#[test]
fn resolve_reference_excluding_latest_skips_excluded_id() {
// given — two sessions WITH messages
let base = temp_dir();
fs::create_dir_all(&base).expect("base dir should exist");
let store = SessionStore::from_cwd(&base).expect("store should build");
let older = persist_session_via_store(&store, "older work");
wait_for_next_millisecond();
let newer = persist_session_via_store(&store, "newer work");
// when — resolve the "latest" alias while excluding the newest session
let handle = store
.resolve_reference_excluding("latest", Some(&newer.session_id))
.expect("latest alias excluding newest should resolve");
// then — the excluded id is skipped, so the older session resolves
assert_eq!(
handle.id, older.session_id,
"excluded id must be skipped when resolving the latest alias"
);
fs::remove_dir_all(base).expect("temp dir should clean up");
}
#[test]
fn session_exists_and_delete_are_scoped_to_workspace_store() {
// given

View File

@@ -1644,16 +1644,13 @@ mod tests {
let tmp = tempfile::tempdir().expect("tempdir");
let worktree = tmp.path().join("worktree");
let git_dir = tmp.path().join("external-gitdir");
fs::create_dir_all(&worktree).expect("worktree dir");
fs::create_dir_all(git_dir.join("objects")).expect("objects dir");
fs::create_dir_all(git_dir.join("refs/heads")).expect("refs dir");
fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n").expect("HEAD");
fs::write(
worktree.join(".git"),
format!("gitdir: {}\n", git_dir.display()),
)
.expect(".git file");
Command::new("git")
.arg("init")
.current_dir(&worktree)
.output()
.expect("git init should run");
let git_dir = worktree.join(".git");
let original_permissions = fs::metadata(&git_dir)
.expect("gitdir metadata")

View File

@@ -0,0 +1,60 @@
# AGENTS.md — rusty-claude-cli (the `claw` binary)
## OVERVIEW
Crate `rusty-claude-cli` produces the `claw` binary (~25 subcommands). Wires together api, runtime, tools, commands, plugins; terminal via crossterm/rustyline/syntect. Hand-rolled arg parser (no clap).
## main.rs MAP
src/main.rs is ~19,800 lines. Landmark table:
| Lines | Section |
|---|---|
| 73330 | Provenance/model types (`ModelSource`, `ModelProvenance`, `PermissionModeSource`), build constants |
| 330682 | Error taxonomy (`classify_error_kind`, JSON/text error output) |
| 774994 | Global flags, `--cwd`/`-C` stripping, stdin plumbing |
| 9951158 | `run()`: single flat match dispatching `CliAction` variants |
| 11621280 | `CliAction` enum, 25 struct variants (each carries `output_format`) |
| 13121477 | Output-format machinery: `OnceLock` statics, duplicate-flag tracking |
| 14782272 | `parse_args`: ~800-line manual token loop |
| 25423389 | Per-subcommand sub-parsers inside `parse_args` |
| 29023389 | Model/permission/allowed-tools resolution |
| 33904696 | Doctor subsystem (~13 `check_*_health` fns) |
| 46976062 | Manifests, bootstrap-plan, system-prompt, version, `resume_session` |
| 54597047 | `StatusContext`, `BinaryProvenance`, broad-cwd policy, stale-base preflight |
| 70489423 | `run_repl` interactive loop (`LiveCli` struct, streaming, heartbeat, `HookAbortMonitor`) |
| 942414264 | Snapshot printers: session-list, status, sandbox, models, help topics, acp, `run_init` (L11027), `run_export` (L11715), `print_help` (L14055) |
| 1426619831 | In-file `mod tests` + 3 smaller test modules (one embeds a Python MCP fixture) |
## CONVENTIONS
- Every subcommand supports `--output-format text|json`, env-overridable.
- `raw_args_request_json_output` pre-scans argv before parsing to suppress stderr config warnings in JSON mode.
- Dual renderers for each output path: human text + structured `*_json`.
- Unknown flags/typos get levenshtein-distance suggestions.
- Comments carry issue numbers (#824, #146, etc.) when tracking known problems.
- `main()` (L330) is only the error envelope. All real work happens in `run()`.
- Error output always includes `status`, `error_kind`, `action`, `hint`, `exit_code` fields.
- `classify_error_kind` maps message prefixes to snake_case kind tokens.
- JSON errors go to stdout, text errors to stderr.
- Sibling modules: `init.rs`, `input.rs` (rustyline), `render.rs` (MarkdownStreamState, Spinner, syntect), `setup_wizard.rs`.
- `build.rs` injects `GIT_SHA`, `RUSTC_VERSION`, `GIT_DIRTY` via `cargo:rustc-env`.
## ANTI-PATTERNS
- File opens with crate-wide `#![allow(...)]` suppressing 13 lints including `dead_code` and `unused_imports`. Legacy. Do NOT extend this list.
- 9+ functions carry `#[allow(clippy::too_many_lines)]`. Tolerated, not license for more.
- Package/bin name mismatch: crate is `rusty-claude-cli`, binary is `claw`. Watch for this in paths and test macros.
## TESTS
All tests live in `tests/` (6 files), black-box style. They spawn `env!("CARGO_BIN_EXE_claw")` in unique temp dirs (AtomicU64 counter).
| File | What it covers |
|---|---|
| `output_format_contract.rs` | ~105 tests pinning `kind`/`status`/`action` JSON contract for EVERY subcommand. Must update when adding/changing any command output. 5,986 lines. |
| `resume_slash_commands.rs` | Resume and slash-command behavior |
| `cli_flags_and_config_defaults.rs` | Flag parsing, config file defaults |
| `compact_output.rs` | Compact output mode |
| `compact_repl_panic.rs` | Nested-runtime panic regression |
| `mock_parity_harness.rs` | Scenario-driven tests against mock-anthropic-service, driven by `rust/mock_parity_scenarios.json` |

File diff suppressed because it is too large Load Diff

View File

@@ -23,7 +23,10 @@ const DEFAULT_BASE_URLS: &[(&str, &str)] = &[
("anthropic", "https://api.anthropic.com"),
("xai", "https://api.x.ai/v1"),
("openai", "https://api.openai.com/v1"),
("dashscope", "https://dashscope.aliyuncs.com/compatible-mode/v1"),
(
"dashscope",
"https://dashscope.aliyuncs.com/compatible-mode/v1",
),
];
const API_KEY_ENV_VARS: &[(&str, &str)] = &[
@@ -51,12 +54,7 @@ pub fn run_setup_wizard() -> Result<(), Box<dyn std::error::Error>> {
let model = prompt_model(&kind, &current)?;
let fast_model = prompt_fast_model(&current, model.as_deref())?;
save_user_provider_settings(
&kind,
&api_key,
base_url.as_deref(),
model.as_deref(),
)?;
save_user_provider_settings(&kind, &api_key, base_url.as_deref(), model.as_deref())?;
if let Some(fast) = &fast_model {
save_settings_field("subagentModel", fast)?;
@@ -64,7 +62,10 @@ pub fn run_setup_wizard() -> Result<(), Box<dyn std::error::Error>> {
println!();
println!(" \x1b[32mProvider saved to ~/.claw/settings.json\x1b[0m");
println!(" Run \x1b[1m/model {}\x1b[0m or restart claw to activate.", model.as_deref().unwrap_or(&kind));
println!(
" Run \x1b[1m/model {}\x1b[0m or restart claw to activate.",
model.as_deref().unwrap_or(&kind)
);
println!();
Ok(())
@@ -82,7 +83,11 @@ fn prompt_provider(current: &RuntimeProviderConfig) -> Result<String, Box<dyn st
let current_kind = current.kind().unwrap_or("anthropic");
println!(" \x1b[1mProvider\x1b[0m");
for (num, label, kind) in PROVIDERS {
let marker = if *kind == current_kind { " (current)" } else { "" };
let marker = if *kind == current_kind {
" (current)"
} else {
""
};
println!(" [{num}] {label}{marker}");
}
let default = PROVIDERS
@@ -129,9 +134,7 @@ fn prompt_api_key(
};
// Check if env var is already set
let env_set = std::env::var(env_var)
.ok()
.is_some_and(|v| !v.is_empty());
let env_set = std::env::var(env_var).ok().is_some_and(|v| !v.is_empty());
if env_set {
println!(" {env_var} is set in environment (will take priority over stored key)");
}
@@ -144,7 +147,9 @@ fn prompt_api_key(
};
if key.is_empty() && !env_set {
eprintln!(" \x1b[33mWarning: no API key configured. Set {env_var} or re-run setup.\x1b[0m");
eprintln!(
" \x1b[33mWarning: no API key configured. Set {env_var} or re-run setup.\x1b[0m"
);
}
Ok(key)
@@ -174,9 +179,7 @@ fn prompt_base_url(
"dashscope" => "DASHSCOPE_BASE_URL",
_ => "BASE_URL",
};
let env_set = std::env::var(env_var)
.ok()
.is_some_and(|v| !v.is_empty());
let env_set = std::env::var(env_var).ok().is_some_and(|v| !v.is_empty());
if env_set {
println!(" {env_var} is set in environment (will take priority over stored URL)");
}
@@ -203,7 +206,9 @@ fn prompt_model(
.find(|(k, _)| *k == kind)
.map_or(empty, |(_, models)| *models);
let current_model = current.model().unwrap_or(aliases.first().copied().unwrap_or(""));
let current_model = current
.model()
.unwrap_or(aliases.first().copied().unwrap_or(""));
println!(" \x1b[1mModel\x1b[0m");
if !aliases.is_empty() {
@@ -235,12 +240,16 @@ fn prompt_fast_model(
println!(" Press Enter to skip (agents will use your main model).");
let current_fast = load_current_settings_field("subagentModel");
let default_hint = current_fast
.as_deref()
.or(main_model)
.unwrap_or("");
let default_hint = current_fast.as_deref().or(main_model).unwrap_or("");
let input = read_line(&format!(" Fast model [{}]: ", if default_hint.is_empty() { "same as main" } else { default_hint }))?;
let input = read_line(&format!(
" Fast model [{}]: ",
if default_hint.is_empty() {
"same as main"
} else {
default_hint
}
))?;
if input.trim().is_empty() {
Ok(current_fast)
} else {
@@ -269,7 +278,10 @@ fn save_settings_field(field: &str, value: &str) -> Result<(), Box<dyn std::erro
};
if let Some(obj) = settings.as_object_mut() {
obj.insert(field.to_string(), serde_json::Value::String(value.to_string()));
obj.insert(
field.to_string(),
serde_json::Value::String(value.to_string()),
);
}
std::fs::create_dir_all(&settings_dir)?;

View File

@@ -112,6 +112,7 @@ fn assert_doctor_help_json_contract(parsed: &Value) {
assert!(checks.iter().any(|check| check == "boot preflight"));
assert!(checks.iter().any(|check| check == "memory"));
assert!(checks.iter().any(|check| check == "mcp validation"));
assert!(checks.iter().any(|check| check == "hook validation"));
}
#[test]
@@ -840,14 +841,19 @@ fn acp_guidance_emits_json_when_requested() {
let root = unique_temp_dir("acp-json");
fs::create_dir_all(&root).expect("temp dir should exist");
let acp = assert_json_command(&root, &["--output-format", "json", "acp"]);
// #443: acp serve exits 2 (not implemented) instead of 0
let output = run_claw(&root, &["--output-format", "json", "acp"], &[]);
assert_eq!(
output.status.code(),
Some(2),
"acp should exit 2 (not implemented)"
);
let acp: Value =
serde_json::from_slice(&output.stdout).expect("acp stdout should be valid json");
assert_eq!(acp["kind"], "acp");
assert_eq!(acp["schema_version"], "1.0");
assert_eq!(acp["status"], "unsupported");
assert_eq!(acp["phase"], "discoverability_only");
assert_eq!(acp["status"], "not_implemented");
assert_eq!(acp["supported"], false);
assert_eq!(acp["exit_code"], 0);
assert_eq!(acp["serve_alias_only"], true);
assert_eq!(acp["protocol"]["json_rpc"], false);
assert_eq!(acp["protocol"]["daemon"], false);
assert!(acp["protocol"]["endpoint"].is_null());
@@ -855,12 +861,23 @@ fn acp_guidance_emits_json_when_requested() {
acp["contracts"]["unsupported_invocation_kind"],
"unsupported_acp_invocation"
);
assert_eq!(acp["discoverability_tracking"], "ROADMAP #64a");
assert_eq!(acp["tracking"], "ROADMAP #76 / #3033 / #3004");
// #443: internal tracking IDs removed from public JSON
assert!(
acp.get("discoverability_tracking").is_none(),
"discoverability_tracking should be removed (#443)"
);
assert!(
acp.get("tracking").is_none(),
"tracking should be removed (#443)"
);
assert!(
acp.get("recommended_workflows").is_none(),
"recommended_workflows should be removed (#443)"
);
assert!(acp["message"]
.as_str()
.expect("acp message")
.contains("discoverability alias"));
.contains("not implemented"));
}
#[test]
@@ -1459,7 +1476,7 @@ fn doctor_and_resume_status_emit_json_when_requested() {
.is_some_and(|available| available.iter().any(|name| name == "web_fetch")));
let checks = doctor["checks"].as_array().expect("doctor checks");
assert_eq!(checks.len(), 10);
assert_eq!(checks.len(), 12);
let check_names = checks
.iter()
.map(|check| {
@@ -1479,8 +1496,10 @@ fn doctor_and_resume_status_emit_json_when_requested() {
check_names,
vec![
"auth",
"base urls",
"config",
"mcp validation",
"hook validation",
"install source",
"workspace",
"memory",
@@ -2063,7 +2082,7 @@ fn local_json_surfaces_have_non_empty_action_contract_714() {
&git_workspace,
strings(&["--output-format", "json", "diff"]),
),
(&workspace, strings(&["--output-format", "json", "acp"])),
// #443: ACP exits 2 (not implemented); tested separately in acp_guidance_emits_json_when_requested
(&workspace, strings(&["--output-format", "json", "config"])),
(
&workspace,
@@ -3346,7 +3365,7 @@ fn config_unsupported_section_json_hint_741() {
fs::create_dir_all(&root).expect("temp dir");
let bin = env!("CARGO_BIN_EXE_claw");
for section in &["list", "show", "bogus", "help"] {
for section in &["list", "show", "bogus"] {
let output = Command::new(bin)
.current_dir(&root)
.args(["--output-format", "json", "config", section])
@@ -3384,6 +3403,36 @@ fn config_unsupported_section_json_hint_741() {
}
}
#[test]
fn config_help_returns_structured_section_list_344() {
// #344: /config help should return a structured section list, not an error
use std::process::Command;
let root = unique_temp_dir("config-help");
fs::create_dir_all(&root).expect("temp dir");
let bin = env!("CARGO_BIN_EXE_claw");
let output = Command::new(bin)
.current_dir(&root)
.args(["--output-format", "json", "config", "help"])
.output()
.expect("claw config help should run");
let stdout = String::from_utf8_lossy(&output.stdout);
let parsed: serde_json::Value =
serde_json::from_str(stdout.trim()).expect("config help should emit valid JSON");
assert_eq!(parsed["kind"], "config", "config help kind must be config");
assert_eq!(
parsed["status"], "ok",
"config help must return status:ok (#344)"
);
assert_eq!(
parsed["section"], "help",
"config help section must be help"
);
let sections = parsed["available_sections"]
.as_array()
.expect("config help must have available_sections array");
assert!(!sections.is_empty(), "available_sections must not be empty");
}
#[test]
fn export_json_has_kind_702() {
// #458/#702: `claw export --output-format json` must emit kind:export.
@@ -3866,7 +3915,7 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
};
let parsed: serde_json::Value =
serde_json::from_str(json_str.trim()).expect("mcp bogus should emit JSON");
assert_eq!(parsed["error_kind"], "unknown_mcp_action");
assert_eq!(parsed["error_kind"], "unsupported_action");
let hint = parsed["hint"].as_str().unwrap_or("");
assert!(!hint.is_empty(), "mcp bogus hint must be non-null (#774)");
}
@@ -4146,8 +4195,8 @@ fn acp_unsupported_invocation_has_hint_782() {
.expect("hint must be non-null (#782)");
assert!(!hint.is_empty(), "hint must not be empty");
assert!(
hint.contains("discoverability") || hint.contains("ROADMAP"),
"hint should explain the discoverability-only status, got: {hint:?}"
hint.contains("not implemented") || hint.contains("unsupported"),
"hint should explain the not-implemented status, got: {hint:?}"
);
}

View File

@@ -530,8 +530,9 @@ fn resumed_help_command_emits_structured_json() {
let stdout = String::from_utf8(output.stdout).expect("utf8");
let parsed: Value = serde_json::from_str(stdout.trim()).expect("should be json");
assert_eq!(parsed["kind"], "help");
assert!(parsed["text"].as_str().is_some());
let text = parsed["text"].as_str().unwrap();
// #338: resume help now uses 'message' field for parity with top-level help
assert!(parsed["message"].as_str().is_some());
let text = parsed["message"].as_str().unwrap();
assert!(text.contains("/status"), "help text should list /status");
}

View File

@@ -0,0 +1,47 @@
# AGENTS.md — rust/crates/tools
## OVERVIEW
Single-crate tool surface: registry, 55 tool specs, permission-gated dispatch, all implementations. One flat `src/lib.rs` (10,892 lines, ~37% tests).
## lib.rs MAP
| Lines | Landmark |
|-------------|----------|
| 174 | Imports + six `global_*_registry()` OnceLock singletons (Lsp, McpTool, Team, Cron, Task, Worker) |
| 75483 | Registry API: `ToolManifestEntry`, `ToolSource`, `ToolRegistry`, `ToolSpec`, `GlobalToolRegistry`, `RuntimeToolDefinition`, `canonical_allowed_tool_name` |
| 4841348 | `mvp_tool_specs()` static table of 55 tools with inline JSON schemas |
| 13491524 | `enforce_permission_check` + `execute_tool()` string-match dispatch, permission classification helpers |
| 15252735 | `run_*` wrappers: deserialize input, call into `execute_*` or runtime fns |
| 27362763 | `workspace_traversal_guard_tests` mod |
| 27643354 | ~45 private serde IO structs |
| 33556824 | Real implementations: web fetch/search, todo store, skill resolution, agent/subagent spawning (`ProviderRuntimeClient` L5182, `SubagentToolExecutor` L5361), notebook edit, sleep, config, plan-mode, structured output, REPL, PowerShell |
| 68256826 | `pub mod lane_completion; pub mod pdf_extract;` |
| 682910892 | `mod tests` (~4000 lines) |
## ADDING A TOOL
1. Add a `ToolSpec` entry in `mvp_tool_specs()`. Include `name`, `description`, `input_schema` (inline JSON), and `required_permission: PermissionMode`.
2. Add a dispatch arm in `execute_tool()` matching the tool name string.
3. Write a `run_<tool>()` wrapper. Deserialize input from a dedicated serde struct.
4. Implement the actual logic below L3355 (or call into another crate).
5. Add inline tests in `mod tests`. Follow BDD naming: `given_x_when_y_then_z`.
6. Permission gating is automatic: `GlobalToolRegistry` / `SubagentToolExecutor` hold an optional `PermissionEnforcer` checked pre-dispatch.
## CONVENTIONS
- **Tool boundary signature**: `Result<String, String>`. Always.
- **Tool naming**: snake_case for file/shell tools, PascalCase otherwise. `canonical_allowed_tool_name` normalizes aliases.
- **State**: OnceLock registries for global singletons. JSON state files under config dirs for persistence.
- **Input validation**: reject empty strings for todos, descriptions, prompts, messages, code. ~12 validation sites between L38066167. Keep that contract.
- **Test naming**: BDD style (`given_x_when_y_then_z`).
- **Env-mutating tests**: acquire `env_lock()` mutex first.
- **Dependencies**: runtime, api, plugins, commands, reqwest(blocking), aspect-*, tokio.
## ANTI-PATTERNS
- **Don't add more `#[allow(clippy::...)]` suppressions.** ~50 `needless_pass_by_value` and several `too_many_lines` allows exist as legacy debt. Don't extend.
- **Don't skip input validation.** Empty-string rejection is a contract across all user-facing text fields.
- **Don't scatter implementation across new submodules.** The crate is intentionally flat (one lib.rs + two leaf mods). Only `lane_completion` and `pdf_extract` break out.
- **Don't duplicate tool names.** The canonical name mapping already handles aliases.
- **Don't bypass `enforce_permission_check`.** Every tool dispatch goes through permission gating. No exceptions.

View File

@@ -2701,6 +2701,20 @@ fn is_within_workspace(path: &str) -> bool {
let path = PathBuf::from(trimmed);
// Reject any parent-directory traversal. Callers never need `..` to refer
// to files inside the workspace, and `..` defeats both checks below: the
// relative branch only inspects the leading component, and the absolute
// branch's `canonicalize()` silently falls back to the literal `..` path
// when the target does not exist yet (e.g. a file about to be created).
// Returning false here is the safe direction: it classifies the command as
// requiring full-access permission rather than workspace-write.
if path
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
{
return false;
}
// If path is absolute, check if it starts with CWD
if path.is_absolute() {
if let Ok(cwd) = std::env::current_dir() {
@@ -2718,6 +2732,26 @@ fn run_powershell(input: PowerShellInput) -> Result<String, String> {
to_pretty_json(execute_powershell(input).map_err(|error| error.to_string())?)
}
#[cfg(test)]
mod workspace_traversal_guard_tests {
use super::is_within_workspace;
#[test]
fn rejects_parent_traversal_components() {
// Leading and embedded `..` must both be rejected (was previously a hole
// because only the leading component was inspected).
assert!(!is_within_workspace("../secrets"));
assert!(!is_within_workspace("src/../../etc/passwd"));
assert!(!is_within_workspace("a/b/../../../etc/crontab"));
}
#[test]
fn allows_plain_relative_paths() {
assert!(is_within_workspace("src/main.rs"));
assert!(is_within_workspace("Cargo.toml"));
}
}
fn to_pretty_json<T: serde::Serialize>(value: T) -> Result<String, String> {
serde_json::to_string_pretty(&value).map_err(|error| error.to_string())
}

69
src/AGENTS.md Normal file
View File

@@ -0,0 +1,69 @@
# src/ AGENTS.md
## OVERVIEW
This is a **porting workspace**, not production code. Nothing here is imported by,
built with, or shipped in the Rust product (`rust/crates/`). The Python tree exists
solely to mirror and track parity against the Claude Code TypeScript source.
## STRUCTURE
```
src/
├── main.py # argparse CLI entry point (summary, parity-audit, manifest, etc.)
├── ~38 top-level .py # mirror TS root files one-to-one
├── models.py # frozen dataclasses: Subsystem, PortingModule, PermissionDenial, ...
├── parity_audit.py # hard-coded TS→Python filename mapping (main.tsx→main.py, etc.)
├── port_manifest.py # builds a manifest of the src/ tree itself
├── reference_data/ # tracked JSON snapshots extracted from the TS archive
│ ├── archive_surface_snapshot.json
│ ├── tools_snapshot.json, commands_snapshot.json
│ └── subsystems/*.json (29 per-subsystem records)
└── ~30 subdirectories/ # PLACEHOLDER PACKAGES (assistant/, bootstrap/, voice/, vim/, ...)
└── each contains only __init__.py loading subsystems/<name>.json
```
Placeholder packages follow an identical template: load
`reference_data/subsystems/<name>.json` via `_archive_helper.load_archive_metadata()`,
re-export `ARCHIVE_NAME`, `MODULE_COUNT`, `SAMPLE_FILES`, `PORTING_NOTE`. There is no
voice, vim, or other real functionality behind them.
## WHERE TO LOOK
| Goal | Start here |
|---|---|
| Understand the CLI subcommands | `main.py` |
| See which TS files map to which .py | `parity_audit.py` |
| Find shared data structures | `models.py` |
| Check TS archive metadata | `reference_data/` |
| Real logic (permissions, path scoping) | `permissions.py`, `path_scope.py` |
| Query engine shim | `query_engine.py` |
| Runtime simulation | `runtime.py` |
| Tests | repo-root `tests/` (test_porting_workspace.py, test_security_scope.py) |
Run tests: `python -m unittest discover -s tests` from repo root.
## CONVENTIONS
- snake_case filenames, preserving TS names. camelCase exceptions exist where the
TS original used it: `QueryEngine.py`, `costHook.py`, `replLauncher.py`.
- Every mirrored entry carries a `source_hint` pointing back to its original `.ts`/`.tsx` path.
- `from __future__ import annotations` throughout. Stdlib only, no third-party deps.
- `models.py` dataclasses are frozen. Renderers are `as_markdown()` / `to_markdown()`.
- main.py simulates routing, turn-loops, bootstrap over mirrored inventories.
Read-only shims return handled/message results. It never calls an LLM.
- Thin shim modules (e.g. `ink.py`) exist as backlog metadata, not working code.
## ANTI-PATTERNS
**Don't add real agent, tool, voice, or vim functionality here.** That belongs in
`rust/crates/`. This tree is a scaffold, not an implementation target.
**Don't commit anything from `archive/`.** The local TS snapshot
(`archive/claude_code_ts_snapshot/src`) is gitignored. `reference_data/` holds the
tracked extracts; work from those.
**Don't let parity_audit.py drift.** When you rename a mirrored module, update the
hard-coded mapping in `parity_audit.py` to match.
**Don't add third-party dependencies.** Everything runs on stdlib.

View File

@@ -55,7 +55,8 @@ def command_names() -> list[str]:
def get_command(name: str) -> PortingModule | None:
needle = COMMAND_ALIASES.get(name.lower(), name.lower())
normalized = name.strip().lower()
needle = COMMAND_ALIASES.get(normalized, normalized)
for module in PORTED_COMMANDS:
if module.name.lower() == needle:
return module
@@ -72,8 +73,15 @@ def get_commands(cwd: str | None = None, include_plugin_commands: bool = True, i
def find_commands(query: str, limit: int = 20) -> list[PortingModule]:
needle = query.lower()
needle = query.strip().lower()
matches = [module for module in PORTED_COMMANDS if needle in module.name.lower() or needle in module.source_hint.lower()]
matches.sort(
key=lambda module: (
module.name.lower() != needle,
not module.name.lower().startswith(needle),
needle not in module.name.lower(),
)
)
return matches[:limit]

View File

@@ -11,6 +11,7 @@ _GLOB_META = set('*?[')
_WINDOWS_DRIVE_RE = re.compile(r'^[A-Za-z]:[\\/]')
_WINDOWS_UNC_RE = re.compile(r'^(?:\\\\|//)[^\\/]+[\\/][^\\/]+')
_ENV_ASSIGNMENT_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*=')
_REDIRECTION_TARGET_RE = re.compile(r'^(?:\d*)?(?:<>|>>?|<)(.+)$|^&>>?(.+)$')
@dataclass(frozen=True)
@@ -118,6 +119,7 @@ def extract_path_candidates(payload: str) -> tuple[str, ...]:
for token in (*tokens, *raw_tokens):
if not token or token.startswith('-') or _ENV_ASSIGNMENT_RE.match(token):
continue
token = _strip_redirection_operator(token)
expanded = os.path.expandvars(os.path.expanduser(token))
if _looks_like_path(token) or _looks_like_path(expanded):
candidate = expanded if _looks_like_path(expanded) else token
@@ -138,6 +140,13 @@ def _looks_like_path(token: str) -> bool:
)
def _strip_redirection_operator(token: str) -> str:
match = _REDIRECTION_TARGET_RE.match(token)
if match is None:
return token
return next(group for group in match.groups() if group is not None)
def _is_windows_absolute(value: str) -> bool:
return bool(_WINDOWS_DRIVE_RE.match(value) or _WINDOWS_UNC_RE.match(value))

View File

@@ -183,6 +183,13 @@ class PortingWorkspaceTests(unittest.TestCase):
self.assertIn("Mirrored command 'plugin'", result.stdout)
self.assertNotIn('Unknown mirrored command', result.stdout)
def test_command_lookup_normalizes_user_input_whitespace(self) -> None:
from src.commands import execute_command, find_commands, get_command
self.assertEqual('plugin', get_command(' PLUGINS ').name)
self.assertEqual('review', find_commands(' review ', limit=1)[0].name)
self.assertIn("Mirrored command 'plugin'", execute_command(' marketplace ', 'browse').message)
def test_route_plugin_slash_commands_match_commands(self) -> None:
prompts = ('/plugin list', '/plugins list', '/marketplace browse', '/reload-plugins')
for prompt in prompts:

View File

@@ -72,6 +72,28 @@ class WorkspacePathScopeTests(unittest.TestCase):
self.assertFalse(decision.allowed)
self.assertIn(str(outside.resolve()), decision.resolved or '')
def test_attached_shell_redirection_targets_are_validated(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
workspace = root / 'workspace'
outside = root / 'outside'
workspace.mkdir()
outside.mkdir()
(outside / 'secret.txt').write_text('secret')
self.assertEqual(
('../outside/secret.txt', '../outside/error.log'),
extract_path_candidates(
'cat <../outside/secret.txt 2>../outside/error.log'
),
)
decision = WorkspacePathScope.from_root(workspace).validate_payload(
'cat <../outside/secret.txt 2>../outside/error.log'
)
self.assertFalse(decision.allowed)
self.assertIn(str(outside.resolve()), decision.resolved or '')
def test_explicit_worktree_roots_are_allowed(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)