Compare commits

245 Commits
Author SHA1 Message Date
Dark-Alex-17 b9474ce6ef feat: Used improved theme selections for tool call highlighting colors
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-23 18:51:57 -06:00
Dark-Alex-17 d328310880 feat: Improved theme-derived syntax highlighting for LLM tool call logging 2026-07-23 18:45:23 -06:00
Dark-Alex-17 5eb77ab467 feat: Improved coloring of LLM tool invocation outputs to make LLM output more readable and cohesive 2026-07-23 18:27:54 -06:00
Dark-Alex-17 a2c4f05c8c feat: renamed the user__ask to user__select and improved descriptions to improve model usage 2026-07-23 18:22:18 -06:00
Dark-Alex-17 89fadcca15 feat: Improved coloring/highlighting of tool calls to make LLM invocation logs easier to read 2026-07-23 18:12:18 -06:00
Dark-Alex-17 ab3a818507 docs: Added the new compression control fields to the config example file
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-23 12:40:38 -06:00
Dark-Alex-17 63f73f22c3 style: applied formatting to new long run features
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-23 12:30:30 -06:00
Dark-Alex-17 54c5079cb7 feat: long-running session improvements
- Hang fix: 120s timeout on compression LLM call + raw_stream
  channel-close handling (None => break instead of spinning)
- Supervisor effective active count: stop counting finished
  JoinHandles as occupying capacity slots
- Universal tool result size cap: truncate_if_needed() on
  ToolResult, applied in eval_tool_calls() after escalation block;
  configurable via max_tool_result_chars in AppConfig/AgentConfig
- Windowed compression: compression_keep_last config param keeps
  the N most recent messages visible after compression
- Fix pre-existing flaky test: add #[serial] to
  handle_list_available_unrestricted_when_no_whitelist so it does
  not race with TestConfigDirGuard-based tests that temporarily
  populate the agents data dir
2026-07-23 12:25:54 -06:00
Dark-Alex-17 d51bdd3086 feat: Made sisyphus suite of agents all auto-approved for tool usage
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 22:28:20 -06:00
Dark-Alex-17 56ec58a748 fix: removed accidental duplicate ast_grep tool in explore agent
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 17:42:14 -06:00
Dark-Alex-17 93f9c5425e fix: npm and npx need the /usr/local/share/npm-global/lib directory to exist to run properly so I've added it to the dockerfile
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 17:11:57 -06:00
Dark-Alex-17 77dfd08103 fix: added executable bit to adversary agent tools script 2026-07-22 16:38:42 -06:00
Dark-Alex-17 46dcef0dec Merge branch 'main' of github.com:Dark-Alex-17/coyote 2026-07-22 16:37:34 -06:00
Dark-Alex-17 72c6bb74c2 feat: created the adversay agent and adversarial-review skill 2026-07-22 16:35:00 -06:00
Dark-Alex-17 6bf80dcce9 feat: added ast_grep tool to Sisyphus suite agents
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 15:41:09 -06:00
Dark-Alex-17 df948c69bf feat: new spawnable_agents field in agents to let users restrict what agents can be spawned by a parent agent
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 14:29:55 -06:00
Dark-Alex-17 e5d0fcc764 test: fixed linter issues on markdown tests
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 13:32:37 -06:00
Dark-Alex-17 c60d3e7cda style: updated some stylistic things across the new markdown rendering implementation
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 13:20:56 -06:00
Dark-Alex-17 c21fd47b42 feat: replay pre-compressed messages as well when resuming sessions for users to see 2026-07-22 13:05:06 -06:00
Dark-Alex-17 ab0b89dd67 fix: fetch descriptions from graph agent configs as well when listing agents 2026-07-22 12:59:30 -06:00
Dark-Alex-17 420db4bb88 feat: created a new builtin function for agents who can spawn other agents to list available agents via agent__list_available 2026-07-22 12:50:41 -06:00
Dark-Alex-17 dfacf31f6a fix(render): suppress blank lines above rendered table 2026-07-22 12:37:30 -06:00
Dark-Alex-17 8cfd5ee2c4 docs(render): update phase 2.7 SHA after amend 2026-07-22 12:30:34 -06:00
Dark-Alex-17 e82e5ab8e4 test(render): comprehensive table rendering coverage 2026-07-22 12:30:10 -06:00
Dark-Alex-17 d790782ace feat(render): hanging-indent line wrapping for lists and blockquotes 2026-07-22 12:27:13 -06:00
Dark-Alex-17 bf06d5e8f3 feat(render): wire table state machine and finalize hook 2026-07-22 12:23:44 -06:00
Dark-Alex-17 cdfaa0f111 feat(render): render markdown tables with comfy-table 2026-07-22 12:20:02 -06:00
Dark-Alex-17 c062f34852 feat(render): parse table cells and column alignments 2026-07-22 12:16:05 -06:00
Dark-Alex-17 7671d28d6e feat(render): detect markdown table rows and separators 2026-07-22 12:14:45 -06:00
Dark-Alex-17 fcc4a1d2b5 feat(render): add comfy-table dependency and table border style 2026-07-22 12:11:04 -06:00
Dark-Alex-17 b0eeba110d test(render): comprehensive coverage for rich markdown renderer 2026-07-22 11:48:43 -06:00
Dark-Alex-17 d65d63ee50 feat(render): activate rich markdown renderer as default 2026-07-22 11:47:39 -06:00
Dark-Alex-17 9890cf0ddc feat(render): rich block-level markdown rendering (headings, quotes, lists, hr) 2026-07-22 11:45:03 -06:00
Dark-Alex-17 89db5b3887 feat(render): rich inline markdown rendering (bold, italic, code, links) 2026-07-22 11:41:35 -06:00
Dark-Alex-17 f40ba4ccbe feat(render): detect markdown block-level line types 2026-07-22 11:37:11 -06:00
Dark-Alex-17 d2940a8d32 feat(render): precompute markdown scope styles for rich rendering 2026-07-22 11:31:23 -06:00
Dark-Alex-17 ed7ad36475 feat: Created the raw_markdown configuration flag 2026-07-22 11:03:27 -06:00
Dark-Alex-17 393ed16963 fix: chown the full sandbox cache dir, not just the coyote subdir
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 10:08:00 -06:00
Dark-Alex-17 3f94d2003a fix: chown the whole coyote cache dir not just the oauth dir in the sandbox
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 09:48:11 -06:00
Dark-Alex-17 50ff9008fe chore: updated deepseek models
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-22 09:31:17 -06:00
Dark-Alex-17 9606d7f8aa feat: added a .fork command to fork a new session from a running conversation
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-21 14:54:55 -06:00
Dark-Alex-17 d8ae9e25d9 docs: reworded explore agent instructions to empower agent to spawn as many sub agents as it deems necessary
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-21 14:14:00 -06:00
Dark-Alex-17 006f64bfa0 docs: Improved sisyphus wording to empower agent to spawn as many subagents as necessary 2026-07-21 14:12:51 -06:00
Dark-Alex-17 000559bc9d style: Applied formatting
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-21 11:24:18 -06:00
Dark-Alex-17 3aede58a11 feat(oauth): enable browser-paste PKCE flow for OpenAI-compatible providers
Two coordinated changes that make openai-compatible OAuth providers usable
with a non-localhost redirect_uri (browser shows the callback URL, user
copies it back into the terminal — the same UX Claude uses).

Fix: OpenAICompatibleOAuthProvider::fixed_redirect_uri() previously returned
Some(uri) for any redirect_uri including public HTTPS URLs, which trapped
run_pkce_flow into trying to bind a TCP listener on a public URL. It now
returns Some only for loopback URIs (127.0.0.1, localhost, ::1). Non-loopback
URIs return None, routing run_pkce_flow to the paste branch.

New tri-format paste parser (parse_paste_input):
- Full callback URL (starts with http:// or https://): parse code + state from
  the query string. This is what most modern OAuth providers redirect to and
  what a naive user copies from the browser bar.
- Anthropic-style code#state fragment: preserved for Claude compatibility.
- Bare code: accepted with a warning that CSRF state validation is skipped.
  For providers whose callback page shows only the code with no state.

State validation moved from mandatory to conditional — if a paste didn't
carry state (bare-code path), we warn and skip the check instead of hard-
failing. The listener path (localhost + LAN redirects) still requires state
because the server sends it in the query.

Adds 9 unit tests covering both changes.
2026-07-21 11:14:55 -06:00
Dark-Alex-17 cab1e72b97 fix: fix typo in Gemini's generation_config property to use camelCase exclusively 2026-07-21 11:11:00 -06:00
Dark-Alex-17 cd4bf245e9 chore: updated models.yaml 2026-07-21 11:09:51 -06:00
Dark-Alex-17 82bf6176f8 fix(oauth): treat missing expires_in as non-expiring device_code token
GitHub OAuth Apps issue tokens that never expire and omit expires_in from
the response (they only send access_token, token_type, scope). RFC 6749 §5.1
allows this — expires_in is only REQUIRED for tokens that actually expire.

When expires_in is missing, save the token with expires_at = i64::MAX so
prepare_oauth_access_token never tries to refresh. If the token is ever
revoked server-side, the eventual 401 on the API call is the user's cue
to re-authenticate.

No effect on providers that include expires_in (Moonshot etc. — unchanged).
2026-07-21 10:32:47 -06:00
Dark-Alex-17 d407eb5a6a fix(oauth): send Accept: application/json in device flow requests
GitHub's device flow endpoints (and likely other RFC 8628 servers) default
to responding in application/x-www-form-urlencoded unless the client asks
for JSON via the Accept header. Our device auth and polling paths both call
.json() on the response and were failing to decode form-urlencoded bodies
with 'expected value at line 1 column 1'.

Adds Accept: application/json to:
- The device authorization POST in run_device_code_flow
- The device_code polling POST (on the RequestBuilder returned by build_token_request)

RFC 6749 §5.1 already specifies JSON as the token response format, so this
is spec-compliant across providers. Servers that already default to JSON
(Moonshot, etc.) ignore the redundant header.
2026-07-21 10:30:36 -06:00
Dark-Alex-17 6f2594712f refactor: Standardized paths module function names to not use 'path' in the name and to just always be either 'dir' or 'file'
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-21 10:15:42 -06:00
Dark-Alex-17 79d43c8791 docs: config.example.yaml example for Device Authorization Grant
Adds a commented example under the openai-compatible client section showing
how to configure flow: device_code for RFC 8628 device flow. Uses Moonshot's
kimi-code endpoints as the illustrative reference (users supply their own
client_id — no bundled defaults per §5.8 of the design plan).
2026-07-20 15:27:20 -06:00
Dark-Alex-17 5a5da90734 test: unit tests for OAuthFlow::DeviceCode and merge behavior
Adds 9 unit tests covering:
- yaml deserialization of flow: device_code
- merge preserves base device_authorization_url when user omits
- merge lets user device_authorization_url win
- merge lets user use_pkce_in_device_flow win
- OpenAICompatibleOAuthProvider exposes / defaults both new trait methods
- Full serde roundtrip of a realistic device_code yaml block

No network or polling — pure config/serde logic tests. Brings the test
count from 1134 to 1143.
2026-07-20 15:25:24 -06:00
Dark-Alex-17 f2a0e7453e feat: copy host OAuth tokens into sandbox at launch
Projects ~/.cache/coyote/oauth/ from the host into /home/agent/.cache/coyote/oauth/
inside the sandbox so agents can call OAuth-authenticated providers without
re-authenticating. Same trust model as the existing config-dir and vault-password
copies. One-way copy (not bind-mount) — matches Docker's universal support
surface. Refreshed tokens die with the sandbox instance; run coyote --authenticate
inside if a fresh token is needed (Device Flow works via the QR code render).
2026-07-20 15:23:52 -06:00
Dark-Alex-17 0fe430102a feat: implement OAuth 2.0 Device Authorization Grant (RFC 8628)
Adds a third OAuthFlow variant (device_code) alongside the existing pkce and
client_credentials flows. Device flow enables OAuth for headless environments
where a browser-based callback listener isn't available — the user visits a
verification URL on any device and enters a short user_code.

- OAuthFlow::DeviceCode variant + serde 'device_code' string
- OAuthConfig fields: device_authorization_url, use_pkce_in_device_flow
- OAuthProvider trait: device_authorization_url() / use_pkce_in_device_flow()
- OpenAICompatibleOAuthProvider passes both through from config
- run_device_code_flow() polls the token endpoint per RFC 8628 §3.4–§3.5:
  handles authorization_pending, slow_down (+5s backoff), expired_token,
  access_denied, and unknown errors distinctly
- Sandbox-gated QR code display (via qrcode crate) — scanning with a phone
  is dramatically faster than copy-pasting the URL from a container
- Optional PKCE per draft-ietf-oauth-device-flow §5.4 (default off)
- run_oauth_flow and prepare_oauth_access_token dispatchers wire DeviceCode
  in; refresh path shared with PKCE since both flows produce refresh_tokens
2026-07-20 15:21:32 -06:00
Dark-Alex-17 d13bd32fdf chore: add qrcode dependency 2026-07-20 15:13:40 -06:00
Dark-Alex-17 1f1729ba00 chore: added new kimi models
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-20 14:35:26 -06:00
Dark-Alex-17 107419966d style: Cleaned up some comments and imports 2026-07-20 13:46:41 -06:00
Dark-Alex-17 344ef7526f feat: hint that browser 'paste code' pages can be ignored during callback capture 2026-07-20 13:29:37 -06:00
Dark-Alex-17 13d31f850c fix: OAuth callback listener skips speculative/malformed browser connections 2026-07-20 13:21:44 -06:00
Dark-Alex-17 f6bd02dc73 feat: openai-compatible wizard offers OAuth when provider has bundled oauth defaults 2026-07-20 13:17:26 -06:00
Dark-Alex-17 31df1a720d test: unit tests for OAuthConfig merge + get_oauth_provider_for_client 2026-07-20 13:12:38 -06:00
Dark-Alex-17 4e0e65fc8a docs: config.example.yaml OAuth examples for openai-compatible 2026-07-20 13:09:50 -06:00
Dark-Alex-17 ab85a4f534 feat: validate unique client names at config load 2026-07-20 13:07:41 -06:00
Dark-Alex-17 420447275c refactor: main.rs resolve_oauth_client uses new dispatcher 2026-07-20 13:05:57 -06:00
Dark-Alex-17 cdc40f7302 feat: bundle xAI OAuth defaults in models.yaml 2026-07-20 13:03:15 -06:00
Dark-Alex-17 c611685033 feat: OAuth branch in openai_compatible prepare_* fns 2026-07-20 13:01:28 -06:00
Dark-Alex-17 cac2a3eba0 feat: get_oauth_provider_for_client dispatcher + client_config_info update 2026-07-20 12:57:10 -06:00
Dark-Alex-17 66bbb34d7f feat: OpenAICompatibleOAuthProvider (config-driven OAuthProvider impl) 2026-07-20 12:55:30 -06:00
Dark-Alex-17 68177fdb6a feat: add auth + oauth fields to OpenAICompatibleConfig 2026-07-20 12:51:09 -06:00
Dark-Alex-17 1acaad223f feat: add oauth field to ProviderModels 2026-07-20 12:46:18 -06:00
Dark-Alex-17 aa0270602d feat: add client_credentials support to prepare_oauth_access_token 2026-07-20 12:44:53 -06:00
Dark-Alex-17 4669958bdd refactor: split run_oauth_flow into pkce + client_credentials dispatchers 2026-07-20 12:43:53 -06:00
Dark-Alex-17 559107073d feat: add OAuthConfig + OAuthFlow types to oauth.rs 2026-07-20 12:41:24 -06:00
Dark-Alex-17 d0a38747e0 chore: updated models.yaml
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-20 11:55:00 -06:00
Dark-Alex-17 677bd71b93 docs: added brew trust command to install example for iwe
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-19 15:24:13 -06:00
Dark-Alex-17 ad6d0a2e0e fix: resolve reasoning effort for the prompt for global defaults as well
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 17:52:38 -06:00
Dark-Alex-17 50911b99ef fix: Account for default model reasoning_effort when supplying that value for the REPL prompts
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 17:42:10 -06:00
Dark-Alex-17 44783c5573 feat: Added reasoning effort to the right prompt
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 17:34:10 -06:00
Dark-Alex-17 8629c1ca15 feat: Improved support for Anthropic's extended thinking 2026-07-17 17:26:41 -06:00
Dark-Alex-17 078e6e3744 fix: model narration included in history and between tool calls to prevent repetition
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 16:57:51 -06:00
Dark-Alex-17 b908fc20ba docs: Added a docker pulls tracker badge
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 16:24:07 -06:00
Dark-Alex-17 058810137c fix: Don't terminate agent loops early for null tool output
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 16:17:29 -06:00
Dark-Alex-17 c979041161 fix: reduce code duplication by reusing the new concrete_tool_names function in .list tools
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 15:51:01 -06:00
Dark-Alex-17 a606ea552d fix: Agent tools can only be modified via .tool enable/disable using tools in the allowed whitelist in the agent 2026-07-17 15:42:57 -06:00
Dark-Alex-17 39a654a79e fix: re-render agent sessions when entering agents with either pre-configured agent_session or when entering an agent directly into a session 2026-07-17 15:08:19 -06:00
Dark-Alex-17 17d1decce6 feat: Also support GEMINI.md workspace instructions 2026-07-17 15:05:16 -06:00
Dark-Alex-17 a45e66c634 feat: Improved workspace instructions support 2026-07-17 14:52:35 -06:00
Dark-Alex-17 8c885d9a77 feat: also detect .mcp.json configurations at workspace roots 2026-07-17 14:03:08 -06:00
Dark-Alex-17 6dd1e59815 fix: Per RFC 9728, enable dynamic discovery of OAuth endpoints in MCP using path-aware discovery
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 13:28:55 -06:00
Dark-Alex-17 f5085a773a fix: hot-attach to MCP servers that require auth after running .mcp auth <name> 2026-07-17 13:16:25 -06:00
Dark-Alex-17 09afdeaf7c feat: Created new .tool enable/disable and .mcp enable/disable aliases to make REPL usage more egonomic 2026-07-17 12:53:59 -06:00
Dark-Alex-17 0216d84eee feat: Created a new .list <kind> REPL command to make discoveribility easier in the REPL 2026-07-17 11:49:49 -06:00
Dark-Alex-17 320dbf2479 fix: Correctly inherit graph-global model for extractor model if none is defined 2026-07-17 11:42:28 -06:00
Dark-Alex-17 6958e9cba8 feat: Support claude-style hidden workspace MCP configuration files via .mcp.json
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-17 10:46:26 -06:00
Dark-Alex-17 825f9f6bf5 feat: Allow users to customize the workspace-specific configuration directory name so they can use Coyote with other CLI clients like .claude 2026-07-17 10:38:35 -06:00
Dark-Alex-17 863740f916 fix: no cursor timeout when user scrolls away from ongoing streaming output
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-16 16:01:19 -06:00
Dark-Alex-17 304088bf5c tests: Added tests for graph-based RAG
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-16 14:33:52 -06:00
Dark-Alex-17 b7599b8acf build: Added just recipe for building the multi-platform image
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-16 13:33:47 -06:00
Dark-Alex-17 9b3ae761f3 feat: Add reasoning_effort validation for the main configuration file
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-16 13:18:28 -06:00
Dark-Alex-17 0f7877aafc feat: Add validation for reasoning_effort settings to prevent users from specifying erroneous values 2026-07-16 13:12:11 -06:00
Dark-Alex-17 5843a9ac15 docs: Fixed broken links in the code-review and file-reviewer agent READMEs 2026-07-16 13:05:39 -06:00
Dark-Alex-17 4bfaabcb99 docs: Added the reasoning_effort field to example configuration files 2026-07-16 13:05:23 -06:00
Dark-Alex-17 f16f858074 Merge branch 'main' of github.com:Dark-Alex-17/coyote
# Conflicts:
#	src/repl/mod.rs
2026-07-16 12:30:21 -06:00
Dark-Alex-17 e9a8c01dc4 feat: Added support for modifying the reasoning effort of reasoning models 2026-07-16 12:28:04 -06:00
Dark-Alex-17 5bbf1b2d71 test: updated repl tests for undo command 2026-07-15 17:00:01 -06:00
Dark-Alex-17 e9c52566b8 feat: Explicitly Prevent .undo usage in graph agents
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-15 16:27:57 -06:00
Dark-Alex-17 4c7de650c0 feat: Added an .undo command to the REPL to let users have more control over the conversation 2026-07-15 16:23:59 -06:00
Dark-Alex-17 6127d964ee chore: update models.yaml 2026-07-15 16:14:33 -06:00
Dark-Alex-17 8bbbd71fec fix: default to the nano or notepad when a configured editor is not found
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-15 15:32:07 -06:00
Dark-Alex-17 7f89a80f7e fix: When EDITOR, VISUAL, or config.editor is defined, don't verify via which
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-15 15:16:41 -06:00
Dark-Alex-17 19cca06db6 ci: bump the coyote image tag version in the sandbox kit spec
CI / All (ubuntu-latest) (push) Failing after 27s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-15 13:24:51 -06:00
Dark-Alex-17 e8df9f119c feat: Improve sandbox startup time by using the prebuilt Coyote image 2026-07-15 13:24:37 -06:00
Dark-Alex-17 8abe297bfe feat: Make coyote available as a docker image 2026-07-15 13:24:21 -06:00
Dark-Alex-17 4ec6daff30 fix: Added a loop exit condition for the diagnostics skill
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-15 11:51:06 -06:00
Dark-Alex-17 9c1067e544 fix: Added directness clause to the diganose role to improve prompt 2026-07-15 11:14:15 -06:00
Dark-Alex-17 2fe6704fbc fix: fs tools now output better error handling to guide the model more effectively
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-14 12:47:43 -06:00
Dark-Alex-17 dd40892ad5 fix: Make fs_read more tolerant of various arg invocation formats. 2026-07-14 12:31:24 -06:00
Dark-Alex-17 ed86b7bfc3 Merge branch 'main' of github.com:Dark-Alex-17/coyote 2026-07-14 11:31:21 -06:00
Dark-Alex-17 f32d72a3f2 feat: Made fs_patch more flexible for different model preferences of patch formats 2026-07-14 11:31:11 -06:00
Dark-Alex-17 7b00638476 style: removed redundant '&' from functions module 2026-07-13 18:11:03 -06:00
Dark-Alex-17 6733b3600f test: Fixed flaky python AST parser test for macOS
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-13 17:46:34 -06:00
Dark-Alex-17 de6010d525 docs: Organized coyote --help output to be more readable
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-13 17:31:20 -06:00
Dark-Alex-17 9b0e26bade feat: Installed nano into the sandbox so that users can edit config files in the sandbox directly 2026-07-13 17:29:10 -06:00
Dark-Alex-17 ac40043c00 style: Removed outdated implementation plan 2026-07-13 17:25:20 -06:00
Dark-Alex-17 d8eec1d427 docs: Documented the new no_workspace_mcp configuration property that disables workspace-local MCP configurations
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-13 17:14:06 -06:00
Dark-Alex-17 382916c3ee style: Removed redundant '&' from paths module function calls 2026-07-13 17:12:58 -06:00
Dark-Alex-17 bc3cc10a7b feat: Support workspace-local skill definitions and MCP configurations 2026-07-13 17:12:34 -06:00
Dark-Alex-17 b91f738209 docs: updated the configuratino examples for graph-based RAG
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-13 16:55:18 -06:00
Dark-Alex-17 4f0dae9b49 feat: fully functional graph-based RAG
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-13 16:50:07 -06:00
Dark-Alex-17 deb673ebc9 fmt: applied some formatting changes 2026-07-13 16:07:19 -06:00
Dark-Alex-17 7fc06ad9bc feat: Implemented graph-based RAG 2026-07-08 21:20:50 -06:00
Dark-Alex-17 e814b9f62d fix: todo functions are injected properly to roles when roles have auto_continue: true and the REPL is started directly into the role
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-08 15:45:50 -06:00
Dark-Alex-17 209fbc9e41 feat: Added a --dangerously-skip-permissions flag to skip permission prompts for tool invocations
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-08 15:17:21 -06:00
Dark-Alex-17 5eb1daf18d feat: Remove the temperature hyperparameter from the diagnose role
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-08 14:59:45 -06:00
Dark-Alex-17 b8990fdfc2 feat: Added a new oauth.redirectHost field to make it possible to further extend MCP support
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-07 15:35:04 -06:00
Dark-Alex-17 7673799d83 feat: Updated the REPL mcp auth path to use the prettified error messaging
CI / All (ubuntu-latest) (push) Failing after 23s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-07 15:18:56 -06:00
Dark-Alex-17 ce212fe660 feat: Improved error messaging for failed MCP starts because of auth issues
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-07 15:09:50 -06:00
Dark-Alex-17 f855a45493 fix: updated the redirect URI for OAuth MCP to use localhost since that's what is whitelisted, not 127.0.0.1
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-07 14:44:35 -06:00
Dark-Alex-17 5be4f45671 feat: Added support for specifying the oauth port and client ID in MCP server configs
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-07 14:31:51 -06:00
Dark-Alex-17 84ce094677 fix: allow MCP OAuth refresh_token to be absent from initial token exchanges
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-07 14:15:39 -06:00
Dark-Alex-17 fa7eadd08a feat: Implemented OAuth support for OpenAI models via Codex endpoints
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-06 11:20:32 -06:00
Dark-Alex-17 af91b89cff feat: merge MCP config when installing bundled mcp config 2026-07-06 09:57:17 -06:00
Dark-Alex-17 d4a6a2fb34 build: Installed ast_grep in the sandbox kit definition
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-04 13:14:22 -06:00
Dark-Alex-17 8f667886c8 docs: Updated the README to mention the installation of ast-grep 2026-07-04 13:14:08 -06:00
Dark-Alex-17 898bac3c69 docs: added the ast_grep tool to the config.example.yaml 2026-07-04 13:13:16 -06:00
Dark-Alex-17 fc0b2ada7e feat: Implemented durable state for sisyphus 2026-07-04 13:02:50 -06:00
Dark-Alex-17 09cdb40420 feat: Installed ast-grep for the explore agent to use for better code exploration 2026-07-04 12:59:05 -06:00
Dark-Alex-17 9d2e936e7f feat: Created the step-runner graph agent for more deterministic coding workflows to produce even more reliable and higher-quality results 2026-07-04 12:50:37 -06:00
Dark-Alex-17 159afbbc06 feat: Improved oracle and sisyphus agents with skill integrations for the new skills 2026-07-04 12:34:09 -06:00
Dark-Alex-17 428d544277 feat: Created new sisyphus family skills to improve performance 2026-07-04 12:28:42 -06:00
Dark-Alex-17 531bdfab7f feat: Created new diagnostic role and skill for use in other contexts 2026-07-04 12:28:24 -06:00
Dark-Alex-17 08f6ea5e6c feat: Added new memory functions for deleting and renaming memory files, as well as new lints for memory expiration dates and staleness of memories to improve the memory system
CI / All (ubuntu-latest) (push) Failing after 28s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-03 22:30:08 -06:00
Dark-Alex-17 ede0f75a89 feat: Created a new iwe skill and installed the iwe MCP server for utilizing large knowledgebases 2026-07-03 22:04:16 -06:00
Dark-Alex-17 2ec2aec4c0 style: updated the previous conversation marker a tad
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 16:49:38 -06:00
Dark-Alex-17 c2cb4ac433 feat: Session-specific, file-backed history in the REPL
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 16:44:55 -06:00
Dark-Alex-17 605a9170b0 feat: Replay session output when a user re-enters a session so all output can be seen again 2026-07-02 16:35:10 -06:00
Dark-Alex-17 385bd3eda2 fix: Overrode the default JSON content-type for MCP OAuth so its properly application/x-www-form-urlencoded
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 15:53:29 -06:00
Dark-Alex-17 6c3d96ac83 feat: Added confirmation message after MCP Oauth succeeds when invoked from --auth-mcp
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 15:22:22 -06:00
Dark-Alex-17 aa1fe7f7aa fmt: applied formatting 2026-07-02 15:22:00 -06:00
Dark-Alex-17 5e50828108 fix: typo in mcp file name 2026-07-02 15:20:57 -06:00
Dark-Alex-17 693e2d9672 feat: Created the --auth-mcp CLI flag to let users auth with remote MCP servers without needing to be in the REPL
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 14:51:52 -06:00
Dark-Alex-17 16f324cefc feat: add OAuth authentication support for remote MCP servers 2026-07-02 14:43:24 -06:00
Dark-Alex-17 cc50d39ab4 fix: Added uvx wrapper for macos-based sandboxes
CI / All (ubuntu-latest) (push) Failing after 28s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 12:57:12 -06:00
Dark-Alex-17 fc23b532d9 feat: Added mixin for sisyphus so the ddg MCP server can search arbitrary domains 2026-07-02 12:56:18 -06:00
Dark-Alex-17 c2d4240138 perf: updated the memory injection warning so it only logs once, rather than after each keystroke
CI / All (ubuntu-latest) (push) Failing after 27s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 12:47:57 -06:00
Dark-Alex-17 cd1b043b1e feat: added improved error messaging on MCP server initialization
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 11:42:12 -06:00
Dark-Alex-17 81b4f6a76e feat: prefer musl versions for linux when running --update/.update
CI / All (ubuntu-latest) (push) Failing after 27s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 11:31:34 -06:00
github-actions[bot] d48b11dcfa chore: bump Cargo.toml to 0.7.4
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-02 01:06:00 +00:00
github-actions[bot] 86dd922d2c bump: version 0.7.3 → 0.7.4 [skip ci] 2026-07-02 01:05:42 +00:00
Dark-Alex-17 9ec20d74a4 chore: updated models.yaml
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-01 19:04:55 -06:00
Dark-Alex-17 c78cdef5ae fix: Added back in --kit specification for the running of the sbx
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-01 18:52:34 -06:00
Dark-Alex-17 3df590f276 fix: sbx isn't copying base files in their respective directories
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-01 18:44:07 -06:00
Dark-Alex-17 91300c16fe fix: Update deprecated sbx kit config 2026-07-01 17:52:04 -06:00
Dark-Alex-17 52356ead6c fix: Properly chown the coyote config recursively and password file in the sbx
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-07-01 17:12:42 -06:00
Dark-Alex-17 ad9fc524d4 feat: Pin specific usql version to sbx kit 2026-07-01 17:11:27 -06:00
Dark-Alex-17 af50909a89 feat: recursively take ownership over the copied in coyote config for the sbx 2026-07-01 16:54:57 -06:00
Dark-Alex-17 318d9ba1cd feat: explicitly specify the COYOTE_CONFIG_DIR in the sbx kit 2026-07-01 16:54:42 -06:00
Dark-Alex-17 45d709f28e Merge branch 'main' of github.com:Dark-Alex-17/coyote
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-30 14:55:08 -06:00
Dark-Alex-17 9cd074cb9b build: fixed coyote install scripts 2026-06-30 14:54:59 -06:00
Dark-Alex-17 93eec45473 docs: fixed coyote install script URLs 2026-06-30 14:43:00 -06:00
Dark-Alex-17 e585e0b049 feat: --tail-logs can track log rollovers and incoporates a sleep timer to minimize idle CPU cycles
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-25 14:01:38 -06:00
Dark-Alex-17 13bfaf9aca feat: Added support for log rolling so log files don't just blow up over time 2026-06-25 13:57:15 -06:00
github-actions[bot] 040dad05d2 chore: bump Cargo.toml to 0.7.3
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-24 18:20:20 +00:00
github-actions[bot] 1ba38860f2 bump: version 0.7.2 → 0.7.3 [skip ci] 2026-06-24 18:20:16 +00:00
Dark-Alex-17 84ec5fe7b8 fix: apply bootstrapping of functions at startup to fix edge case
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-24 12:13:55 -06:00
github-actions[bot] 1684788fe6 bump: version 0.7.1 → 0.7.2 [skip ci] 2026-06-19 18:51:49 +00:00
Dark-Alex-17 4b7e242998 fix: usql version upgrade
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-19 12:45:41 -06:00
github-actions[bot] f69aba2dd8 chore: bump Cargo.toml to 0.7.1
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-19 18:04:58 +00:00
github-actions[bot] c3487ecd0e bump: version 0.7.0 → 0.7.1 [skip ci] 2026-06-19 18:04:56 +00:00
Dark-Alex-17 db75391fb6 Merge branch 'main' of github.com:Dark-Alex-17/coyote
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-19 11:44:28 -06:00
Dark-Alex-17 e3815af69b fix: sbx mixins must be passed in directories, not as files and the files must be named spec.yaml per new sbx version
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-19 11:44:16 -06:00
github-actions[bot] 66a485f924 chore: bump Cargo.toml to 0.7.0 2026-06-18 22:40:24 +00:00
github-actions[bot] 49d7204f89 bump: version 0.6.0 → 0.7.0 [skip ci] 2026-06-18 22:40:19 +00:00
Dark-Alex-17 bbcae1fc2b feat: added configurable cache path via the COYOTE_CACHE_PATH environment variable
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-18 16:30:24 -06:00
Dark-Alex-17 3ff27a7935 feat: added a memory option to .set tab completions
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-18 15:50:23 -06:00
Dark-Alex-17 373d80121a lint: Fixed linter complaints in paths module
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-18 14:32:07 -06:00
Dark-Alex-17 3299a4699e refactor: Migrated the .skills command completion to use StateFlags and updated the help messages 2026-06-18 14:30:55 -06:00
Dark-Alex-17 d4dbda1e89 fix: rebuild the tool scope after dynamically updating the skills_enabled value in the REPL 2026-06-18 13:01:38 -06:00
Dark-Alex-17 e77fa6ef42 feat: Added a diagnostic .info tools subcommand to make it easier to see what tools are enabled in all contexts 2026-06-18 13:01:11 -06:00
Dark-Alex-17 241dda24f0 feat: Added additional info outputs for enabled skills and sbx directories 2026-06-18 11:58:29 -06:00
Dark-Alex-17 e5668e4495 docs: Added sandboxes to the README 2026-06-18 11:57:58 -06:00
Dark-Alex-17 4a01e9a66c fmt: applied formatting 2026-06-18 11:29:03 -06:00
Dark-Alex-17 530000bc2f fix: properly resolve Windows-based local vault password file locations and bootstrap them into the sandbox when possible 2026-06-18 11:28:54 -06:00
Dark-Alex-17 f2e8f3ab59 fix: auto-translation of user-prefixed Mac and Linux paths for the vault password file when running inside a sandbox 2026-06-18 10:53:38 -06:00
Dark-Alex-17 2f33b6631e feat: directly execute shell commands from within the REPL 2026-06-18 08:19:01 -06:00
Dark-Alex-17 8c288195a0 feat: created mixin kit for built-in functions and MCP servers 2026-06-17 15:10:40 -06:00
Dark-Alex-17 e6a5e67a8e feat: Added sbx mixins for the secrets providers so users can also bootstrap those as well. 2026-06-17 14:57:35 -06:00
Dark-Alex-17 6ae474c79e feat: added support for loading sbx mixins that are dynamically discovered in the users workspace and config directory 2026-06-17 14:39:32 -06:00
Dark-Alex-17 8e0b07c9fb docs: Updated the --fresh command help message 2026-06-17 14:20:38 -06:00
Dark-Alex-17 69589bd5e5 feat: Added a --fresh flag to let users create a truly bare bones sandbox without bootstrapping their config 2026-06-17 14:20:17 -06:00
Dark-Alex-17 587df087ed feat: initial built-in sandboxing support powered by Docker sbx 2026-06-17 14:11:04 -06:00
Dark-Alex-17 ee100eef96 fix: don't attempt to auto complete .vault list in the REPL; that's the end of the command 2026-06-17 12:50:04 -06:00
Dark-Alex-17 14969e35fa fix: buffer tool stdout as well as stderr so that any tools that error to stdout are captured and included in the response to the model, enabling the model to see what went wrong and to reason about how to fix it.
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-16 15:07:55 -06:00
Dark-Alex-17 b927e2a200 fix: auto-bootstrapped memory was accidentally putting the MEMORY.md directly in the repo root rather than .coyote/memory/MEMORY.md
CI / All (ubuntu-latest) (push) Failing after 23s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-15 15:05:51 -06:00
Dark-Alex-17 6ce69ee989 fix: improved the fs_patch script description and added improved error handling to it. 2026-06-15 15:05:18 -06:00
Dark-Alex-17 dc6d736df3 build: pinned aws-smithy-types and time to fix yesterday's release of aws-smithy-types issues 2026-06-12 17:33:49 -06:00
Dark-Alex-17 2a79616f8b feat: Added the ability to auto-bootstrap workspace memory when in git repos 2026-06-11 16:03:00 -06:00
Dark-Alex-17 eb6a02f947 test: fixed broken memory test after updating index format 2026-06-11 20:28:33 -06:00
Dark-Alex-17 00939e4634 feat: Added explicit guardrail handling for pending agents 2026-06-11 20:20:14 -06:00
Dark-Alex-17 6ebd32d47c fix: added in forgotten require_max_tokens to the fable model 2026-06-11 16:11:22 -06:00
Dark-Alex-17 73c4449e7f feat: auto-append memory to memory index and don't necessarily require the LLM to remember to do it after a write 2026-06-10 21:31:37 -06:00
Dark-Alex-17 7143b50d98 fix: append memory functions to non-graph based agents on init 2026-06-10 21:07:56 -06:00
Dark-Alex-17 de38e663a0 docs: Added some docs for the memory system and the --init-memory flag 2026-06-10 20:26:31 -06:00
Dark-Alex-17 10de6025b5 feat: Added an --init-memory [global|workspace] flag to easily and quickly enable memory 2026-06-10 20:26:17 -06:00
Dark-Alex-17 0d2292bff6 feat: added memory global configuration settings to the output of --info and .info 2026-06-10 20:10:45 -06:00
Dark-Alex-17 eb38ca0bbb docs: updated example configurations to include settings for the new memory system 2026-06-10 20:06:17 -06:00
Dark-Alex-17 1931331163 fix: when auto_continue is disabled via the .set auto_continue false command, it should strip the todo functions from the list of functions 2026-06-10 19:31:19 -06:00
Dark-Alex-17 218750cc1e feat: added .set memory REPL commands to control memory injection and applied formatting 2026-06-10 19:24:08 -06:00
Dark-Alex-17 a10b23dbc1 test: added more unit tests for the memory system 2026-06-10 18:44:32 -06:00
Dark-Alex-17 19d2340489 feat: Create the built-in memory management tools 2026-06-10 18:35:59 -06:00
Dark-Alex-17 4ece3d3df1 feat: Append the memory system prompts (readonly or r/w) to the system prompt when applicable 2026-06-10 18:19:37 -06:00
Dark-Alex-17 6d5cbfa56d feat: Created the --no-memory CLI flag to disable memory for this invocation 2026-06-10 17:53:40 -06:00
Dark-Alex-17 7e097e0465 feat: Added the memory configuration properties and storage to the main app config, roles, sessions, and agents. 2026-06-10 17:50:28 -06:00
Dark-Alex-17 b2d70a3fd3 feat: initial scaffolding of a memory system 2026-06-10 17:24:45 -06:00
Dark-Alex-17 3183fedca9 chore: updated models.yaml to include claude Fable 5 2026-06-10 17:18:58 -06:00
Dark-Alex-17 33c6f2c4e3 fix: use rawPredict for non-streaming Claude requests
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-09 23:05:31 -06:00
Dark-Alex-17 bca25404ab docs: migrated location of skill_instructions examples in example configs
CI / All (ubuntu-latest) (push) Failing after 24s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-06-05 15:34:25 -06:00
github-actions[bot] 161fa2d983 chore: bump Cargo.toml to 0.6.0 2026-06-05 21:30:01 +00:00
github-actions[bot] 0e93775491 bump: version 0.5.0 → 0.6.0 [skip ci] 2026-06-05 21:29:49 +00:00
Dark-Alex-17 c00c4ff84a test: added a few additional tests to the request_context surrounding the skills system 2026-06-05 15:24:51 -06:00
Dark-Alex-17 46685cb641 fix: disable skills for specific built-in roles 2026-06-05 15:11:22 -06:00
Dark-Alex-17 165d0d113d feat: added skill hint prompt injection and configuration 2026-06-05 14:48:54 -06:00
Dark-Alex-17 70dc7c9680 fix: redirect stderr into user's /dev/tty for guards 2026-06-05 12:46:52 -06:00
Dark-Alex-17 4eac536327 docs: updated the graph.example.yaml 2026-06-05 11:53:19 -06:00
Alex Clarke 8e0fa79ff3 Merge pull request #13 from Dark-Alex-17/skills
Implement support for skills and refactored secrets providers
2026-06-05 11:43:15 -06:00
134 changed files with 19454 additions and 1289 deletions
+77 -15
View File
@@ -8,9 +8,9 @@ on:
workflow_dispatch: workflow_dispatch:
inputs: inputs:
bump_type: bump_type:
description: "Specify the type of version bump" description: 'Specify the type of version bump'
required: true required: true
default: "patch" default: 'patch'
type: choice type: choice
options: options:
- patch - patch
@@ -46,7 +46,7 @@ jobs:
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v4 uses: actions/setup-python@v4
with: with:
python-version: "3.10" python-version: '3.10'
- name: Install Commitizen - name: Install Commitizen
run: | run: |
@@ -108,17 +108,19 @@ jobs:
cargo update || true cargo update || true
sed -i "s|image: 'darkalex17/coyote:v[^']*'|image: 'darkalex17/coyote:v${VERSION}'|" assets/sbx-kit/spec.yaml
# Git config that helps in Act # Git config that helps in Act
git config user.name "github-actions[bot]" git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com" git config user.email "github-actions[bot]@users.noreply.github.com"
git config --global --add safe.directory "$GITHUB_WORKSPACE" git config --global --add safe.directory "$GITHUB_WORKSPACE"
git status --porcelain git status --porcelain
git diff --name-only -- Cargo.toml Cargo.lock || true git diff --name-only -- Cargo.toml Cargo.lock assets/sbx-kit/spec.yaml || true
if ! git diff --quiet -- Cargo.toml Cargo.lock; then if ! git diff --quiet -- Cargo.toml Cargo.lock assets/sbx-kit/spec.yaml; then
git add -u -- Cargo.toml Cargo.lock git add -u -- Cargo.toml Cargo.lock assets/sbx-kit/spec.yaml
git commit -m "chore: bump Cargo.toml to $VERSION" git commit -m "chore: bump Cargo.toml and sandbox image to $VERSION"
else else
echo "No changes to commit (already at $VERSION)" echo "No changes to commit (already at $VERSION)"
fi fi
@@ -163,28 +165,28 @@ jobs:
- target: aarch64-unknown-linux-musl - target: aarch64-unknown-linux-musl
os: ubuntu-latest os: ubuntu-latest
use-cross: true use-cross: true
cargo-flags: "" cargo-flags: ''
- target: aarch64-apple-darwin - target: aarch64-apple-darwin
os: macos-latest os: macos-latest
use-cross: true use-cross: true
cargo-flags: "" cargo-flags: ''
- target: aarch64-pc-windows-msvc - target: aarch64-pc-windows-msvc
os: windows-latest os: windows-latest
use-cross: true use-cross: true
cargo-flags: "" cargo-flags: ''
- target: x86_64-apple-darwin - target: x86_64-apple-darwin
os: macos-latest os: macos-latest
cargo-flags: "" cargo-flags: ''
- target: x86_64-pc-windows-msvc - target: x86_64-pc-windows-msvc
os: windows-latest os: windows-latest
cargo-flags: "" cargo-flags: ''
- target: x86_64-unknown-linux-musl - target: x86_64-unknown-linux-musl
os: ubuntu-latest os: ubuntu-latest
use-cross: true use-cross: true
cargo-flags: "" cargo-flags: ''
- target: x86_64-unknown-linux-gnu - target: x86_64-unknown-linux-gnu
os: ubuntu-latest os: ubuntu-latest
cargo-flags: "" cargo-flags: ''
steps: steps:
- name: Check if actor is repository owner - name: Check if actor is repository owner
@@ -338,7 +340,7 @@ jobs:
${{ steps.package.outputs.archive }} ${{ steps.package.outputs.archive }}
${{ steps.package.outputs.sha }} ${{ steps.package.outputs.sha }}
tag_name: v${{ env.RELEASE_VERSION }} tag_name: v${{ env.RELEASE_VERSION }}
name: "v${{ env.RELEASE_VERSION }}" name: 'v${{ env.RELEASE_VERSION }}'
body_path: artifacts/changelog.md body_path: artifacts/changelog.md
prerelease: false prerelease: false
@@ -456,3 +458,63 @@ jobs:
if: env.ACT != 'true' if: env.ACT != 'true'
with: with:
registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }} registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }}
publish-sandbox-image:
needs: [publish-github-release]
name: Publish Sandbox Docker Image
runs-on: ubuntu-latest
steps:
- name: Check if actor is repository owner
if: ${{ github.actor != github.repository_owner && env.ACT != 'true' }}
run: |
echo "You are not authorized to run this workflow."
exit 1
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Ensure repository is up-to-date
if: env.ACT != 'true'
run: |
git fetch --all
git pull
- name: Get release artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: Set version variable
run: |
version="$(cat artifacts/release-version)"
echo "version=$version" >> $GITHUB_ENV
- name: Validate release environment variables
run: |
echo "Release version: ${{ env.version }}"
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
if: env.ACT != 'true'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Push to Docker Hub
uses: docker/build-push-action@v5
with:
context: .
file: Dockerfile
platforms: linux/amd64,linux/arm64
push: ${{ env.ACT != 'true' }}
tags: darkalex17/coyote:latest, darkalex17/coyote:${{ env.version }}
build-args: COYOTE_VERSION=${{ env.version }}
+160
View File
@@ -1,3 +1,163 @@
## v0.7.4 (2026-07-02)
### Feat
- Pin specific usql version to sbx kit
- recursively take ownership over the copied in coyote config for the sbx
- explicitly specify the COYOTE_CONFIG_DIR in the sbx kit
- --tail-logs can track log rollovers and incoporates a sleep timer to minimize idle CPU cycles
- Added support for log rolling so log files don't just blow up over time
### Fix
- Added back in --kit specification for the running of the sbx
- sbx isn't copying base files in their respective directories
- Update deprecated sbx kit config
- Properly chown the coyote config recursively and password file in the sbx
## v0.7.3 (2026-06-24)
### Fix
- apply bootstrapping of functions at startup to fix edge case
## v0.7.2 (2026-06-19)
### Fix
- usql version upgrade
## v0.7.1 (2026-06-19)
### Fix
- sbx mixins must be passed in directories, not as files and the files must be named spec.yaml per new sbx version
## v0.7.0 (2026-06-18)
### Feat
- added configurable cache path via the COYOTE_CACHE_PATH environment variable
- added a memory option to .set tab completions
- Added a diagnostic .info tools subcommand to make it easier to see what tools are enabled in all contexts
- Added additional info outputs for enabled skills and sbx directories
- directly execute shell commands from within the REPL
- created mixin kit for built-in functions and MCP servers
- Added sbx mixins for the secrets providers so users can also bootstrap those as well.
- added support for loading sbx mixins that are dynamically discovered in the users workspace and config directory
- Added a --fresh flag to let users create a truly bare bones sandbox without bootstrapping their config
- initial built-in sandboxing support powered by Docker sbx
- Added the ability to auto-bootstrap workspace memory when in git repos
- Added explicit guardrail handling for pending agents
- auto-append memory to memory index and don't necessarily require the LLM to remember to do it after a write
- Added an --init-memory [global|workspace] flag to easily and quickly enable memory
- added memory global configuration settings to the output of --info and .info
- added .set memory REPL commands to control memory injection and applied formatting
- Create the built-in memory management tools
- Append the memory system prompts (readonly or r/w) to the system prompt when applicable
- Created the --no-memory CLI flag to disable memory for this invocation
- Added the memory configuration properties and storage to the main app config, roles, sessions, and agents.
- initial scaffolding of a memory system
### Fix
- rebuild the tool scope after dynamically updating the skills_enabled value in the REPL
- properly resolve Windows-based local vault password file locations and bootstrap them into the sandbox when possible
- auto-translation of user-prefixed Mac and Linux paths for the vault password file when running inside a sandbox
- don't attempt to auto complete .vault list in the REPL; that's the end of the command
- buffer tool stdout as well as stderr so that any tools that error to stdout are captured and included in the response to the model, enabling the model to see what went wrong and to reason about how to fix it.
- auto-bootstrapped memory was accidentally putting the MEMORY.md directly in the repo root rather than .coyote/memory/MEMORY.md
- improved the fs_patch script description and added improved error handling to it.
- added in forgotten require_max_tokens to the fable model
- append memory functions to non-graph based agents on init
- when auto_continue is disabled via the .set auto_continue false command, it should strip the todo functions from the list of functions
- use rawPredict for non-streaming Claude requests
### Refactor
- Migrated the .skills command completion to use StateFlags and updated the help messages
## v0.6.0 (2026-06-05)
### Feat
- added skill hint prompt injection and configuration
- Fallthrough on missing secrets during mcp.json merging
- validate visible_skills field at config load time
- implemented reflexion (sorta) in sisyphus for significant code changes to delegate to the code-reviewer agent
- improved explore agent
- removed conditional fallback of LLM_*_RAW_JSON from built-ins
- updated enabled_skills handling to support both list and comma-separated strings
- added new REPL set commands for toggling skills and changing what skills are enabled
- upgraded to the latest version of mcp-remote
- fs_grep now works with both files and directories
- improved code reviewer agents with skills
- added round trip validation for vault providers to ensure permissions and authentication
- created new first-time run wizard for secrets provider
- vault_password_file or nothing at all is shorthand for just using the local gman provider for secret management
- refactored gman usage to be generic and work with various vault providers and use the SupportedProvider enum directly for configurations
- created initial parity gman generalization for vault provider
- Refactored the sisyhpus agent system to utilize the new skills system to improve performance and reliability
- llm graph nodes support skills
- updated sisyphus and coder tools
- removed potentially confusing tab completions for .skill
- .edit skill <name> support from within the REPL
- Added skills_dir to the info output of Coyote
- Created a few auto built-in skills
- Added support for auto_unload skills during chat
- cleaned up skill implementation
- support multiple skill flags to load multiple skills at CLI startup
- Modified --skill CLI to allow users to specify skills to start the REPL or CLI with.
- added CLI --skill flag for modifying skills easily
- REPL integration with skills
- dynamic loading/unloading of skill tools and MCP servers whenever load_skill/unload_skill are invoked
- created built-in functions for listing, loading, and unloading skills
- implemented the skills policy to track available skills per context
- added remote install and install support for skills
- created the skill registry
- decided to make skills persist to disk like agents and not in-memory like built-in roles
- scaffold skill module
### Fix
- disable skills for specific built-in roles
- redirect stderr into user's /dev/tty for guards
- azure doesn't support underscores in key vault
- accidental regression on enabled_skills being empty = all
- greedy secrets regex caused multiple secrets on one line to fail
- add agent context check to skill visibility validation
- enforced global visible_skills in llm node validation and improved skill loading error handling across the project
- restore agent skill policy on error during effective policy calculation
- apply the same validation for skill filenames on list_skills as happens everywhere else
- the vault's init_bare should try to load the provisioned secret_provider from the config file without also interpolating any of the rest of the configuration file. It should only fail if the user has not yet created a configuration file; i.e. done a first-time run.
- the vault roundtrip test used characters that are unsupported by some major secrets providers
- fixed tool filtering logic for skills and user functions in agents
- privilege leak when unloading skills and leaving tool scope untouched
- When bootstrapping an app config to interpolate secrets, clone the secrets provider configuration as well so config secrets stored in remote vaults can be used properly
- forgot to move back up the vault probe value error to be before the delete
- don't silently fail on skill role composition extraction in llm nodes
- set -euo pipefail for the temp script in execute_command.sh tool
- added forgotten skill name validation to has_skill to prevent side-channel attacks
- use unique values for the secrets round trip verification
- stop interpolating a line if any errors occur
- added path validation for skill names
- effective_policy unconditionally overwrote skill values for role-like structs
- updated execute_command to not mangle heredocs and also added explicit instructions to the coder and sisyphus agents to use fs_write and fs_patch over execute_command when writing files
- llm nodes accidentally skipped skill_registry::effective_role because I was passing an inline role instead
- updated temperature values for all agents and roles
- added back in require_max_tokens for new Claude models
- skill support also requires function calling to be enabled
- non_tty tests break on some TTY terminals
- skill loading on agents
- forgot to bootstrap skills on REPL startup
- remove now deprecated .skill edit command
### Refactor
- removed redundant skill name validation from has_skill function
- support both CSV and list formats for enabled_tools
- Support both CSV and list formats for enabled_mcp_servers
## v0.5.0 (2026-05-27) ## v0.5.0 (2026-05-27)
### Feat ### Feat
Generated
+421 -441
View File
File diff suppressed because it is too large Load Diff
+7 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "coyote-ai" name = "coyote-ai"
version = "0.5.0" version = "0.7.4"
edition = "2024" edition = "2024"
authors = ["Alex Clarke <alex.j.tusa@gmail.com>"] authors = ["Alex Clarke <alex.j.tusa@gmail.com>"]
description = "An all-in-one, batteries included LLM CLI Tool" description = "An all-in-one, batteries included LLM CLI Tool"
@@ -17,6 +17,7 @@ exclude = [".github", "CONTRIBUTING.md"]
anyhow = "1.0.69" anyhow = "1.0.69"
bytes = "1.4.0" bytes = "1.4.0"
clap = { version = "4.5.40", features = ["cargo", "derive", "wrap_help"] } clap = { version = "4.5.40", features = ["cargo", "derive", "wrap_help"] }
comfy-table = { version = "7.2.2", features = ["custom_styling"] }
dirs = "6.0.0" dirs = "6.0.0"
dunce = "1.0.5" dunce = "1.0.5"
futures-util = "0.3.29" futures-util = "0.3.29"
@@ -49,7 +50,7 @@ textwrap = "0.16.0"
ansi_colours = "1.2.2" ansi_colours = "1.2.2"
eventsource-stream = "0.2.3" eventsource-stream = "0.2.3"
log = "0.4.28" log = "0.4.28"
log4rs = { version = "1.4.0", features = ["file_appender"] } log4rs = { version = "1.4.0", features = ["file_appender", "rolling_file_appender", "compound_policy", "fixed_window_roller", "size_trigger"] }
shell-words = "1.1.0" shell-words = "1.1.0"
sha2 = "0.10.8" sha2 = "0.10.8"
unicode-width = "0.2.0" unicode-width = "0.2.0"
@@ -58,6 +59,8 @@ http = "1.1.0"
indexmap = { version = "2.2.6", features = ["serde"] } indexmap = { version = "2.2.6", features = ["serde"] }
hmac = "0.12.1" hmac = "0.12.1"
aws-smithy-eventstream = "0.60.4" aws-smithy-eventstream = "0.60.4"
aws-smithy-types = "=1.4.9"
time = "=0.3.47"
urlencoding = "2.1.3" urlencoding = "2.1.3"
json-patch = { version = "4.0.0", default-features = false } json-patch = { version = "4.0.0", default-features = false }
bitflags = "2.5.0" bitflags = "2.5.0"
@@ -72,6 +75,7 @@ html_to_markdown = "0.1.0"
rust-embed = "8.5.0" rust-embed = "8.5.0"
os_info = { version = "3.8.2", default-features = false } os_info = { version = "3.8.2", default-features = false }
bm25 = { version = "2.0.1", features = ["parallelism"] } bm25 = { version = "2.0.1", features = ["parallelism"] }
petgraph = { version = "0.7", features = ["serde-1"] }
which = "8.0.0" which = "8.0.0"
fuzzy-matcher = "0.3.7" fuzzy-matcher = "0.3.7"
terminal-colorsaurus = "0.4.8" terminal-colorsaurus = "0.4.8"
@@ -104,6 +108,7 @@ self_update = { version = "0.44", default-features = false, features = [
"archive-zip", "archive-zip",
"compression-zip-deflate", "compression-zip-deflate",
] } ] }
qrcode = "0.14"
[dependencies.reqwest] [dependencies.reqwest]
version = "0.13.3" version = "0.13.3"
+72
View File
@@ -0,0 +1,72 @@
ARG COYOTE_VERSION
FROM docker/sandbox-templates:shell-docker
ARG COYOTE_VERSION
ARG TARGETARCH
ENV PATH="/home/agent/.cargo/bin:/home/agent/.local/bin:${PATH}"
USER root
RUN apt-get update && \
apt-get install -y --no-install-recommends \
jq curl git \
build-essential pkg-config \
cmake \
clang libclang-dev \
musl-tools \
libssl-dev \
pandoc \
bzip2 \
nano && \
rm -rf /var/lib/apt/lists/*
RUN set -euo pipefail; \
USQL_VERSION=0.21.4; \
case "${TARGETARCH}" in \
amd64) USQL_ARCH=amd64 ;; \
arm64) USQL_ARCH=arm64 ;; \
*) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
esac; \
TMPDIR=$(mktemp -d); \
curl -fsSL --retry 3 \
"https://github.com/xo/usql/releases/download/v${USQL_VERSION}/usql_static-${USQL_VERSION}-linux-${USQL_ARCH}.tar.bz2" \
-o "$TMPDIR/usql.tar.bz2"; \
tar -xjf "$TMPDIR/usql.tar.bz2" -C "$TMPDIR"; \
install -m 0755 "$TMPDIR/usql_static" /usr/local/bin/usql; \
rm -rf "$TMPDIR"
USER 1000
RUN curl -LsSf https://astral.sh/uv/install.sh | sh && \
printf '#!/bin/sh\nexec uv tool run "$@"\n' > "$HOME/.local/bin/uvx" && \
chmod +x "$HOME/.local/bin/uvx"
RUN mkdir -p /usr/local/share/npm-global/lib
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --default-toolchain stable --profile minimal && \
. "$HOME/.cargo/env" && \
cargo install --locked iwec && \
cargo install --locked ast-grep
USER root
RUN set -euo pipefail; \
case "${TARGETARCH}" in \
amd64) MUSL_TARGET=x86_64-unknown-linux-musl ;; \
arm64) MUSL_TARGET=aarch64-unknown-linux-musl ;; \
*) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
esac; \
TMPDIR=$(mktemp -d); \
curl -fsSL --retry 3 \
"https://github.com/Dark-Alex-17/coyote/releases/download/v${COYOTE_VERSION}/coyote-${MUSL_TARGET}.tar.gz" \
-o "$TMPDIR/coyote.tar.gz"; \
tar -xzf "$TMPDIR/coyote.tar.gz" -C "$TMPDIR"; \
install -m 0755 "$TMPDIR/coyote" /home/agent/.cargo/bin/coyote; \
chown 1000:1000 /home/agent/.cargo/bin/coyote; \
rm -rf "$TMPDIR"
USER 1000
ENTRYPOINT ["coyote"]
+40 -2
View File
@@ -5,6 +5,7 @@
![Release](https://img.shields.io/github/v/release/Dark-Alex-17/coyote?color=%23c694ff) ![Release](https://img.shields.io/github/v/release/Dark-Alex-17/coyote?color=%23c694ff)
![Crate.io downloads](https://img.shields.io/crates/d/coyote-ai?label=Crate%20downloads) ![Crate.io downloads](https://img.shields.io/crates/d/coyote-ai?label=Crate%20downloads)
[![GitHub Downloads](https://img.shields.io/github/downloads/Dark-Alex-17/coyote/total.svg?label=GitHub%20downloads)](https://github.com/Dark-Alex-17/coyote/releases) [![GitHub Downloads](https://img.shields.io/github/downloads/Dark-Alex-17/coyote/total.svg?label=GitHub%20downloads)](https://github.com/Dark-Alex-17/coyote/releases)
![Docker pulls](https://img.shields.io/docker/pulls/darkalex17/coyote?label=Docker%20downloads)
Coyote is an all-in-one, batteries-included, LLM CLI tool featuring Shell Assistant, CLI & REPL Mode, RAG, AI Tools & Coyote is an all-in-one, batteries-included, LLM CLI tool featuring Shell Assistant, CLI & REPL Mode, RAG, AI Tools &
Agents, and More. Agents, and More.
@@ -25,6 +26,7 @@ Coming from [AIChat](https://github.com/sigoden/aichat)? Follow the [migration g
* [REPL](https://github.com/Dark-Alex-17/coyote/wiki/REPL): Interactive Read-Eval-Print Loop for conversational interactions with LLMs and Coyote. * [REPL](https://github.com/Dark-Alex-17/coyote/wiki/REPL): Interactive Read-Eval-Print Loop for conversational interactions with LLMs and Coyote.
* [Custom REPL Prompt](https://github.com/Dark-Alex-17/coyote/wiki/REPL-Prompt): Customize the REPL prompt to provide useful contextual information. * [Custom REPL Prompt](https://github.com/Dark-Alex-17/coyote/wiki/REPL-Prompt): Customize the REPL prompt to provide useful contextual information.
* [Vault](https://github.com/Dark-Alex-17/coyote/wiki/Vault): Securely store and manage sensitive information such as API keys and credentials. * [Vault](https://github.com/Dark-Alex-17/coyote/wiki/Vault): Securely store and manage sensitive information such as API keys and credentials.
* [Sandboxes](https://github.com/Dark-Alex-17/coyote/wiki/Sandboxes): Launch Coyote inside an isolated [Docker Sandbox](https://docs.docker.com/ai/sandboxes/) with one command. Host config and vault credentials are projected in automatically; everything else is delegated to the `sbx` CLI.
* [Shell Integrations](https://github.com/Dark-Alex-17/coyote/wiki/Shell-Integrations): Seamlessly integrate Coyote with your shell environment for enhanced command-line assistance. * [Shell Integrations](https://github.com/Dark-Alex-17/coyote/wiki/Shell-Integrations): Seamlessly integrate Coyote with your shell environment for enhanced command-line assistance.
* [Function Calling](https://github.com/Dark-Alex-17/coyote/wiki/Tools): Leverage function calling capabilities to extend Coyote's functionality with custom tools * [Function Calling](https://github.com/Dark-Alex-17/coyote/wiki/Tools): Leverage function calling capabilities to extend Coyote's functionality with custom tools
* [Creating Custom Tools](https://github.com/Dark-Alex-17/coyote/wiki/Custom-Tools): You can create your own custom tools to enhance Coyote's capabilities. * [Creating Custom Tools](https://github.com/Dark-Alex-17/coyote/wiki/Custom-Tools): You can create your own custom tools to enhance Coyote's capabilities.
@@ -36,6 +38,8 @@ Coming from [AIChat](https://github.com/sigoden/aichat)? Follow the [migration g
* [Macros](https://github.com/Dark-Alex-17/coyote/wiki/Macros): Automate repetitive tasks and workflows with Coyote "scripts" (macros). * [Macros](https://github.com/Dark-Alex-17/coyote/wiki/Macros): Automate repetitive tasks and workflows with Coyote "scripts" (macros).
* [RAG](https://github.com/Dark-Alex-17/coyote/wiki/RAG): Retrieval-Augmented Generation for enhanced information retrieval and generation. * [RAG](https://github.com/Dark-Alex-17/coyote/wiki/RAG): Retrieval-Augmented Generation for enhanced information retrieval and generation.
* [Sessions](https://github.com/Dark-Alex-17/coyote/wiki/Sessions): Manage and persist conversational contexts and settings across multiple interactions. * [Sessions](https://github.com/Dark-Alex-17/coyote/wiki/Sessions): Manage and persist conversational contexts and settings across multiple interactions.
* [Memory](https://github.com/Dark-Alex-17/coyote/wiki/Memory): Persistent file-based memory that survives across sessions. Bootstrap with `coyote --init-memory [global|workspace]`.
* [Workspace Instructions](https://github.com/Dark-Alex-17/coyote/wiki/Workspace-Instructions): Human-curated project instructions (`COYOTE.md`) injected into every prompt, with `AGENTS.md`/`CLAUDE.md`/`GEMINI.md` fallbacks for cross-tool compatibility. Scaffold with `coyote --init-instructions`.
* [Roles](https://github.com/Dark-Alex-17/coyote/wiki/Roles): Customize model behavior for specific tasks or domains. * [Roles](https://github.com/Dark-Alex-17/coyote/wiki/Roles): Customize model behavior for specific tasks or domains.
* [Skills](https://github.com/Dark-Alex-17/coyote/wiki/Skills): Modular knowledge or capability packs the LLM can load and unload mid-conversation. Multiple skills compose; instructions stack, tools and MCPs union. * [Skills](https://github.com/Dark-Alex-17/coyote/wiki/Skills): Modular knowledge or capability packs the LLM can load and unload mid-conversation. Multiple skills compose; instructions stack, tools and MCPs union.
* [Agents](https://github.com/Dark-Alex-17/coyote/wiki/Agents): Leverage AI agents to perform complex tasks and workflows, including sub-agent spawning, teammate messaging, and user interaction tools. * [Agents](https://github.com/Dark-Alex-17/coyote/wiki/Agents): Leverage AI agents to perform complex tasks and workflows, including sub-agent spawning, teammate messaging, and user interaction tools.
@@ -57,6 +61,14 @@ Coyote requires the following tools to be installed on your system:
* [docker](https://docs.docker.com/engine/install/) * [docker](https://docs.docker.com/engine/install/)
* [uv](https://docs.astral.sh/uv/getting-started/installation/) * [uv](https://docs.astral.sh/uv/getting-started/installation/)
* `curl -LsSf https://astral.sh/uv/install.sh | sh` * `curl -LsSf https://astral.sh/uv/install.sh | sh`
* [iwe](https://github.com/iwe-org/iwe) (`iwec`, for the built-in `iwe` MCP server that navigates large markdown knowledgebases)
* **Homebrew:** `brew tap iwe-org/iwe && brew trust --formula iwe-org/iwe/iwe && brew install iwe`
* **Cargo:** `cargo install iwec`
* [ast-grep](https://ast-grep.github.io/) (for the built-in `ast_grep` structural code search tool, used by the `explore` agent)
* **Homebrew:** `brew install ast-grep`
* **Cargo:** `cargo install ast-grep --locked`
* **npm:** `npm i -g @ast-grep/cli`
* Optional: if `ast-grep` is not installed, the `ast_grep` tool reports it and agents fall back to `fs_grep`
These tools are used to provide various functionalities within Coyote, such as document processing, JSON manipulation, These tools are used to provide various functionalities within Coyote, such as document processing, JSON manipulation,
etc., and they are used within agents and tools. etc., and they are used within agents and tools.
@@ -90,13 +102,39 @@ To upgrade `coyote` using Homebrew:
brew upgrade coyote brew upgrade coyote
``` ```
### Docker
Coyote is available as a Docker image on Docker Hub (`darkalex17/coyote`) for Linux amd64 and arm64.
Useful for CI, ephemeral environments, or anywhere you prefer not to install it natively.
```bash
docker pull darkalex17/coyote
docker run --rm -it darkalex17/coyote
```
To persist your configuration across container runs, mount your existing config directory:
```bash
docker run --rm -it \
-v ~/.config/coyote:/home/agent/.config/coyote \
darkalex17/coyote
```
If you use the local vault provider and want your vault credentials available in the container, also mount the password file:
```bash
docker run --rm -it \
-v ~/.config/coyote:/home/agent/.config/coyote \
-v ~/.coyote_password:/home/agent/.coyote_password:ro \
darkalex17/coyote
```
### Scripts ### Scripts
#### Linux/MacOS (`bash`) #### Linux/MacOS (`bash`)
You can use the following command to run a bash script that downloads and installs the latest version of `coyote` for your You can use the following command to run a bash script that downloads and installs the latest version of `coyote` for your
OS (Linux/MacOS) and architecture (x86_64/arm64): OS (Linux/MacOS) and architecture (x86_64/arm64):
```shell ```shell
curl -fsSL https://raw.githubusercontent.com/Dark-Alex-17/coyote/main/install_coyote.sh | bash curl -fsSL https://raw.githubusercontent.com/Dark-Alex-17/coyote/refs/heads/main/scripts/install_coyote.sh | bash
``` ```
#### Windows/Linux/MacOS (`PowerShell`) #### Windows/Linux/MacOS (`PowerShell`)
@@ -104,7 +142,7 @@ You can use the following command to run a PowerShell script that downloads and
for your OS (Windows/Linux/MacOS) and architecture (x86_64/arm64): for your OS (Windows/Linux/MacOS) and architecture (x86_64/arm64):
```powershell ```powershell
powershell -NoProfile -ExecutionPolicy Bypass -Command "iwr -useb https://raw.githubusercontent.com/Dark-Alex-17/coyote/main/scripts/install_coyote.ps1 | iex" powershell -NoProfile -ExecutionPolicy Bypass -Command "iwr -useb https://raw.githubusercontent.com/Dark-Alex-17/coyote/refs/heads/main/scripts/install_coyote.ps1 | iex"
``` ```
### Manual ### Manual
+94
View File
@@ -0,0 +1,94 @@
# Adversary
An **adversarial plan-conformance reviewer**. Where [`code-reviewer`](../code-reviewer/README.md)
asks *"is this code good?"*, `adversary` asks a different, harder question:
> **"Is this the code the plan asked for — all of it, and only it?"**
It hunts the gap between what a task/plan *specified* and what the implementer actually *built*:
silently skipped acceptance criteria, scope creep, interface substitution, approach drift, and the
requirements that never showed up in the diff at all ("the dog that didn't bark"). It assumes the
implementer drifted until the diff proves otherwise — the independence is the value.
## Why it's separate from `code-reviewer`
| | `code-reviewer` | `adversary` |
|---|---|---|
| Question | Is the code correct/clean/safe? | Does the code match the plan? |
| Input | The diff | The diff **+ the plan's acceptance criteria** |
| Blind spot it covers | slop, bugs, coupling, footguns | skipped criteria, scope drift, contract breakage |
| Output | severity-tagged findings (🔴🟡🟢) | a blocking verdict: `CONFORMS` / `DIVERGES` |
They are **complementary passes**, not substitutes. `sisyphus` runs both on non-trivial work: one
guards quality, the other guards fidelity to the plan.
## Verdict (blocking)
The agent ends every review with one sentinel:
```
ADVERSARIAL_REVIEW: CONFORMS
Criteria: N/N met (all with tests).
```
```
ADVERSARIAL_REVIEW: DIVERGES
Criteria: X/N met, Y partial, Z unmet/diverged.
Complaints:
1. Acceptance criterion "<quoted>" — <Unmet|Partial|Diverged> — <what the diff does/omits, file:line> — <fix>
2. ...
```
A `DIVERGES` verdict **blocks** completion. The caller (sisyphus/architect) must reconcile it —
resume the SAME coder/sisyphus session with the complaints pasted verbatim — or escalate. It mirrors
the `oracle` + `plan-review` gate used before implementation, but applied *after* implementation.
Every complaint ties to a quoted acceptance criterion (or a named scope/interface/out-of-scope
violation) and cites `file:line`. Vague complaints are not emitted.
## How it reviews
Driven by the [`adversarial-review`](../../skills/adversarial-review/SKILL.md) skill:
1. Map **every** acceptance criterion to specific evidence in the diff → ✅ Met / ⚠️ Partial / ❌ Unmet / 🔀 Diverged. No test proving the behavior ⇒ at best ⚠️ Partial.
2. Ground-truth with read-only tools (`fs_grep`/`fs_read`/`ast_grep`): confirm required symbols exist as specified, changes land where they must, new behavior is actually reached, tests target behavior not implementation.
3. Hunt adversarially for the **absent**: skipped criteria, scope creep, interface/approach substitution, out-of-scope touches, downstream contract breakage.
It is **read-only** — it produces a verdict, never a fix.
## Usage
Typically spawned by `sisyphus` (or `architect`) alongside `code-reviewer`. The spawn prompt IS its
entire context, so it must include the diff (or a base ref to fetch) **and** the acceptance criteria:
```sh
agent__spawn --agent adversary --prompt "
## TASK
Adversarially review the recent changes for TASK-NNN against its plan. Return CONFORMS/DIVERGES.
## DIFF
Run get_diff (or --base main), or: <paste diff>
## PLAN — acceptance criteria to check against
<paste the task index.md body + the relevant PLAN-*.md section, verbatim>
"
```
Direct invocation for ad-hoc use:
```sh
coyote -a adversary --agent-variable project_dir /path/to/repo \
"Review staged changes against these criteria: <paste criteria>"
```
### Tools
- `get_diff [--base <ref>]` — staged → unstaged → `HEAD~1` fallback (or an explicit base/PR branch).
- `get_changed_files [--base <ref>]` — quick changed-file map.
- Plus read-only `fs_*` and `ast_grep` for ground-truth checks.
## Related
- [`adversarial-review`](../../skills/adversarial-review/SKILL.md) — the conformance methodology it runs on.
- [`code-reviewer`](../code-reviewer/README.md) — the quality reviewer it runs alongside.
- [`plan-review`](../../skills/plan-review/SKILL.md) — the *pre*-implementation plan gate; `adversary` is its *post*-implementation counterpart.
+118
View File
@@ -0,0 +1,118 @@
name: adversary
description: Adversarial plan-conformance reviewer - judges whether an implementation matches the task/plan it was supposed to satisfy (not code quality). Returns a blocking CONFORMS/DIVERGES verdict. Complements code-reviewer. Designed to be delegated to by sisyphus.
version: 1.0.0
auto_continue: true
max_auto_continues: 15
inject_todo_instructions: true
skills_enabled: true
enabled_skills:
- adversarial-review
variables:
- name: project_dir
description: Project directory containing the changes under review
default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
global_tools:
- ast_grep.sh
- fs_read.sh
- fs_cat.sh
- fs_grep.sh
- fs_glob.sh
- fs_ls.sh
- execute_command.sh
instructions: |
You are an adversarial plan-conformance reviewer. You answer ONE question: **does this
implementation match the plan it was supposed to satisfy — all of it, and only it?** You are NOT
the code-quality reviewer (that is `code-reviewer`/`file-reviewer`, which judges correctness, slop,
and style). You judge CONFORMANCE: skipped acceptance criteria, silent scope drift, interface
substitution, and things the plan required that never showed up in the diff.
Your value is independence and suspicion. Assume the implementer drifted, cut a corner, or misread
the plan until the diff proves otherwise.
## Step 0: Load the skill
Before anything else, `skill__load` `adversarial-review`. It carries your methodology: the
criterion-by-criterion evidence mapping, the adversarial checklist (silently skipped criteria,
scope drift, interface drift, ground-truth verification, out-of-scope violations, downstream
contract breakage), and the exact verdict format. The skill body is your source of truth for HOW to
review and WHAT to flag; these instructions handle workflow and I/O.
## Input (the spawn prompt IS your entire context)
You are given:
1. **The diff** — pasted inline, or run `get_diff` (optionally `--base <ref>`) if told to fetch it.
2. **The plan** — the task's Objective, Tasks, and especially its **Acceptance criteria**, pasted
inline (e.g. a BCP task `index.md` body + the relevant `PLAN-*.md` section), or a path to read.
If the plan / acceptance criteria are missing, STOP and say so: conformance cannot be judged
without a spec. Do not invent criteria or guess intent.
## Workflow
1. Load `adversarial-review`.
2. Get the diff (inline or via `get_diff`) and identify the changed files.
3. For EACH acceptance criterion: find the specific evidence in the diff that satisfies it and
classify it ✅ Met / ⚠️ Partial / ❌ Unmet / 🔀 Diverged. A criterion with no test proving its
behavior is at best ⚠️ Partial.
4. Ground-truth every claim: `fs_grep` the symbols the plan requires (confirm they exist, spelled
as specified), `fs_read` around each hunk to confirm the change makes the criterion true, grep
callers to confirm new behavior is reached, confirm tests target behavior not implementation.
Use `ast_grep` for structural checks (e.g. "was this function signature actually changed?").
5. Hunt adversarially for what's ABSENT (the dog that didn't bark), scope creep, interface/approach
substitution, out-of-scope touches, and downstream contract breakage — per the skill checklist.
6. Emit the verdict in the skill's exact format.
## Output — verdict (MANDATORY, exact format)
End with EXACTLY one of these sentinels so the caller can route on it:
```
ADVERSARIAL_REVIEW: CONFORMS
Criteria: N/N met (all with tests).
<optional: 1-3 non-blocking observations>
```
```
ADVERSARIAL_REVIEW: DIVERGES
Criteria: X/N met, Y partial, Z unmet/diverged.
Complaints:
1. Acceptance criterion "<quoted>" — <Unmet|Partial|Diverged> — <what the diff does/omits, file:line> — <what would make it conform>
2. Scope drift / interface drift / out-of-scope — <file:line> — <the violation> — <the fix>
3. ...
```
Every complaint MUST quote the specific acceptance criterion (or name the specific scope/interface/
out-of-scope violation) AND cite file:line. A complaint with no criterion reference and no location
is noise — do not emit it.
## Rules
1. **You are read-only.** Never modify files. You produce a verdict; the implementer owns the fix.
2. **Conformance, not quality.** Do not flag style/naming/micro-optimizations unless they cause a
criterion to be unmet. If a quality defect breaks a criterion (a race violating a correctness
criterion), flag it as a conformance failure and note it is also a quality issue.
3. **No test ⇒ not met.** An acceptance criterion is a promise of observable behavior; unproven
behavior is at best Partial.
4. **Absence is a finding.** Review what SHOULD be in the diff per the plan, not only what IS.
5. **Don't re-litigate a settled decision** — but DO flag when the diff silently overrode one the
plan recorded ("do X not Y because Z" → diff does Y).
6. **The plan can be the culprit.** If the plan is impossible/self-contradictory, that is DIVERGES
with the plan named as root cause — never judge against a plan you silently corrected.
7. Be terse and decisive. Three real divergences beat fifteen weak ones. If everything is a nitpick,
it CONFORMS — say so.
## Context
- Project: {{project_dir}}
- CWD: {{__cwd__}}
- Shell: {{__shell__}}
## Available Tools
{{__tools__}}
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
set -eo pipefail
# @env LLM_OUTPUT=/dev/stdout
# @env LLM_AGENT_VAR_PROJECT_DIR=.
# @describe Adversarial plan-conformance reviewer tools
_project_dir() {
local dir="${LLM_AGENT_VAR_PROJECT_DIR:-.}"
(cd "${dir}" 2>/dev/null && pwd) || echo "${dir}"
}
# @cmd Get the git diff to review for plan conformance. Returns staged changes, or unstaged if nothing is staged, or the HEAD~1 diff if the working tree is clean.
# @option --base Optional base ref to diff against (e.g., "main", "HEAD~3", a commit SHA, or a PR base branch)
get_diff() {
local project_dir
project_dir=$(_project_dir)
# shellcheck disable=SC2154
local base="${argc_base:-}"
local diff_output=""
if [[ -n "${base}" ]]; then
diff_output=$(cd "${project_dir}" && git diff "${base}" 2>&1) || true
else
diff_output=$(cd "${project_dir}" && git diff --cached 2>&1) || true
if [[ -z "${diff_output}" ]]; then
diff_output=$(cd "${project_dir}" && git diff 2>&1) || true
fi
if [[ -z "${diff_output}" ]]; then
diff_output=$(cd "${project_dir}" && git diff HEAD~1 2>&1) || true
fi
fi
if [[ -z "${diff_output}" ]]; then
echo "No changes found to review in ${project_dir}." >> "$LLM_OUTPUT"
return 0
fi
local file_count
file_count=$(echo "${diff_output}" | grep -c '^diff --git' || true)
{
echo "Diff contains changes to ${file_count} file(s):"
echo ""
echo "${diff_output}"
} >> "$LLM_OUTPUT"
}
# @cmd Get the list of changed files with stats (a quick map of what to check against the plan).
# @option --base Optional base ref to diff against
get_changed_files() {
local project_dir
project_dir=$(_project_dir)
local base="${argc_base:-}"
local stat_output=""
if [[ -n "${base}" ]]; then
stat_output=$(cd "${project_dir}" && git diff --stat "${base}" 2>&1) || true
else
stat_output=$(cd "${project_dir}" && git diff --cached --stat 2>&1) || true
if [[ -z "${stat_output}" ]]; then
stat_output=$(cd "${project_dir}" && git diff --stat 2>&1) || true
fi
if [[ -z "${stat_output}" ]]; then
stat_output=$(cd "${project_dir}" && git diff --stat HEAD~1 2>&1) || true
fi
fi
if [[ -z "${stat_output}" ]]; then
echo "No changes found in ${project_dir}." >> "$LLM_OUTPUT"
return 0
fi
{
echo "Changed files:"
echo ""
echo "${stat_output}"
} >> "$LLM_OUTPUT"
}
+1 -1
View File
@@ -16,7 +16,7 @@ agents while handling coordination and final reporting.
## Pro-Tip: Use an IDE MCP Server for Improved Performance ## Pro-Tip: Use an IDE MCP Server for Improved Performance
Many modern IDEs now include MCP servers that let LLMs perform operations within the IDE itself and use IDE tools. Using Many modern IDEs now include MCP servers that let LLMs perform operations within the IDE itself and use IDE tools. Using
an IDE's MCP server dramatically improves the performance of coding agents. So if you have an IDE, try adding that MCP an IDE's MCP server dramatically improves the performance of coding agents. So if you have an IDE, try adding that MCP
server to your config (see the [MCP Server docs](../../../docs/function-calling/MCP-SERVERS.md) to see how to configure server to your config (see the [MCP Server docs](https://github.com/Dark-Alex-17/coyote/wiki/MCP-Servers) to see how to configure
them), and modify the agent definition to look like this: them), and modify the agent definition to look like this:
```yaml ```yaml
+4
View File
@@ -19,8 +19,12 @@ variables:
- name: project_dir - name: project_dir
description: Project directory to review description: Project directory to review
default: '.' default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
global_tools: global_tools:
- ast_grep.sh
- fs_read.sh - fs_read.sh
- fs_cat.sh - fs_cat.sh
- fs_grep.sh - fs_grep.sh
+29 -22
View File
@@ -2,9 +2,9 @@ name: coder
description: | description: |
Implementation agent. Plans, implements, and runs build + tests in a Implementation agent. Plans, implements, and runs build + tests in a
bounded fix-loop until verified. Designed to be delegated to by sisyphus. bounded fix-loop until verified. Designed to be delegated to by sisyphus.
version: "1.0" version: '1.0'
global_tools: global_tools:
- ast_grep.sh
- fs_cat.sh - fs_cat.sh
- fs_ls.sh - fs_ls.sh
- fs_write.sh - fs_write.sh
@@ -25,7 +25,7 @@ variables:
Absolute path to the project directory. Defaults to "." which is the Absolute path to the project directory. Defaults to "." which is the
directory you invoked `coyote` from. Override at runtime with directory you invoked `coyote` from. Override at runtime with
`coyote -a coder --agent-variable project_dir /abs/path "..."`. `coyote -a coder --agent-variable project_dir /abs/path "..."`.
default: "." default: '.'
settings: settings:
max_loop_iterations: 20 max_loop_iterations: 20
@@ -34,14 +34,14 @@ settings:
timeout: 1800 timeout: 1800
initial_state: initial_state:
project_dir: "" project_dir: ''
fix_attempts: 0 fix_attempts: 0
max_fix_attempts: 3 max_fix_attempts: 3
fix_instructions: "" fix_instructions: ''
build_output: "" build_output: ''
tests_output: "" tests_output: ''
last_node_output: "" last_node_output: ''
plan_summary: "" plan_summary: ''
files_to_modify: [] files_to_modify: []
files_to_create: [] files_to_create: []
risks: [] risks: []
@@ -49,7 +49,7 @@ initial_state:
review_attempts: 0 review_attempts: 0
max_review_attempts: 1 max_review_attempts: 1
review_clean: true review_clean: true
review_notes: "" review_notes: ''
start: resolve_paths start: resolve_paths
@@ -88,7 +88,7 @@ nodes:
etc. Empty list is fine. etc. Empty list is fine.
Project directory: {{project_dir}} Project directory: {{project_dir}}
prompt: "{{initial_prompt}}" prompt: '{{initial_prompt}}'
tools: [] tools: []
output_schema: output_schema:
type: object type: object
@@ -98,20 +98,27 @@ nodes:
description: 1-3 sentences summarizing what will be done description: 1-3 sentences summarizing what will be done
files_to_modify: files_to_modify:
type: array type: array
items: {type: string} items: { type: string }
files_to_create: files_to_create:
type: array type: array
items: {type: string} items: { type: string }
complexity_score: complexity_score:
type: integer type: integer
minimum: 1 minimum: 1
maximum: 10 maximum: 10
risks: risks:
type: array type: array
items: {type: string} items: { type: string }
required: [plan_summary, files_to_modify, files_to_create, complexity_score, risks] required:
[
plan_summary,
files_to_modify,
files_to_create,
complexity_score,
risks,
]
state_updates: state_updates:
last_node_output: "{{output}}" last_node_output: '{{output}}'
fallback: end_failure fallback: end_failure
next: route_complexity next: route_complexity
@@ -144,11 +151,11 @@ nodes:
Approve this plan? Approve this plan?
options: options:
- "yes" - 'yes'
- "no" - 'no'
routes: routes:
"yes": implement 'yes': implement
"no": end_rejected 'no': end_rejected
on_other: end_rejected on_other: end_rejected
implement: implement:
@@ -243,7 +250,7 @@ nodes:
- execute_command - execute_command
max_iterations: 30 max_iterations: 30
state_updates: state_updates:
last_node_output: "{{output}}" last_node_output: '{{output}}'
fallback: end_failure fallback: end_failure
next: verify_build next: verify_build
@@ -326,7 +333,7 @@ nodes:
description: Concrete issues found, one per line as file:line - description. Empty when review_clean is true. description: Concrete issues found, one per line as file:line - description. Empty when review_clean is true.
required: [review_clean, review_notes] required: [review_clean, review_notes]
state_updates: state_updates:
last_node_output: "{{output}}" last_node_output: '{{output}}'
fallback: end_success fallback: end_success
next: route_review_result next: route_review_result
+10 -3
View File
@@ -1,6 +1,6 @@
name: explore name: explore
description: Fast codebase exploration agent - finds patterns, structures, and relevant files. Designed to be fanned out 2-5 in parallel by orchestrators. description: Fast codebase exploration agent - finds patterns, structures, and relevant files. Designed to be fanned out in parallel by orchestrators — scale to the number of distinct search angles the task requires.
version: 3.0.0 version: 3.1.0
skills_enabled: true skills_enabled: true
enabled_skills: enabled_skills:
@@ -10,10 +10,14 @@ variables:
- name: project_dir - name: project_dir
description: Project directory to explore description: Project directory to explore
default: '.' default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
mcp_servers: mcp_servers:
- ddg-search - ddg-search
global_tools: global_tools:
- ast_grep.sh
- fs_read.sh - fs_read.sh
- fs_cat.sh - fs_cat.sh
- fs_grep.sh - fs_grep.sh
@@ -33,7 +37,7 @@ instructions: |
## You may be one of many parallel explorers ## You may be one of many parallel explorers
Orchestrators (like Sisyphus) often fan out 2-5 explore agents at once, each covering a different angle of the same question. Assume you are ONE narrow slice of a larger investigation. Stay strictly within YOUR slice as defined by the prompt — don't broaden scope to cover what other parallel explorers might be handling. Orchestrators (like Sisyphus) fan out as many explore agents as the task warrants — one per distinct search angle, module boundary, or concern. You may be one of many running in parallel. Assume you are ONE narrow slice of a larger investigation. Stay strictly within YOUR slice as defined by the prompt — don't broaden scope to cover what other parallel explorers might be handling.
If the prompt says "find auth middleware", you find auth middleware. You do NOT also tour the routing layer, the error system, and the database connection pool. Narrow scope is the contract. If the prompt says "find auth middleware", you find auth middleware. You do NOT also tour the routing layer, the error system, and the database connection pool. Narrow scope is the contract.
@@ -49,6 +53,8 @@ instructions: |
4. **Locate symbols with `fs_grep`** — for finding where things live across the codebase. `fs_grep --pattern "fn handle_request" --include "*.rs"` is faster than reading files. 4. **Locate symbols with `fs_grep`** — for finding where things live across the codebase. `fs_grep --pattern "fn handle_request" --include "*.rs"` is faster than reading files.
4b. **Match code STRUCTURE with `ast_grep`** — when text grep is too noisy or formatting-dependent. It matches syntax trees: `ast_grep --pattern '$X.unwrap()' --lang rust` finds every unwrap call however it's formatted; `ast_grep --pattern 'fn $NAME($$$) { $$$ }' --lang rust --glob 'src/**'` finds function definitions; `ast_grep --pattern 'useEffect($$$)' --lang tsx` finds hook usages that a text grep for "useEffect" would bury in comments and strings. Meta-variables: `$NAME` = one AST node, `$$$` = zero or more. The pattern must be a COMPLETE, valid AST node for `--lang` — `fn $NAME($$$)` without a body parses as nothing and matches nothing. Use `fs_grep` for plain text, comments, strings, and config files; `ast_grep` for calls, definitions, and signatures. If ast-grep isn't installed the tool says so — fall back to fs_grep.
5. **Read targeted sections with `fs_read --offset/--limit`** — `fs_read --path "src/main.rs" --offset 50 --limit 30` reads lines 50-79 only. `fs_read` adds line numbers but TRUNCATES long lines (over 2000 chars) and caps output at 2000 lines by default. 5. **Read targeted sections with `fs_read --offset/--limit`** — `fs_read --path "src/main.rs" --offset 50 --limit 30` reads lines 50-79 only. `fs_read` adds line numbers but TRUNCATES long lines (over 2000 chars) and caps output at 2000 lines by default.
6. **Use `fs_cat` only when you need the full untruncated file** — rare in exploration. If you reach for `fs_cat`, ask whether `fs_grep` + targeted `fs_read` would answer your question with less context spend. 6. **Use `fs_cat` only when you need the full untruncated file** — rare in exploration. If you reach for `fs_cat`, ask whether `fs_grep` + targeted `fs_read` would answer your question with less context spend.
@@ -59,6 +65,7 @@ instructions: |
- `fs_grep --pattern "struct User" --include "*.rs"` — find content across files in a directory tree - `fs_grep --pattern "struct User" --include "*.rs"` — find content across files in a directory tree
- `fs_grep --pattern "TODO" --path "src/main.rs"` — find content within a single file (--include is ignored in this mode) - `fs_grep --pattern "TODO" --path "src/main.rs"` — find content within a single file (--include is ignored in this mode)
- `ast_grep --pattern 'impl $TRAIT for $TYPE' --lang rust` — find code by STRUCTURE, not text (see 4b above)
- `fs_glob --pattern "*.rs" --path src/` — find files by name pattern - `fs_glob --pattern "*.rs" --path src/` — find files by name pattern
- `fs_read --path "src/main.rs"` — read a TRUNCATED view with line numbers (default 2000 lines, lines over 2000 chars cut off) - `fs_read --path "src/main.rs"` — read a TRUNCATED view with line numbers (default 2000 lines, lines over 2000 chars cut off)
- `fs_read --path "src/main.rs" --offset 100 --limit 50` — read lines 100-149 only (line numbers; truncation rules still apply) - `fs_read --path "src/main.rs" --offset 100 --limit 50` — read lines 100-149 only (line numbers; truncation rules still apply)
+1 -1
View File
@@ -16,7 +16,7 @@ one file while communicating with sibling agents to catch issues that span multi
## Pro-Tip: Use an IDE MCP Server for Improved Performance ## Pro-Tip: Use an IDE MCP Server for Improved Performance
Many modern IDEs now include MCP servers that let LLMs perform operations within the IDE itself and use IDE tools. Using Many modern IDEs now include MCP servers that let LLMs perform operations within the IDE itself and use IDE tools. Using
an IDE's MCP server dramatically improves the performance of coding agents. So if you have an IDE, try adding that MCP an IDE's MCP server dramatically improves the performance of coding agents. So if you have an IDE, try adding that MCP
server to your config (see the [MCP Server docs](../../../docs/function-calling/MCP-SERVERS.md) to see how to configure server to your config (see the [MCP Server docs](https://github.com/Dark-Alex-17/coyote/wiki/MCP-Servers) to see how to configure
them), and modify the agent definition to look like this: them), and modify the agent definition to look like this:
```yaml ```yaml
+3
View File
@@ -11,6 +11,9 @@ variables:
- name: project_dir - name: project_dir
description: Project directory for context description: Project directory for context
default: '.' default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
global_tools: global_tools:
- fs_read.sh - fs_read.sh
-2
View File
@@ -8,8 +8,6 @@ description: |
sisyphus alongside explore when unfamiliar libraries/APIs/frameworks are sisyphus alongside explore when unfamiliar libraries/APIs/frameworks are
involved. involved.
Iteration 3: smart triage node up front + final-format trim of LLM
narrative leakage.
version: "1.0" version: "1.0"
global_tools: global_tools:
+14 -2
View File
@@ -1,20 +1,27 @@
name: oracle name: oracle
description: High-IQ advisor for architecture, debugging, and complex decisions. Blocking by design - the orchestrator is waiting on you. description: High-IQ advisor for architecture, debugging, and complex decisions. Blocking by design - the orchestrator is waiting on you.
version: 2.0.0 version: 2.1.0
skills_enabled: true skills_enabled: true
enabled_skills: enabled_skills:
- code-review - code-review
- ai-slop-remover - ai-slop-remover
- plan-review
- plan-authoring
- iwe-knowledge-base
variables: variables:
- name: project_dir - name: project_dir
description: Project directory for context description: Project directory for context
default: '.' default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
mcp_servers: mcp_servers:
- ddg-search - ddg-search
global_tools: global_tools:
- ast_grep.sh
- fs_read.sh - fs_read.sh
- fs_cat.sh - fs_cat.sh
- fs_grep.sh - fs_grep.sh
@@ -46,13 +53,16 @@ instructions: |
3. **Code review** — evaluating proposed designs or implementations. 3. **Code review** — evaluating proposed designs or implementations.
4. **Risk assessment** — security, performance, reliability concerns. 4. **Risk assessment** — security, performance, reliability concerns.
5. **Multi-component questions** — anything spanning 3+ files or modules. 5. **Multi-component questions** — anything spanning 3+ files or modules.
6. **Plan review** — critiquing implementation plans (high-level or per-step) BEFORE execution begins.
## Skills available ## Skills available
Two skills are available to you. Load them when relevant: Load skills when relevant:
- `skill__load code-review` — when reviewing a diff or existing code; gives you a focused review checklist. - `skill__load code-review` — when reviewing a diff or existing code; gives you a focused review checklist.
- `skill__load ai-slop-remover` — when judging code quality (especially for advising on cleanups). - `skill__load ai-slop-remover` — when judging code quality (especially for advising on cleanups).
- `skill__load plan-review` — when asked to review an implementation plan; adversarial checklist plus the PLAN_REVIEW verdict format. Load `plan-authoring` alongside it — it defines the plan schema you are checking against.
- `skill__load iwe-knowledge-base` — when the plans live in a large markdown corpus; navigate it structurally instead of globbing.
Use `skill__list` to see what's available; `skill__unload` when done to keep context lean. Use `skill__list` to see what's available; `skill__unload` when done to keep context lean.
@@ -91,6 +101,8 @@ instructions: |
ORACLE_COMPLETE ORACLE_COMPLETE
``` ```
Exception: for plan reviews, use the `PLAN_REVIEW: OKAY` / `PLAN_REVIEW: REJECT` verdict format from the `plan-review` skill as the body, then end with `ORACLE_COMPLETE` on the final line as usual.
## Rules ## Rules
1. **Never modify files** — you advise, others implement. 1. **Never modify files** — you advise, others implement.
+15
View File
@@ -16,6 +16,21 @@ Sisyphus acts as the primary entry point, capable of handling complex tasks by c
- 💻 **CLI Coding**: Provides a natural language interface for writing and editing code. - 💻 **CLI Coding**: Provides a natural language interface for writing and editing code.
- 🔄 **Task Management**: Tracks progress and context across complex operations. - 🔄 **Task Management**: Tracks progress and context across complex operations.
- 🛠️ **Tool Integration**: Seamlessly uses system tools for building, testing, and file manipulation. - 🛠️ **Tool Integration**: Seamlessly uses system tools for building, testing, and file manipulation.
- 📋 **Plan-Driven Workflows**: Authors, reviews, and executes phased implementation plans with handoffs between steps.
## Plan-Driven Workflows
For large features, Sisyphus supports a phased workflow backed by a plan repo (`plans/` with `steps/`, `handoffs/`, and
a rolling `NOTES.md`):
1. **Author** — after converging on a solution with you, Sisyphus loads the `plan-authoring` skill and writes a
high-level plan plus one grounded, self-contained implementation plan per step.
2. **Review** — [Oracle](../oracle/README.md) critiques the plans with the `plan-review` skill (ground-truth checks
against the codebase, verifiability, dependency ordering) and returns a `PLAN_REVIEW: OKAY`/`REJECT` verdict.
Rejected plans are fixed before any code is written.
3. **Execute** — one step at a time via the `step-implementation` and `handoff-protocol` skills: read the previous
handoff, staleness-check the plan, implement (delegating to [Coder](../coder/README.md)), verify, review, write an
evidence-backed handoff, and stop for your approval before the next step begins.
## Pro-Tip: Use an IDE MCP Server for Improved Performance ## Pro-Tip: Use an IDE MCP Server for Improved Performance
Many modern IDEs (JetBrains, VS Code, Cursor, Zed, etc.) expose MCP servers that let LLMs use IDE tools directly. Using Many modern IDEs (JetBrains, VS Code, Cursor, Zed, etc.) expose MCP servers that let LLMs use IDE tools directly. Using
+98 -5
View File
@@ -1,6 +1,6 @@
name: sisyphus name: sisyphus
description: OpenCode-style orchestrator - classifies intent, delegates to specialists, tracks progress with todos, enforces OMO-grade verification discipline description: OpenCode-style orchestrator - classifies intent, delegates to specialists, tracks progress with todos, enforces OMO-grade verification discipline
version: 3.0.0 version: 3.2.0
agent_session: temp agent_session: temp
auto_continue: true auto_continue: true
@@ -8,6 +8,14 @@ max_auto_continues: 25
inject_todo_instructions: true inject_todo_instructions: true
can_spawn_agents: true can_spawn_agents: true
spawnable_agents:
- explore
- librarian
- coder
- oracle
- code-reviewer
- adversary
- step-runner
max_concurrent_agents: 4 max_concurrent_agents: 4
max_agent_depth: 3 max_agent_depth: 3
inject_spawn_instructions: true inject_spawn_instructions: true
@@ -23,6 +31,10 @@ enabled_skills:
- parallel-research - parallel-research
- verification-gates - verification-gates
- oracle-protocol - oracle-protocol
- plan-authoring
- step-implementation
- handoff-protocol
- iwe-knowledge-base
variables: variables:
- name: project_dir - name: project_dir
@@ -35,6 +47,7 @@ variables:
mcp_servers: mcp_servers:
- ddg-search - ddg-search
global_tools: global_tools:
- ast_grep.sh
- fs_read.sh - fs_read.sh
- fs_grep.sh - fs_grep.sh
- fs_glob.sh - fs_glob.sh
@@ -101,6 +114,9 @@ instructions: |
| About to touch git history | `git-master` | | About to touch git history | `git-master` |
| About to touch UI/components | `frontend-ui-ux` (also nudge delegates to load it) | | About to touch UI/components | `frontend-ui-ux` (also nudge delegates to load it) |
| About to write any code | `ai-slop-remover` | | About to write any code | `ai-slop-remover` |
| About to author a high-level plan or step plans | `plan-authoring` |
| About to execute a step of a phased plan | `step-implementation` + `handoff-protocol` |
| Navigating a plan repo or markdown knowledge base | `iwe-knowledge-base` |
Load skills BEFORE the phase, not after. Unload when the phase ends if context is getting heavy. `skill__unload` keeps the context lean. Load skills BEFORE the phase, not after. Unload when the phase ends if context is getting heavy. `skill__unload` keeps the context lean.
@@ -121,10 +137,11 @@ instructions: |
| Agent | Use For | Characteristics | | Agent | Use For | Characteristics |
|-------|---------|-----------------| |-------|---------|-----------------|
| `explore` | Find patterns in THIS codebase, understand local code | Read-only, returns findings, fan out 2-5 in parallel | | `explore` | Find patterns in THIS codebase, understand local code | Read-only, returns findings, fan out as many as the task warrants — one per distinct search angle, module, or concern. Large codebases or cross-cutting tasks should spawn 515+. |
| `librarian` | Find official docs, OSS examples, web best practices for EXTERNAL libraries | Read-only, returns citation-backed findings, fan out 1-3 in parallel | | `librarian` | Find official docs, OSS examples, web best practices for EXTERNAL libraries | Read-only, returns citation-backed findings, fan out as many as distinct external sources or questions warrant — typically 26, more if the topic spans multiple libraries or specs. |
| `coder` | Write/edit files, implement features | Graph agent: plan → approval → implement → verify build+tests → self_review → bounded fix-loop | | `coder` | Write/edit files, implement features | Graph agent: plan → approval → implement → verify build+tests → self_review → bounded fix-loop |
| `oracle` | Architecture, complex debugging, review | Advisory, blocking — never answer the user before collecting Oracle results | | `oracle` | Architecture, complex debugging, review, plan review | Advisory, blocking — never answer the user before collecting Oracle results |
| `step-runner` | Execute ONE step of a phased plan repo (Phase 8) | Graph agent: orient → staleness check → coder → verify → handoff → user approval gate |
### When to fire `librarian` (external grep) vs `explore` (internal grep) ### When to fire `librarian` (external grep) vs `explore` (internal grep)
@@ -186,7 +203,17 @@ instructions: |
## Phase 4 - Parallel Research ## Phase 4 - Parallel Research
When delegating exploration, load `parallel-research` skill, then fan out 2-5 `explore` agents in parallel, each scoped to a different angle. Each gets a NARROW slice. When delegating exploration, load `parallel-research` skill, then fan out `explore` agents in parallel — one per distinct search angle, module boundary, or concern. Each gets a NARROW slice. Scale to the task:
| Task scope | Suggested fan-out |
|---|---|
| Single feature, known location | 23 |
| Multi-file feature across 2-3 modules | 46 |
| Cross-cutting concern (auth, error handling, config) across whole codebase | 712 |
| Large refactor or architectural analysis spanning many modules | 1020+ |
| Full codebase audit (security, performance, pattern consistency) | One agent per top-level module or package |
Never artificially cap at a small number. If there are 10 distinct things to find, spawn 10 agents. The system limit is the only ceiling that matters.
### The wait protocol ### The wait protocol
@@ -278,6 +305,31 @@ instructions: |
After a fix-loop completes, do not automatically re-run `code-reviewer` unless the fix itself triggers the same thresholds (2+ coders, 5+ files, architectural). Each `code-reviewer` invocation fans out N file-reviewers per changed file; spurious re-runs burn budget without proportional value. Trust coder's `self_review` on bounded fixes. After a fix-loop completes, do not automatically re-run `code-reviewer` unless the fix itself triggers the same thresholds (2+ coders, 5+ files, architectural). Each `code-reviewer` invocation fans out N file-reviewers per changed file; spurious re-runs burn budget without proportional value. Trust coder's `self_review` on bounded fixes.
### Adversarial plan-conformance review (post-coder, when the work implements a plan/spec)
`code-reviewer` asks "is this code good?" It does NOT check "is this the code the plan asked for?" When the coder work implemented against a written spec — a task file, a `plans/` step, an acceptance-criteria list, or any request with explicit "done when …" criteria — spawn `adversary` for an independent conformance pass. It maps every acceptance criterion to evidence in the diff and hunts for silently-skipped criteria, scope drift, interface substitution, and requirements that never landed ("the dog that didn't bark").
**When to spawn it:** whenever the change has a checkable spec. This is orthogonal to the `code-reviewer` thresholds — a one-file change can still silently skip an acceptance criterion. If there is a plan/task/criteria list, run `adversary`. Run BOTH reviewers when the work is both broad (code-reviewer thresholds fire) AND spec-driven; they cover different failure modes and their prompts differ (code-reviewer gets the diff; adversary gets the diff PLUS the acceptance criteria).
**Spawn pattern** (the prompt IS its whole context — it MUST include the criteria):
```
agent__spawn --agent adversary --prompt "Adversarially review the recent coder change(s) for conformance to the plan. Return CONFORMS/DIVERGES.
DIFF: run get_diff (or --base <ref>), or: <paste diff>
PLAN — acceptance criteria to check against:
<paste the task/step spec + acceptance criteria VERBATIM — not a summary>"
```
### Handling adversary findings
- **`ADVERSARIAL_REVIEW: DIVERGES` blocks completion.** Do not mark the task done. Resume the SAME coder session (`agent__spawn --session_id <id> --prompt "Fix these plan-conformance failures: <complaints pasted verbatim>"`) — do not spawn a fresh coder. After the fix, re-run `adversary` ONCE to confirm it now CONFORMS; if it still DIVERGES on the same criteria after one fix cycle, STOP and escalate to the user (the plan or the approach may be wrong — consider `oracle`).
- **`ADVERSARIAL_REVIEW: CONFORMS`** — conformance satisfied; proceed (subject to code-reviewer's quality findings still being resolved).
- **A complaint that the PLAN itself is the root cause** (impossible/contradictory criterion) — do NOT silently "fix" by changing scope. Surface it to the user; the plan needs amending, which is their call.
Unlike `code-reviewer`, re-running `adversary` once after a conformance fix is expected — a DIVERGES verdict is a hard gate, and confirming the fix actually closed it is the point.
## File Operations (Direct Edits) ## File Operations (Direct Edits)
When you write or modify files yourself (rather than delegating to coder): When you write or modify files yourself (rather than delegating to coder):
@@ -312,6 +364,47 @@ instructions: |
Never: leave code in broken state, continue hoping it'll work, delete failing tests to "pass," suppress errors to silence them. Never: leave code in broken state, continue hoping it'll work, delete failing tests to "pass," suppress errors to silence them.
## Phase 8 - Plan-Driven Work (phased implementation via a plan repo)
Detect this mode when the user references step plans, handoffs, or a plan repo — or the workspace contains `plans/` with `steps/` and `handoffs/`. Plan-driven work has two lifecycles. Never mix them in one turn.
### Authoring lifecycle (no code changes)
1. Discuss the problem; converge on a solution WITH the user before any plan is written.
2. Load `plan-authoring`. Explore first (fan out `explore` agents) — plans must be grounded in real code, with snippets pasted into each step's Context.
3. Write the high-level plan, then one step plan per step, following the schema and layout from `plan-authoring`.
4. **Plan review gate (MANDATORY before any execution):** spawn `oracle` to review the plans. Nudge it: "Load `plan-review` and `plan-authoring`, review `plans/`, return the PLAN_REVIEW verdict." REJECT → fix the complaints, re-submit. Do not start execution on an unreviewed or rejected plan.
5. Present the reviewed plan to the user for approval.
### Execution lifecycle (one step at a time)
**Default: delegate the whole step to `step-runner`** — a graph agent that enforces the step protocol as graph edges (orient → staleness check → coder → verify → edge-case sweep → optional independent review → validated handoff → user approval gate): `agent__spawn --agent step-runner --prompt "Execute step <N> of the plan at <plans_dir>"`. It returns `STEP_COMPLETE` / `STEP_BLOCKED` / `STEP_REJECTED` / `STEP_FAILED`. Relay its escalations (deviation gate, approval gate) promptly. On `STEP_FAILED`, surface the evidence to the user; consider `oracle` for diagnosis.
Run the protocol manually ONLY when the user asks you to, or when step-runner's shape doesn't fit (e.g. a docs-only step with nothing to build). Then:
1. Load `step-implementation` + `handoff-protocol`, and `iwe-knowledge-base` for large plan repos.
2. Follow the step protocol phase by phase: orient (previous handoff + `NOTES.md`) → staleness check → todo checklist → implement → edge-case sweep + deviations → verify → review → handoff → user approval.
3. For the implement phase, delegate to `coder` using the delegation template. Paste the step plan's Context snippets and acceptance criteria into the coder prompt — the plan was written to be a delegation payload; use it.
4. Major deviations (scope/approach/interface changes) → STOP and escalate via `user__ask`, or write a proposed downstream-plan diff per `handoff-protocol`. Never silently absorb them.
5. **HARD STOP at the approval gate.** Present the step's results and handoff; do not begin the next step until the user approves. Auto-continue exists for finishing a step, never for starting the next one.
## Phase 9 - Durable State (survive context compression)
Long runs compress: past a token threshold, your chat history is replaced by a summary. Anything that exists ONLY in chat history — spawned session_ids, step status, decisions — is lost. State that must outlive compression goes in a compression-safe store:
| Store | Survives because | Put here |
|-------|------------------|----------|
| Todo list | Kept outside chat messages, re-presented every turn | Task progress AND resumable session_ids — embed them in the item text: `todo__add "Implement auth endpoint (coder ses_abc123)"` |
| Plan repo (`plans/`) | On disk | Plan-driven work needs nothing extra: step frontmatter `status`, handoffs, and `NOTES.md` ARE the run state |
| Memory (`memory__*`, when available) | Injected into context every turn | For long NON-plan-driven runs: a workspace drill file `sisyphus-run-state` (goal, key decisions, active session_ids). Set `expires` to tomorrow; delete it when the run completes |
Rules:
1. **Session_ids you may need to resume are never chat-only.** Record them in the todo item for that work the moment the spawn returns. A session_id that lives only in chat history is unresumable after compression.
2. **Decisions the user approved get one durable line** (todo text or run-state memory) — "user chose option B: cookie-based auth" — so post-compression you don't re-litigate or contradict it.
3. **Re-orientation after compression:** if the history looks summarized, do NOT trust your recollection of details. Re-read `todo__list`, and for plan-driven work re-read the plan statuses and the latest handoff in `plans/`. The summary tells you roughly where you were; the durable stores tell you exactly.
4. Do not hoard: run state is not knowledge. Never bloat `MEMORY.md` with orchestration state — one expiring drill file, cleaned up at run end.
## When to Do It Yourself vs Delegate ## When to Do It Yourself vs Delegate
**Do yourself**: trivial typos/renames, single-file changes you've already read, simple command execution, quick file searches you can express in one grep. **Do yourself**: trivial typos/renames, single-file changes you've already read, simple command execution, quick file searches you can express in one grep.
+11
View File
@@ -0,0 +1,11 @@
schemaVersion: '1'
kind: mixin
name: sisyphus-ddg
description: >
Allows Sisyphus to hit all domains since it utilizes the DuckDuckGo
MCP server. This allows the MCP server to actually perform web searches
on arbitrary domains and retrieve info for the agent.
network:
allowedDomains:
- '*'
+93
View File
@@ -0,0 +1,93 @@
# Step-Runner
A graph-based agent that executes **one step** of a phased implementation
plan, with the step protocol from the `step-implementation` skill enforced
as graph edges rather than prose. Designed to be delegated to by
**[Sisyphus](../sisyphus/README.md)**; delegates implementation to
**[Coder](../coder/README.md)** and independent review to
**[code-reviewer](../code-reviewer/README.md)**.
It expects a plan repo authored per the `plan-authoring` skill:
```
plans/
steps/NN-<slug>.md # step plans with frontmatter (step/title/depends_on/status)
handoffs/NN-<slug>.md # written by this agent, validated by a deterministic gate
NOTES.md # rolling durable facts
```
## Workflow
```
resolve_step (script) locate plan + previous handoff, check depends_on,
↓ mark plan in-progress [→ gate_blocked if deps unsatisfied]
orient (llm, read-only) merge handoff directives + staleness-check the plan
route_staleness (script) major deviation → gate_deviation (approval)
implement (agent → coder) coder runs its own build/test/self-review fix-loop
route_coder_result (script) COMPLETE → verify | REJECTED / FAILED → end
verify_format_lint (script) format BEFORE evidence, then lint
verify_build (script) step-level build/typecheck
verify_tests (script) FULL test suite
↓ [failures → fix_loop_gate, back-edge to implement]
edge_case_sweep (llm) missed edge cases; annotate downstream plans
↓ (Edge cases sections ONLY - scope changes become proposals)
route_sweep (script) 5+ files or architectural boundary → independent_review
independent_review (agent) code-reviewer; 🔴 findings loop back to implement (bounded)
write_handoff (llm) evidence-backed handoff per handoff-protocol + NOTES.md
check_handoff (script) deterministic schema gate; marks plan status complete
gate_user_review (approval) HARD STOP - approve, or send revision comments
↓ (revisions loop through implement → verify → handoff again)
end_success / end_blocked / end_rejected / end_failure
```
End nodes emit sentinel outcomes for the caller:
- `STEP_COMPLETE` — step implemented, verified, handoff written, user approved.
- `STEP_BLOCKED``depends_on` unsatisfied and the user declined to proceed.
- `STEP_REJECTED` — user aborted at the deviation gate, or the coder's plan
was rejected at its approval gate.
- `STEP_FAILED` — coder failed, the step-level fix budget was exhausted, or
the handoff failed validation twice.
## Usage
```sh
# From the project root: run the next in-progress/pending step
coyote -a step-runner "Execute the next step"
# A specific step (also parsed from the prompt: "execute step 3")
coyote -a step-runner --agent-variable step 3 "Execute step 3"
# Plan repo somewhere else
coyote -a step-runner --agent-variable plans_dir docs/plans "Execute the next step"
```
**Invoke from the project root.** The coder sub-agent resolves its own
`project_dir` from the invocation directory; overriding `project_dir` here
does not propagate to the spawned coder.
## Tuning
`graph.yaml` `initial_state` exposes:
- `max_fix_attempts` (default `2`) — step-level fix budget (the coder has
its own internal budget of 3).
- `max_review_attempts` (default `1`) — bounded 🔴-finding fix loops after
independent review.
Environment overrides honored by the script nodes:
- `FORMAT_CMD` / `LINT_CMD` — formatting and linting (otherwise a per-type
heuristic formats, and linting defers to the build/check command).
- `BUILD_CMD` / `TEST_CMD` — skip project-type detection (same as coder).
- `STEP_AUTOAPPROVE=1` — bypass the deviation gate (non-interactive runs).
- `STEP_SKIP_REVIEW=1` — never spawn the independent reviewer.
The final user approval gate is never bypassed by an environment variable -
it is the point of the workflow.
+606
View File
@@ -0,0 +1,606 @@
name: step-runner
description: |
Executes ONE step of a phased implementation plan (plans/ repo) with the
step protocol enforced as graph edges: orient -> staleness check ->
implement (coder) -> verify -> edge-case sweep -> optional independent
review -> evidence-backed handoff -> user approval gate. Designed to be
delegated to by sisyphus.
version: '1.0'
global_tools:
- ast_grep.sh
- fs_cat.sh
- fs_ls.sh
- fs_write.sh
- fs_patch.sh
- execute_command.sh
skills_enabled: true
enabled_skills:
- step-implementation
- handoff-protocol
- code-review
- ai-slop-remover
variables:
- name: project_dir
description: |
Absolute path to the project directory. Defaults to "." (the directory
coyote was invoked from). The coder sub-agent resolves its own
project_dir the same way, so invoke step-runner FROM the project root
unless you override this for both.
default: '.'
- name: plans_dir
description: |
Path to the plan repo. Relative paths resolve against project_dir.
Expected layout: <plans_dir>/steps/NN-<slug>.md,
<plans_dir>/handoffs/, <plans_dir>/NOTES.md.
default: 'plans'
- name: step
description: |
Which step to execute: a step number, or "next" to pick the first
in-progress (resume) or pending step plan.
default: 'next'
settings:
max_loop_iterations: 20
log_state_snapshots: true
validate_before_run: true
timeout: 7200
initial_state:
project_dir: ''
plans_dir: ''
step_number: 0
step_slug: ''
step_title: ''
step_plan_path: ''
step_plan: ''
prev_handoff_path: '(none)'
prev_handoff: '(none - this is the first step)'
notes_path: ''
notes: '(none)'
handoff_path: ''
blocking_reason: ''
plan_summary: ''
implementation_brief: ''
staleness_report: ''
has_major_deviation: false
deviation_summary: ''
user_feedback: ''
fix_instructions: ''
fix_attempts: 0
max_fix_attempts: 2
coder_result: ''
format_output: ''
lint_ok: true
lint_output: ''
build_ok: true
build_output: ''
tests_ok: true
tests_output: ''
edge_case_report: ''
downstream_updates: ''
needs_independent_review: false
review_report: ''
review_attempts: 0
max_review_attempts: 1
handoff_attempts: 0
handoff_fix: ''
step_summary: ''
start: resolve_step
nodes:
resolve_step:
id: resolve_step
type: script
description: |
Locate the step plan, previous handoff, and NOTES.md; parse frontmatter;
check depends_on satisfaction against existing handoffs; mark the plan
in-progress. Routes to gate_blocked when dependencies are unsatisfied.
script: scripts/resolve_step.sh
timeout: 30
fallback: end_failure
next: orient
gate_blocked:
id: gate_blocked
type: approval
description: Escalate unsatisfied dependencies instead of building on missing ground.
question: |
Step {{step_number}} ({{step_title}}) is BLOCKED:
{{blocking_reason}}
Proceed anyway?
options:
- 'yes'
- 'no'
routes:
'yes': orient
'no': end_blocked
on_other: end_blocked
orient:
id: orient
type: llm
description: |
Read-only orientation and staleness check: merge the previous handoff's
directives with the step plan, then verify the plan's assumptions
against the CURRENT codebase before any edit.
skills_enabled: true
enabled_skills:
- step-implementation
instructions: |
You are orienting for one step of a phased implementation plan. Load
`step-implementation` and apply its Orient and Staleness-check phases.
You are READ-ONLY in this node: no edits, no fixes.
1. Read the previous handoff (below). Note directives aimed at this
step, deviations that changed the codebase, and bare assertions
that need re-verification.
2. Staleness-check the step plan against the code at {{project_dir}}:
grep the symbols it references (via execute_command), read its
Context snippets at their claimed locations with fs_cat, confirm
its Test commands exist.
3. Classify discrepancies per the skill's deviation table: minor
(mechanics differ; correct silently in the brief) vs major (scope,
approach, interfaces, or a later step's assumptions affected).
Produce `implementation_brief`: the corrected, self-contained marching
orders for the implementer - plan tasks in order, handoff directives
applied, minor staleness corrections folded in, acceptance criteria
restated. The implementer sees ONLY the step plan plus your brief.
prompt: |
## Step plan ({{step_plan_path}})
{{step_plan}}
## Previous handoff ({{prev_handoff_path}})
{{prev_handoff}}
## Rolling project notes
{{notes}}
tools:
- fs_cat
- fs_ls
- execute_command
max_iterations: 20
output_schema:
type: object
properties:
plan_summary:
type: string
description: 1-3 sentences summarizing what this step delivers
implementation_brief:
type: string
description: Corrected, self-contained instructions for the implementer
staleness_report:
type: string
description: Findings from checking plan assumptions against current code; "clean" if none
has_major_deviation:
type: boolean
description: True when a discrepancy changes scope, approach, or interfaces
deviation_summary:
type: string
description: Major deviations only, with the plan claim vs current reality. Empty when none
required:
[
plan_summary,
implementation_brief,
staleness_report,
has_major_deviation,
deviation_summary,
]
fallback: end_failure
next: route_staleness
route_staleness:
id: route_staleness
type: script
description: Major deviation -> user gate; otherwise straight to implement.
script: scripts/route_staleness.sh
timeout: 5
fallback: implement
gate_deviation:
id: gate_deviation
type: approval
description: Major deviations are never silently absorbed - the user decides.
question: |
Step {{step_number}} ({{step_title}}): the plan no longer matches the
codebase in a way that changes scope or approach.
{{deviation_summary}}
Staleness report:
{{staleness_report}}
Proceed with the corrected brief? (Answer with anything else to give
your own guidance to the implementer.)
options:
- 'proceed'
- 'abort'
routes:
'proceed': implement
'abort': end_rejected
on_other: implement
state_updates:
user_feedback: '{{choice}}'
implement:
id: implement
type: agent
description: |
Delegate implementation to the coder graph agent, which runs its own
plan -> implement -> build -> tests -> self-review fix-loop internally.
agent: coder
prompt: |
## TASK
Execute step {{step_number}} ({{step_title}}) of a phased implementation
plan for the project at {{project_dir}}.
## EXPECTED OUTCOME
Every task in the step plan below is implemented and its acceptance
criteria are met. Tests are derived from the Acceptance criteria
section (not from the implementation). Build and full test suite pass.
## MUST DO
- Follow the Orientation brief below - it supersedes the raw plan where
they disagree (it folds in corrections from the staleness check).
- Match the patterns pasted in the step plan's Context section.
- Derive tests from the plan's Acceptance criteria.
## MUST NOT DO
- Do not touch anything listed in the plan's Out of scope section.
- Do not modify files under {{plans_dir}}.
- Do not implement work belonging to other steps.
## CONTEXT
### Step plan
{{step_plan}}
### Orientation brief (handoff directives + staleness corrections applied)
{{implementation_brief}}
### User guidance (if any)
{{user_feedback}}
### Fix loop status (empty on first attempt)
{{fix_instructions}}
timeout: 3600
state_updates:
coder_result: '{{output}}'
next: route_coder_result
route_coder_result:
id: route_coder_result
type: script
description: Route on the coder sentinel - COMPLETE verifies, REJECTED/FAILED terminate.
script: scripts/route_coder_result.sh
timeout: 5
fallback: end_failure
verify_format_lint:
id: verify_format_lint
type: script
description: |
Format BEFORE evidence collection (FORMAT_CMD override or per-type
heuristic), then lint (LINT_CMD, when configured). Lint failure routes
to the fix loop.
script: scripts/verify_format_lint.sh
timeout: 300
fallback: fix_loop_gate
verify_build:
id: verify_build
type: script
description: Step-level build/typecheck evidence, collected AFTER formatting.
script: scripts/verify_build.sh
timeout: 600
fallback: fix_loop_gate
verify_tests:
id: verify_tests
type: script
description: FULL test suite - regressions in untouched code fail the step too.
script: scripts/verify_tests.sh
timeout: 1200
fallback: fix_loop_gate
fix_loop_gate:
id: fix_loop_gate
type: script
description: |
Step-level fix budget (the coder already ran its own internal fix
loop). Loops to implement with fix_instructions, or ends as failure.
script: scripts/fix_loop_gate.sh
timeout: 5
fallback: end_failure
edge_case_sweep:
id: edge_case_sweep
type: llm
description: |
Post-implementation sweep: missed spots, edge cases, downstream plan
implications. May annotate downstream plans' Edge cases sections
(annotate vs propose per handoff-protocol). Also judges whether the
change warrants an independent review pass.
skills_enabled: true
enabled_skills:
- step-implementation
- handoff-protocol
instructions: |
The implementation for this step just passed build and tests. Load
`step-implementation` (edge-case sweep phase) and `handoff-protocol`
(annotate-vs-propose rules), then:
1. Read the changed code (the coder result below names the files).
Look for edge cases the plan missed: empty inputs, error paths,
concurrency, partial failure, compat.
2. For each edge case belonging to a LATER step: check that step's
plan under {{plans_dir}}/steps/. If its Edge cases section already
covers it, done. If not, append an entry to that section via
fs_patch - touch NOTHING else in the file.
3. NEVER edit a later plan's Objective, Tasks, Acceptance criteria,
or Out of scope. Scope-affecting changes become proposed diffs in
`downstream_updates` instead.
4. Set needs_independent_review=true when the change touched 5+ files
or crosses architectural boundaries (auth, public APIs, schema,
security-sensitive paths).
Be terse. Findings, not prose.
prompt: |
## Coder result
{{coder_result}}
## Step plan
{{step_plan}}
## Staleness report from orientation
{{staleness_report}}
tools:
- fs_cat
- fs_ls
- fs_patch
- execute_command
max_iterations: 20
output_schema:
type: object
properties:
edge_case_report:
type: string
description: Edge cases discovered - both handled and punted, one per line. "none" if empty
downstream_updates:
type: string
description: Annotations made (plan file + section) and proposed diffs for scope-affecting changes. "none" if empty
needs_independent_review:
type: boolean
required: [edge_case_report, downstream_updates, needs_independent_review]
fallback: write_handoff
next: route_sweep
route_sweep:
id: route_sweep
type: script
description: Broad or boundary-crossing changes get an independent reviewer.
script: scripts/route_sweep.sh
timeout: 5
fallback: write_handoff
independent_review:
id: independent_review
type: agent
description: Independent review pass - the author's self-review cannot catch its own rationalizations.
agent: code-reviewer
prompt: |
Review the changes produced for step {{step_number}} ({{step_title}})
of a phased implementation plan in {{project_dir}}.
What the step was supposed to do:
{{plan_summary}}
Coder summary (names the modified/created files):
{{coder_result}}
Review the changed files against the step plan's acceptance criteria.
Preserve severity tags in your findings.
timeout: 1200
state_updates:
review_report: '{{output}}'
next: route_review
route_review:
id: route_review
type: script
description: Critical findings loop back to implement (bounded); otherwise proceed to handoff.
script: scripts/route_review.sh
timeout: 5
fallback: write_handoff
write_handoff:
id: write_handoff
type: llm
description: |
Write the evidence-backed handoff per handoff-protocol and append
durable facts to NOTES.md. The completion gate (check_handoff)
verifies the document afterward.
skills_enabled: true
enabled_skills:
- handoff-protocol
- ai-slop-remover
instructions: |
Load `handoff-protocol` and follow its writer schema EXACTLY: the
frontmatter (step, title, result) and all eight sections, writing
"None" rather than omitting a section.
Write the handoff to {{handoff_path}} with fs_write. Paste the
verification evidence below verbatim into the Evidence section -
commands, exit codes, decisive output lines. Deviations come from the
staleness report, gate decisions, and fix loop history. Downstream
plan updates come from the sweep results.
Then append durable, step-independent facts (if any) to {{notes_path}}
- create the file if missing, never rewrite existing entries.
If "Gate feedback" below is non-empty, a previous handoff attempt
failed validation - fix exactly what it lists.
prompt: |
## Step
{{step_number}} ({{step_title}}) - plan at {{step_plan_path}}
## Plan summary
{{plan_summary}}
## Coder result
{{coder_result}}
## Staleness report / deviations
{{staleness_report}}
Major deviation summary (if any): {{deviation_summary}}
User guidance given (if any): {{user_feedback}}
Fix loop attempts used: {{fix_attempts}} of {{max_fix_attempts}}
## Edge cases discovered
{{edge_case_report}}
## Downstream plan updates
{{downstream_updates}}
## Independent review report (if any)
{{review_report}}
## Verification evidence (paste verbatim)
### Format
{{format_output}}
### Lint
{{lint_output}}
### Build
{{build_output}}
### Tests
{{tests_output}}
## Gate feedback
{{handoff_fix}}
tools:
- fs_cat
- fs_ls
- fs_write
- fs_patch
max_iterations: 15
output_schema:
type: object
properties:
step_summary:
type: string
description: 3-6 sentence summary of the step for the user's approval decision - what was done, deviations, anything needing their attention
required: [step_summary]
fallback: end_failure
next: check_handoff
check_handoff:
id: check_handoff
type: script
description: |
Deterministic completion gate - handoff exists with frontmatter and all
required sections. On success, marks the step plan status complete.
One retry back to write_handoff, then failure.
script: scripts/check_handoff.sh
timeout: 10
fallback: end_failure
gate_user_review:
id: gate_user_review
type: approval
description: The hard stop - the next step never starts without explicit approval.
question: |
## Step {{step_number}} ({{step_title}}) - ready for review
{{step_summary}}
Handoff: {{handoff_path}}
Build: {{build_ok}} | Tests: {{tests_ok}} | Fix attempts: {{fix_attempts}}/{{max_fix_attempts}}
Approve this step? (Answer with anything else to send revision
instructions straight to the implementer.)
options:
- 'approve'
- 'revise'
routes:
'approve': end_success
'revise': get_revision
on_other: revise_from_choice
state_updates:
user_feedback: '{{choice}}'
get_revision:
id: get_revision
type: input
description: Collect revision instructions, then loop back through implement -> verify -> handoff.
question: 'What should change? Your comments go to the implementer verbatim.'
validation: 'len(input) > 0'
state_updates:
fix_instructions: '{{input}}'
next: implement
revise_from_choice:
id: revise_from_choice
type: script
description: Free-form approval answers are treated as revision instructions.
script: scripts/revise_from_choice.sh
timeout: 5
fallback: get_revision
end_success:
id: end_success
type: end
output: |
STEP_COMPLETE
Step: {{step_number}} ({{step_title}})
Plan: {{step_plan_path}}
Handoff: {{handoff_path}}
Build: passed | Tests: passed | Fix attempts: {{fix_attempts}}/{{max_fix_attempts}}
{{step_summary}}
Downstream plan updates:
{{downstream_updates}}
end_blocked:
id: end_blocked
type: end
output: |
STEP_BLOCKED
Step: {{step_number}} ({{step_title}})
Reason:
{{blocking_reason}}
end_rejected:
id: end_rejected
type: end
output: |
STEP_REJECTED
Step: {{step_number}} ({{step_title}})
Rejected at: deviation gate or coder approval gate.
Deviation summary:
{{deviation_summary}}
Coder result (if it ran):
{{coder_result}}
end_failure:
id: end_failure
type: end
output: |
STEP_FAILED
Step: {{step_number}} ({{step_title}})
Fix attempts: {{fix_attempts}}/{{max_fix_attempts}}
Blocking reason (if resolution failed): {{blocking_reason}}
Coder result:
{{coder_result}}
Last build output:
{{build_output}}
Last tests output:
{{tests_output}}
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
set -uo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
handoff_path=$(echo "$state" | jq -r '.handoff_path // ""')
step_plan_path=$(echo "$state" | jq -r '.step_plan_path // ""')
handoff_attempts=$(echo "$state" | jq -r '.handoff_attempts // 0')
problems=""
if [[ ! -f "$handoff_path" ]]; then
problems="- handoff file does not exist at $handoff_path"$'\n'
else
content=$(cat "$handoff_path")
grep -qE '^result:[[:space:]]*(complete|partial|blocked)' <<< "$content" \
|| problems+="- frontmatter is missing 'result: complete|partial|blocked'"$'\n'
for section in "Summary" "Completed" "Not completed" "Deviations" "Downstream plan updates" "Edge cases discovered" "Evidence" "Notes for next step"; do
grep -qE "^##[[:space:]]+${section}" <<< "$content" \
|| problems+="- missing required section: ## ${section}"$'\n'
done
fi
if [[ -z "$problems" ]]; then
if [[ -f "$step_plan_path" ]]; then
tmp=$(mktemp)
awk 'BEGIN{n=0} /^---[[:space:]]*$/{n++; print; next} n==1 && /^status:/{print "status: complete"; next} {print}' "$step_plan_path" > "$tmp" && mv "$tmp" "$step_plan_path"
fi
jq -nc '{"handoff_fix": "", "_next": "gate_user_review"}'
exit 0
fi
if (( handoff_attempts >= 1 )); then
jq -nc \
--arg br "Handoff failed validation twice. Problems:
$problems" \
'{"blocking_reason": $br, "_next": "end_failure"}'
exit 0
fi
jq -nc \
--arg hf "The previous handoff attempt failed validation. Fix exactly these problems:
$problems" \
'{
"handoff_attempts": 1,
"handoff_fix": $hf,
"_next": "write_handoff"
}'
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
fix_attempts=$(echo "$state" | jq -r '.fix_attempts // 0')
max_fix_attempts=$(echo "$state" | jq -r '.max_fix_attempts // 2')
lint_ok=$(echo "$state" | jq -r '.lint_ok | if . == null then "true" else (. | tostring) end')
build_ok=$(echo "$state" | jq -r '.build_ok | if . == null then "true" else (. | tostring) end')
tests_ok=$(echo "$state" | jq -r '.tests_ok | if . == null then "true" else (. | tostring) end')
lint_output=$(echo "$state" | jq -r '.lint_output // ""')
build_output=$(echo "$state" | jq -r '.build_output // ""')
tests_output=$(echo "$state" | jq -r '.tests_output // ""')
if (( fix_attempts >= max_fix_attempts )); then
jq -nc \
--argjson n "$fix_attempts" \
'{
"fix_attempts": $n,
"_next": "end_failure"
}'
exit 0
fi
next_attempts=$((fix_attempts + 1))
if [[ "$lint_ok" != "true" ]]; then
stage="lint"
output="$lint_output"
elif [[ "$build_ok" != "true" ]]; then
stage="build"
output="$build_output"
elif [[ "$tests_ok" != "true" ]]; then
stage="full test suite"
output="$tests_output"
else
stage="verification"
output="fix_loop_gate was reached but no failing stage was recorded. Re-run verification."
fi
fix_instructions=$(printf '## Fix loop status (step-level attempt %d of %d)\n\nThe implementation passed the coder'"'"'s internal checks but failed step-level verification at the %s stage.\n\nOutput:\n```\n%s\n```\n\nIdentify the minimal fix and apply it. Do not refactor. Regressions in untouched code caused by this change are in scope.' \
"$next_attempts" "$max_fix_attempts" "$stage" "$output")
jq -nc \
--argjson n "$next_attempts" \
--arg 'fi' "$fix_instructions" \
'{
"fix_attempts": $n,
"fix_instructions": $fi,
"lint_ok": true,
"build_ok": true,
"tests_ok": true,
"_next": "implement"
}'
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env bash
set -uo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
fail() {
jq -nc --arg r "$1" '{"blocking_reason": $r, "_next": "end_failure"}'
exit 0
}
project_dir="${LLM_AGENT_VAR_PROJECT_DIR:-.}"
project_dir=$(cd "$project_dir" 2>/dev/null && pwd) || fail "project_dir does not exist: $project_dir"
plans_dir="${LLM_AGENT_VAR_PLANS_DIR:-plans}"
[[ "$plans_dir" != /* ]] && plans_dir="$project_dir/$plans_dir"
steps_dir="$plans_dir/steps"
handoffs_dir="$plans_dir/handoffs"
notes_path="$plans_dir/NOTES.md"
[[ -d "$steps_dir" ]] || fail "No step plans directory at $steps_dir (expected <plans_dir>/steps/NN-<slug>.md)"
frontmatter() {
awk '/^---[[:space:]]*$/{n++; next} n==1{print} n>=2{exit}' "$1"
}
fm_value() {
echo "$1" | grep -E "^$2:" | head -1 | sed -E "s/^$2:[[:space:]]*//" | sed -E 's/^["'"'"']|["'"'"']$//g'
}
step="${LLM_AGENT_VAR_STEP:-next}"
if [[ "$step" == "next" ]]; then
prompt_step=$(echo "$state" | jq -r '.initial_prompt // ""' | grep -oiE 'step[[:space:]#:]*[0-9]+' | head -1 | grep -oE '[0-9]+' || true)
[[ -n "$prompt_step" ]] && step="$prompt_step"
fi
plan_file=""
if [[ "$step" == "next" ]]; then
first_pending=""
while IFS= read -r f; do
st=$(fm_value "$(frontmatter "$f")" "status")
if [[ "$st" == "in-progress" ]]; then
plan_file="$f"
break
fi
[[ -z "$first_pending" && ( "$st" == "pending" || -z "$st" ) ]] && first_pending="$f"
done < <(find "$steps_dir" -maxdepth 1 -name '*.md' | sort)
[[ -z "$plan_file" ]] && plan_file="$first_pending"
[[ -z "$plan_file" ]] && fail "No in-progress or pending step plans in $steps_dir"
else
[[ "$step" =~ ^[0-9]+$ ]] || fail "step must be a number or 'next'; got: $step"
padded=$(printf '%02d' "$((10#$step))")
plan_file=$(find "$steps_dir" -maxdepth 1 \( -name "${padded}-*.md" -o -name "${step}-*.md" \) | sort | head -1)
[[ -n "$plan_file" ]] || fail "No step plan matching step $step in $steps_dir"
fi
bn=$(basename "$plan_file" .md)
num_part="${bn%%-*}"
[[ "$num_part" =~ ^[0-9]+$ ]] || fail "Step plan filename must start with a number: $bn"
step_number=$((10#$num_part))
step_slug="${bn#*-}"
fm=$(frontmatter "$plan_file")
step_title=$(fm_value "$fm" "title")
[[ -z "$step_title" ]] && step_title="$step_slug"
deps=$(echo "$fm" | awk '/^depends_on:/{f=1; print; next} f && /^[[:space:]]*-/{print; next} f{exit}' | grep -oE '[0-9]+' || true)
unsatisfied=""
for dep in $deps; do
dep_padded=$(printf '%02d' "$((10#$dep))")
dep_handoff=$(find "$handoffs_dir" -maxdepth 1 \( -name "${dep_padded}-*.md" -o -name "${dep}-*.md" \) 2>/dev/null | sort | head -1)
if [[ -z "$dep_handoff" ]]; then
unsatisfied+="- step $dep: no handoff found (step not executed?)"$'\n'
continue
fi
dep_result=$(fm_value "$(frontmatter "$dep_handoff")" "result")
if [[ "$dep_result" != "complete" ]]; then
unsatisfied+="- step $dep: handoff result is '$dep_result' (not complete): $dep_handoff"$'\n'
fi
done
prev_handoff_path="(none)"
prev_handoff="(none - this is the first step)"
prev_file=""
prev_num=0
while IFS= read -r h; do
hn="${h##*/}"
hn="${hn%%-*}"
[[ "$hn" =~ ^[0-9]+$ ]] || continue
n=$((10#$hn))
if (( n < step_number && n >= prev_num )); then
prev_num=$n
prev_file="$h"
fi
done < <(find "$handoffs_dir" -maxdepth 1 -name '*.md' 2>/dev/null | sort)
if [[ -n "$prev_file" ]]; then
prev_handoff_path="$prev_file"
prev_handoff=$(head -c 16000 "$prev_file")
fi
notes="(none)"
[[ -f "$notes_path" ]] && notes=$(head -c 8000 "$notes_path")
step_plan=$(head -c 24000 "$plan_file")
handoff_path="$handoffs_dir/$(basename "$plan_file")"
tmp=$(mktemp)
awk 'BEGIN{n=0} /^---[[:space:]]*$/{n++; print; next} n==1 && /^status:/{print "status: in-progress"; next} {print}' "$plan_file" > "$tmp" && mv "$tmp" "$plan_file"
next_node="orient"
blocking_reason=""
if [[ -n "$unsatisfied" ]]; then
next_node="gate_blocked"
blocking_reason="Unsatisfied dependencies:"$'\n'"$unsatisfied"
fi
jq -nc \
--arg pd "$project_dir" \
--arg pl "$plans_dir" \
--argjson sn "$step_number" \
--arg ss "$step_slug" \
--arg st "$step_title" \
--arg spp "$plan_file" \
--arg sp "$step_plan" \
--arg php "$prev_handoff_path" \
--arg ph "$prev_handoff" \
--arg np "$notes_path" \
--arg no "$notes" \
--arg hp "$handoff_path" \
--arg br "$blocking_reason" \
--arg nx "$next_node" \
'{
"project_dir": $pd,
"plans_dir": $pl,
"step_number": $sn,
"step_slug": $ss,
"step_title": $st,
"step_plan_path": $spp,
"step_plan": $sp,
"prev_handoff_path": $php,
"prev_handoff": $ph,
"notes_path": $np,
"notes": $no,
"handoff_path": $hp,
"blocking_reason": $br,
"_next": $nx
}'
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
feedback=$(echo "$state" | jq -r '.user_feedback // ""')
if [[ -z "$feedback" ]]; then
jq -nc '{"_next": "get_revision"}'
exit 0
fi
fix_instructions=$(printf '## Revision requested by the user at the step approval gate\n\nAddress these comments with minimal edits, then the step re-verifies and the handoff is rewritten:\n\n%s' \
"$feedback")
jq -nc \
--arg 'fi' "$fix_instructions" \
'{
"fix_instructions": $fi,
"_next": "implement"
}'
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
coder_result=$(echo "$state" | jq -r '.coder_result // ""')
case "$coder_result" in
*CODER_COMPLETE*)
jq -nc '{"_next": "verify_format_lint"}'
;;
*CODER_REJECTED*)
jq -nc '{"_next": "end_rejected"}'
;;
*CODER_FAILED*)
jq -nc '{"blocking_reason": "coder fix-loop exhausted; see coder result", "_next": "end_failure"}'
;;
*)
jq -nc '{"blocking_reason": "coder returned no recognizable sentinel (expected CODER_COMPLETE / CODER_REJECTED / CODER_FAILED)", "_next": "end_failure"}'
;;
esac
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
review_report=$(echo "$state" | jq -r '.review_report // ""')
review_attempts=$(echo "$state" | jq -r '.review_attempts // 0')
max_review_attempts=$(echo "$state" | jq -r '.max_review_attempts // 1')
if ! grep -qF "🔴" <<< "$review_report"; then
jq -nc '{"_next": "write_handoff"}'
exit 0
fi
if (( review_attempts >= max_review_attempts )); then
jq -nc '{"_next": "write_handoff"}'
exit 0
fi
next_review=$((review_attempts + 1))
fix_instructions=$(printf '## Independent review findings (attempt %d of %d)\n\nAn independent reviewer flagged CRITICAL (🔴) findings. Address ONLY the 🔴 findings with minimal edits. Do not refactor unrelated code.\n\n%s' \
"$next_review" "$max_review_attempts" "$review_report")
jq -nc \
--argjson n "$next_review" \
--arg 'fi' "$fix_instructions" \
'{
"review_attempts": $n,
"fix_instructions": $fi,
"needs_independent_review": false,
"_next": "implement"
}'
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
has_major=$(echo "$state" | jq -r '.has_major_deviation // false')
if [[ "${STEP_AUTOAPPROVE:-0}" == "1" ]]; then
jq -nc '{"_next": "implement"}'
exit 0
fi
if [[ "$has_major" == "true" ]]; then
jq -nc '{"_next": "gate_deviation"}'
else
jq -nc '{"_next": "implement"}'
fi
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
needs_review=$(echo "$state" | jq -r '.needs_independent_review // false')
if [[ "${STEP_SKIP_REVIEW:-0}" == "1" ]]; then
jq -nc '{"_next": "write_handoff"}'
exit 0
fi
if [[ "$needs_review" == "true" ]]; then
jq -nc '{"_next": "independent_review"}'
else
jq -nc '{"_next": "write_handoff"}'
fi
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -uo pipefail
# shellcheck disable=SC1091
source "$(dirname "$0")/../../.shared/utils.sh"
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
project_dir=$(echo "$state" | jq -r '.project_dir // "."')
if [[ -n "${BUILD_CMD:-}" ]]; then
cmd="$BUILD_CMD"
else
project_info=$(detect_project "$project_dir")
cmd=$(echo "$project_info" | jq -r '.check // .build // ""')
fi
if [[ -z "$cmd" || "$cmd" == "null" ]]; then
jq -nc '{
"build_ok": true,
"build_output": "(no build/check command available for this project type)",
"_next": "verify_tests"
}'
exit 0
fi
exit_code=0
output=$(cd "$project_dir" && eval "$cmd" 2>&1) || exit_code=$?
if (( exit_code == 0 )); then
jq -nc \
--arg out "Ran: $cmd
$output" \
'{
"build_ok": true,
"build_output": $out,
"_next": "verify_tests"
}'
else
jq -nc \
--arg out "Ran: $cmd
Exit code: $exit_code
$output" \
'{
"build_ok": false,
"build_output": $out,
"_next": "fix_loop_gate"
}'
fi
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
set -uo pipefail
# shellcheck disable=SC1091
source "$(dirname "$0")/../../.shared/utils.sh"
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
project_dir=$(echo "$state" | jq -r '.project_dir // "."')
project_type=$(detect_project "$project_dir" | jq -r '.type // "unknown"')
format_cmd="${FORMAT_CMD:-}"
if [[ -z "$format_cmd" ]]; then
case "$project_type" in
rust) format_cmd="cargo fmt" ;;
go) format_cmd="gofmt -w ." ;;
python) command -v ruff &>/dev/null && format_cmd="ruff format ." ;;
esac
fi
if [[ -z "$format_cmd" ]]; then
format_output="(no format command configured for project type '$project_type'; skipped. Set FORMAT_CMD to enable.)"
else
fmt_rc=0
fmt_out=$(cd "$project_dir" && eval "$format_cmd" 2>&1) || fmt_rc=$?
format_output="Ran: $format_cmd
Exit code: $fmt_rc
$fmt_out"
fi
lint_cmd="${LINT_CMD:-}"
if [[ -z "$lint_cmd" ]]; then
jq -nc \
--arg fo "$format_output" \
'{
"format_output": $fo,
"lint_ok": true,
"lint_output": "(no LINT_CMD configured; linting is covered by the build/check command)",
"_next": "verify_build"
}'
exit 0
fi
lint_rc=0
lint_out=$(cd "$project_dir" && eval "$lint_cmd" 2>&1) || lint_rc=$?
if (( lint_rc == 0 )); then
jq -nc \
--arg fo "$format_output" \
--arg lo "Ran: $lint_cmd
$lint_out" \
'{
"format_output": $fo,
"lint_ok": true,
"lint_output": $lo,
"_next": "verify_build"
}'
else
jq -nc \
--arg fo "$format_output" \
--arg lo "Ran: $lint_cmd
Exit code: $lint_rc
$lint_out" \
'{
"format_output": $fo,
"lint_ok": false,
"lint_output": $lo,
"_next": "fix_loop_gate"
}'
fi
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -uo pipefail
# shellcheck disable=SC1091
source "$(dirname "$0")/../../.shared/utils.sh"
if [[ -n "${GRAPH_STATE_FILE:-}" ]]; then
state=$(cat "$GRAPH_STATE_FILE")
elif [[ -n "${GRAPH_STATE:-}" ]]; then
state="$GRAPH_STATE"
else
state='{}'
fi
project_dir=$(echo "$state" | jq -r '.project_dir // "."')
if [[ -n "${TEST_CMD:-}" ]]; then
cmd="$TEST_CMD"
else
project_info=$(detect_project "$project_dir")
cmd=$(echo "$project_info" | jq -r '.test // ""')
fi
if [[ -z "$cmd" || "$cmd" == "null" ]]; then
jq -nc '{
"tests_ok": true,
"tests_output": "(no test command available for this project type)",
"_next": "edge_case_sweep"
}'
exit 0
fi
exit_code=0
output=$(cd "$project_dir" && eval "$cmd" 2>&1) || exit_code=$?
if (( exit_code == 0 )); then
jq -nc \
--arg out "Ran: $cmd
$output" \
'{
"tests_ok": true,
"tests_output": $out,
"_next": "edge_case_sweep"
}'
else
jq -nc \
--arg out "Ran: $cmd
Exit code: $exit_code
$output" \
'{
"tests_ok": false,
"tests_output": $out,
"_next": "fix_loop_gate"
}'
fi
+5
View File
@@ -18,6 +18,11 @@
"type": "stdio", "type": "stdio",
"command": "uvx", "command": "uvx",
"args": ["duckduckgo-mcp-server"] "args": ["duckduckgo-mcp-server"]
},
"iwe": {
"type": "stdio",
"command": "iwec",
"args": ["--project", "."]
} }
} }
} }
+44
View File
@@ -0,0 +1,44 @@
schemaVersion: "1"
kind: mixin
name: built-in-tools
description: >
Installs binaries and allows network domains required by Coyote's built-in
global tools and the default MCP server set. Auto-applied by Coyote's sbx
mixin discovery when running `coyote --sandbox`.
network:
allowedDomains:
# fetch_url_via_jina + jina reader fallback
- "r.jina.ai:443"
# get_current_weather (.sh, .py, .ts)
- "wttr.in:443"
# search_arxiv (the .sh tool still uses http://, so :80 is required until fixed)
- "export.arxiv.org:443"
- "export.arxiv.org:80"
# search_arxiv + search_wikipedia may follow DOI redirects
- "doi.org:443"
# search_wikipedia
- "en.wikipedia.org:443"
# search_wolframalpha
- "api.wolframalpha.com:443"
# web_search_perplexity
- "api.perplexity.ai:443"
# web_search_tavily
- "api.tavily.com:443"
# send_twilio
- "api.twilio.com:443"
# MCP: github (built-in mcp.json: api.githubcopilot.com)
- "api.githubcopilot.com:443"
# MCP: atlassian (built-in mcp.json: mcp-remote -> mcp.atlassian.com)
- "mcp.atlassian.com:443"
# MCP: ddg-search (built-in mcp.json: uvx duckduckgo-mcp-server)
- "duckduckgo.com:443"
- "html.duckduckgo.com:443"
- "lite.duckduckgo.com:443"
# MCP: npx-based servers (mcp-remote) pull from npm
- "registry.npmjs.org:443"
# MCP: docker server may pull images from common registries
- "ghcr.io:443"
- "registry-1.docker.io:443"
- "auth.docker.io:443"
- "production.cloudflare.docker.com:443"
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env bash
set -e
# @describe Structural code search using AST patterns (ast-grep). Matches syntax trees, not text,
# so it finds code regardless of formatting: function calls with any arguments, definitions, etc.
# Use meta-variables in patterns: $NAME matches one AST node, $$$ matches zero or more nodes.
# Patterns must be COMPLETE, valid AST nodes in the target language: 'fn $NAME($$$) { $$$ }'
# matches Rust fn definitions (with body - 'fn $NAME($$$)' alone parses as nothing and matches
# nothing), 'foo($$$)' matches all calls to foo, '$X.unwrap()' matches all unwrap calls.
# Prefer this over fs_grep when searching for code STRUCTURE (calls, definitions, signatures);
# use fs_grep for plain text, comments, or strings.
# @option --pattern! The AST pattern to search for (must parse as valid code in the target language)
# @option --lang The target language (e.g. rust, typescript, tsx, javascript, python, go, java, c, cpp, kotlin, swift, ruby, php, css, html, yaml, json). Strongly recommended; without it files of every supported language are scanned
# @option --path The directory OR file to search in (defaults to current working directory)
# @option --glob File glob to narrow the search (e.g. "src/**/*.rs", "!**/tests/**")
# @env LLM_OUTPUT=/dev/stdout The output path
MAX_RESULTS=100
MAX_OUTPUT_BYTES=32768
resolve_binary() {
if command -v ast-grep &>/dev/null; then
echo "ast-grep"
return 0
fi
if command -v sg &>/dev/null && sg --version 2>/dev/null | grep -qi 'ast-grep'; then
echo "sg"
return 0
fi
return 1
}
main() {
# shellcheck disable=SC2154
local pattern="$argc_pattern"
local lang="${argc_lang:-}"
local search_path="${argc_path:-.}"
local glob="${argc_glob:-}"
local bin
if ! bin=$(resolve_binary); then
printf 'ast-grep is not installed. Fall back to fs_grep for this search.\nTo enable structural search, install ast-grep:\n cargo install ast-grep --locked\n brew install ast-grep\n npm i -g @ast-grep/cli\n' >> "$LLM_OUTPUT"
return 0
fi
if [[ ! -e "$search_path" ]]; then
echo "Error: path not found: $search_path" >> "$LLM_OUTPUT"
return 1
fi
local args=(run --pattern "$pattern" --color never --heading never)
[[ -n "$lang" ]] && args+=(--lang "$lang")
[[ -n "$glob" ]] && args+=(--globs "$glob")
args+=("$search_path")
local output exit_code=0
output=$("$bin" "${args[@]}" 2>&1) || exit_code=$?
if [[ -z "$output" ]]; then
echo "No structural matches found for: $pattern" >> "$LLM_OUTPUT"
return 0
fi
if (( exit_code > 1 )); then
printf 'ast-grep failed (exit %s):\n%s\n\nHint: the pattern must be valid %s syntax. Meta-variables: $NAME (one node), $$$ (zero or more).\n' \
"$exit_code" "$output" "${lang:-source}" >> "$LLM_OUTPUT"
return 0
fi
local total
total=$(wc -l <<< "$output")
output=$(head -n "$MAX_RESULTS" <<< "$output" | head -c "$MAX_OUTPUT_BYTES")
echo "$output" >> "$LLM_OUTPUT"
if (( total > MAX_RESULTS )); then
printf '\n(Showing %s of %s matching lines. Narrow with --glob, --lang, or a more specific pattern.)\n' \
"$MAX_RESULTS" "$total" >> "$LLM_OUTPUT"
fi
}
+9 -1
View File
@@ -10,5 +10,13 @@ set -e
main() { main() {
# shellcheck disable=SC2154 # shellcheck disable=SC2154
cat "$argc_path" >> "$LLM_OUTPUT" 2>&1 || echo "No such file or path: $argc_path" >> "$LLM_OUTPUT" local path="$argc_path"
# An empty result is shown to the model as the opaque literal "DONE"; emit a note instead.
if [[ -f "$path" && ! -s "$path" ]]; then
echo "(empty file: $path)" >> "$LLM_OUTPUT"
return 0
fi
cat "$path" >> "$LLM_OUTPUT" 2>&1 || echo "No such file or path: $path" >> "$LLM_OUTPUT"
} }
+2 -2
View File
@@ -17,8 +17,8 @@ main() {
local search_path="${argc_path:-.}" local search_path="${argc_path:-.}"
if [[ ! -d "$search_path" ]]; then if [[ ! -d "$search_path" ]]; then
echo "Error: directory not found: $search_path" >> "$LLM_OUTPUT" echo "Error: directory not found: $search_path" >&2
return 1 exit 1
fi fi
local results local results
+2 -2
View File
@@ -21,8 +21,8 @@ main() {
local include_filter="${argc_include:-}" local include_filter="${argc_include:-}"
if [[ ! -e "$search_path" ]]; then if [[ ! -e "$search_path" ]]; then
echo "Error: path not found: $search_path" >> "$LLM_OUTPUT" echo "Error: path not found: $search_path" >&2
return 1 exit 1
fi fi
local grep_args=(-nH --color=never) local grep_args=(-nH --color=never)
+14 -1
View File
@@ -9,5 +9,18 @@ set -e
main() { main() {
# shellcheck disable=SC2154 # shellcheck disable=SC2154
ls -1 "$argc_path" >> "$LLM_OUTPUT" 2>&1 || echo "No such path: $argc_path" >> "$LLM_OUTPUT" local path="$argc_path"
local output
if ! output=$(ls -1 "$path" 2>&1); then
echo "$output" >> "$LLM_OUTPUT"
return 0
fi
# An empty result is shown to the model as the opaque literal "DONE"; emit a note instead.
if [[ -z "$output" ]]; then
echo "(empty directory: $path)" >> "$LLM_OUTPUT"
else
echo "$output" >> "$LLM_OUTPUT"
fi
} }
+17
View File
@@ -5,6 +5,23 @@ set -e
# PREFERRED way to modify a file. Prefer this over fs_write whenever the file already exists: it sends less data, # PREFERRED way to modify a file. Prefer this over fs_write whenever the file already exists: it sends less data,
# preserves unchanged content automatically, and is less prone to accidental data loss from full rewrites. # preserves unchanged content automatically, and is less prone to accidental data loss from full rewrites.
# Use fs_write only when you are creating a new file or doing a complete rewrite where most of the content changes. # Use fs_write only when you are creating a new file or doing a complete rewrite where most of the content changes.
#
# CRITICAL — the patch is matched byte-for-byte. There is no fuzzy matching, no whitespace tolerance, and no context shift:
# - Context lines (prefixed with a single space) and removed lines (prefixed with '-') must equal the file content exactly.
# If unsure, fs_cat the file first and copy the bytes verbatim into your patch.
# - JSON-escape the contents string ONCE. Each literal backslash in the file becomes \\ in the JSON contents string. So a
# shell line containing s|\\"|"|g must appear in JSON as s|\\\\\"|\"|g — NOT s|\\\\\\\"|\\\"|g. Over-escaping backslashes
# is the most common cause of "unable to apply patch" failures, especially in files with sed/jq/regex pipelines or
# embedded Python with quoted strings.
# - Hunks are applied in order; the first hunk that fails aborts the whole patch — later hunks are NOT attempted.
# - If you've edited this file in earlier tool calls, fs_cat it again before composing the patch. A stale view of the file
# produces context lines that no longer match.
# - On failure the error message names the failing hunk and shows the expected-vs-actual line. Fix that specific line and
# retry — do not blindly resend a near-identical patch.
#
# For files with heavy escaping (sed/jq/regex pipelines, shell with embedded heredocs, deeply quoted strings), prefer
# fs_write over chained fs_patch hunks to replace the entire file with the full new contents (i.e. original content +
# your changes).
# @option --path! The path of the file to apply the patch to # @option --path! The path of the file to apply the patch to
# @option --contents! The patch to apply to the file # @option --contents! The patch to apply to the file
+18 -6
View File
@@ -8,8 +8,8 @@ set -e
# Use the grep tool to find specific content before reading, then read with offset to target the relevant section. # Use the grep tool to find specific content before reading, then read with offset to target the relevant section.
# @option --path! The absolute path to the file or directory to read # @option --path! The absolute path to the file or directory to read
# @option --offset The line number to start reading from (1-indexed, default: 1) # @option --offset <INT> The line number to start reading from (1-indexed, default: 1)
# @option --limit The maximum number of lines to read (default: 2000) # @option --limit <INT> The maximum number of lines to read (default: 2000)
# @env LLM_OUTPUT=/dev/stdout The output path # @env LLM_OUTPUT=/dev/stdout The output path
@@ -23,8 +23,8 @@ main() {
local limit="${argc_limit:-2000}" local limit="${argc_limit:-2000}"
if [[ ! -e "$target" ]]; then if [[ ! -e "$target" ]]; then
echo "Error: path not found: $target" >> "$LLM_OUTPUT" echo "Error: path not found: $target" >&2
return 1 exit 1
fi fi
if [[ -d "$target" ]]; then if [[ -d "$target" ]]; then
@@ -33,9 +33,20 @@ main() {
fi fi
local total_lines file_bytes local total_lines file_bytes
total_lines=$(wc -l < "$target" 2>/dev/null || echo 0) # awk counts a final line that lacks a trailing newline; wc -l would undercount it by one.
total_lines=$(awk 'END { print NR }' "$target" 2>/dev/null || echo 0)
file_bytes=$(wc -c < "$target" 2>/dev/null || echo 0) file_bytes=$(wc -c < "$target" 2>/dev/null || echo 0)
if [[ "$total_lines" -eq 0 ]]; then
echo "(file is empty: $target)" >> "$LLM_OUTPUT"
return 0
fi
if [[ "$offset" -gt "$total_lines" ]]; then
echo "(offset $offset is past the end of the file, which has $total_lines lines)" >> "$LLM_OUTPUT"
return 0
fi
if [[ "$file_bytes" -gt "$MAX_BYTES" ]] && [[ "$offset" -eq 1 ]] && [[ "$limit" -ge 2000 ]]; then if [[ "$file_bytes" -gt "$MAX_BYTES" ]] && [[ "$offset" -eq 1 ]] && [[ "$limit" -ge 2000 ]]; then
{ {
echo "Warning: Large file (${file_bytes} bytes, ${total_lines} lines). Showing first ${limit} lines." echo "Warning: Large file (${file_bytes} bytes, ${total_lines} lines). Showing first ${limit} lines."
@@ -48,7 +59,8 @@ main() {
sed -n "${offset},${end_line}p" "$target" 2>/dev/null | { sed -n "${offset},${end_line}p" "$target" 2>/dev/null | {
local line_num=$offset local line_num=$offset
while IFS= read -r line; do # `|| [[ -n "$line" ]]` keeps the final line when the file has no trailing newline.
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ ${#line} -gt $MAX_LINE_LENGTH ]]; then if [[ ${#line} -gt $MAX_LINE_LENGTH ]]; then
line="${line:0:$MAX_LINE_LENGTH}... (truncated)" line="${line:0:$MAX_LINE_LENGTH}... (truncated)"
fi fi
+43 -3
View File
@@ -507,7 +507,9 @@ open_link() {
guard_operation() { guard_operation() {
if [[ -z "$AUTO_CONFIRM" && -z "$LLM_AGENT_VAR_AUTO_CONFIRM" ]]; then if [[ -z "$AUTO_CONFIRM" && -z "$LLM_AGENT_VAR_AUTO_CONFIRM" ]]; then
ans="$(confirm "${1:-Are you sure you want to continue?}")" # 2>/dev/tty: keep the prompt off the host-captured stderr pipe so it
# can't leak into tool_call_error JSON when the wrapped command fails.
ans="$(confirm "${1:-Are you sure you want to continue?}" 2>/dev/tty)"
if [[ "$ans" == 0 ]]; then if [[ "$ans" == 0 ]]; then
error "Operation aborted!" 2>&1 error "Operation aborted!" 2>&1
@@ -550,7 +552,7 @@ patch_file() {
continue continue
} }
if (line ~ /^@@ /) { if (line ~ /^@@/) {
mode = "hunk" mode = "hunk"
hunkIndex++ hunkIndex++
patchLineIndex++ patchLineIndex++
@@ -583,6 +585,10 @@ patch_file() {
if (hunkIndex == 0) { if (hunkIndex == 0) {
print "error: no patch" > "/dev/stderr" print "error: no patch" > "/dev/stderr"
print "" > "/dev/stderr"
print "No hunk header was found. Each hunk must start with a line beginning \"@@\"" > "/dev/stderr"
print "(for example \"@@ ... @@\" or \"@@ -1,4 +1,4 @@\"). Inside a hunk, context lines" > "/dev/stderr"
print "start with a single space, removed lines with \"-\", and added lines with \"+\"." > "/dev/stderr"
exit 1 exit 1
} }
@@ -598,6 +604,14 @@ patch_file() {
for (i = 2; i <= hunkTotalOriginalLines[hunkIndex]; i++) { for (i = 2; i <= hunkTotalOriginalLines[hunkIndex]; i++) {
if (lines[nextLineIndex] != hunkOriginalLines[hunkIndex,i]) { if (lines[nextLineIndex] != hunkOriginalLines[hunkIndex,i]) {
if (i - 1 > bestPartialLen[hunkIndex]) {
bestPartialLen[hunkIndex] = i - 1
bestPartialAnchorLine[hunkIndex] = lineIndex
bestPartialHunkPos[hunkIndex] = i
bestPartialDivergeLine[hunkIndex] = nextLineIndex
bestPartialExpected[hunkIndex] = hunkOriginalLines[hunkIndex,i]
bestPartialActual[hunkIndex] = lines[nextLineIndex]
}
nextLineIndex = 0 nextLineIndex = 0
break break
} }
@@ -619,7 +633,32 @@ patch_file() {
} }
if (hunkIndex != totalHunks + 1) { if (hunkIndex != totalHunks + 1) {
failingHunk = hunkIndex
print "error: unable to apply patch" > "/dev/stderr" print "error: unable to apply patch" > "/dev/stderr"
print "" > "/dev/stderr"
print "Hunk " failingHunk " of " totalHunks " did not match the file." > "/dev/stderr"
if (bestPartialLen[failingHunk] == 0) {
print "" > "/dev/stderr"
print "The first context/removed line of hunk " failingHunk " was not found anywhere in the file:" > "/dev/stderr"
print " expected: " hunkOriginalLines[failingHunk, 1] > "/dev/stderr"
} else {
print "" > "/dev/stderr"
print "Closest match: anchored at file line " bestPartialAnchorLine[failingHunk] ", matched " bestPartialLen[failingHunk] " of " hunkTotalOriginalLines[failingHunk] " original lines before diverging." > "/dev/stderr"
print "" > "/dev/stderr"
print "At file line " bestPartialDivergeLine[failingHunk] " (hunk original line " bestPartialHunkPos[failingHunk] "):" > "/dev/stderr"
print " expected: " bestPartialExpected[failingHunk] > "/dev/stderr"
print " actual: " bestPartialActual[failingHunk] > "/dev/stderr"
}
print "" > "/dev/stderr"
print "Lines must match byte-for-byte (no fuzzy matching). Check escaping, whitespace, and quoting." > "/dev/stderr"
if (failingHunk < totalHunks) {
print "" > "/dev/stderr"
print (totalHunks - failingHunk) " subsequent hunk(s) were not attempted (patcher aborts on first failure)." > "/dev/stderr"
}
exit 1 exit 1
} }
} }
@@ -657,7 +696,8 @@ guard_path() {
confirmation_prompt="$2" confirmation_prompt="$2"
if [[ ! "$path" == "$(pwd)"* && -z "$AUTO_CONFIRM" && -z "$LLM_AGENT_VAR_AUTO_CONFIRM" ]]; then if [[ ! "$path" == "$(pwd)"* && -z "$AUTO_CONFIRM" && -z "$LLM_AGENT_VAR_AUTO_CONFIRM" ]]; then
ans="$(confirm "$confirmation_prompt")" # 2>/dev/tty: see guard_operation — prevents prompt text leaking via captured stderr.
ans="$(confirm "$confirmation_prompt" 2>/dev/tty)"
if [[ "$ans" == 0 ]]; then if [[ "$ans" == 0 ]]; then
error "Operation aborted!" >&2 error "Operation aborted!" >&2
+3
View File
@@ -1,3 +1,6 @@
---
skills_enabled: false
---
As a professional Prompt Engineer, your role is to create effective and innovative prompts for interacting with AI models. As a professional Prompt Engineer, your role is to create effective and innovative prompts for interacting with AI models.
Your core skills include: Your core skills include:
+3
View File
@@ -1,3 +1,6 @@
---
skills_enabled: false
---
Create a concise, 3-6 word title. Create a concise, 3-6 word title.
**Notes**: **Notes**:
+96
View File
@@ -0,0 +1,96 @@
---
name: diagnose
enabled_tools:
- execute_command
- fs_cat
- fs_ls
- web_search_coyote
skills_enabled: false
auto_continue: true
max_auto_continues: 10
---
You are an expert systems troubleshooter: equal parts SRE, sysadmin, network engineer, and homelab tinkerer. Your job
is to diagnose and fix technical problems of any kind: services that won't start, networking failures, container
issues, driver problems, permission errors, misbehaving hardware, broken configs, or anything else. You are not limited
to code.
<system>
os: {{__os__}}
distro: {{__os_distro__}}
arch: {{__arch__}}
shell: {{__shell__}}
cwd: {{__cwd__}}
now: {{__now__}}
</system>
## Prime Directive
**You run the diagnostics yourself.** Never tell the user to run a command and paste the output back. Use the
`execute_command` tool to gather evidence directly, then interpret the results for them. The user should watch you
work, not act as your terminal.
## Diagnostic Loop
Work the loop until the problem is solved or genuinely blocked:
1. **Reproduce & observe.** Run the failing thing (or inspect its state) to see the actual error with your own eyes.
Never diagnose from the user's paraphrase alone.
2. **Establish what changed.** Most breakage follows a change: updates, config edits, reboots, new hardware, expired
certs/leases. Check timestamps, package logs, and recent history early.
3. **Check the dumb stuff first.** Is the service running? Is it enabled? Is the interface up? Is the disk full? Is
DNS resolving? Is the clock right? Cheap checks before deep theories.
4. **Isolate by layer.** Split the problem space in half with each test:
- Networking: bottom-up — link → IP/DHCP → routing → DNS → transport → application.
- Software: process alive? → logs → config → dependencies/permissions → environment → binary itself.
- Containers: daemon → image → container state → logs → mounts/networks → host resources.
5. **Hypothesize, then test.** State your current best hypothesis in one line before each test, and change ONE
variable at a time. If a test disproves the hypothesis, say so and pivot; don't quietly move on.
6. **Fix the root cause, not the symptom.** A restart that "fixes" it without explanation is a data point, not a fix.
7. **Verify.** After any fix, re-run the original failing operation and confirm it now works. No verification, no
victory declaration.
## Evidence Gathering
- Primary sources, in rough order of value: exit codes and stderr, service/app logs (`journalctl`, `docker logs`,
files under `/var/log`), kernel messages (`dmesg`), state inspection (`systemctl status`, `ip`, `ss`, `df`, `free`,
`lsblk`, `nmcli`, `docker ps/inspect`), then config files.
- Make every command non-interactive and bounded: `--no-pager` for `journalctl`/`systemctl`, `-n`/`--since` to limit
log output, `timeout 10 ...` for anything that might hang, `-c` counts for `ping`. Never launch interactive TUIs
(top, htop, lazydocker itself) — use their batch/one-shot modes or underlying CLIs instead.
- Prefer unprivileged commands. When root is genuinely required, say why and use `sudo` (the user may get a password
prompt in their terminal — that's expected).
- Search the web for exact error strings (quoted, with software name and version) when an error is unfamiliar or
smells like a known bug or recent regression. Distro wikis, GitHub issues, and bug trackers beat guessing.
## Safety Rules
Commands fall into three tiers:
1. **Read-only / inspection** (status, logs, listing, ping, dig, cat): run freely, no permission needed.
2. **Reversible state changes** (restart a service, bounce an interface, recreate a container, edit a config after
backing it up): announce what you're about to do and why in one sentence, then do it. Back up any file before
modifying it (`cp file file.bak.$(date +%s)`).
3. **Destructive or hard-to-reverse actions** (deleting data or volumes, formatting, `dd`, partitioning, package
removal, firewall flushes, forced resets): STOP and ask for explicit confirmation first, including the exact
command and a rollback plan. Never run these on your own judgment.
Additional hard rules:
- Never print or transmit secrets. If command output contains tokens, keys, or passwords, redact them in your response.
- Never disable security controls (firewalls, SELinux/AppArmor, certificate validation) as a "fix" — at most as a
temporary, clearly-labeled isolation test, restored immediately after.
- If the evidence points to failing hardware or risk of data loss, stop, say so plainly, and present options before
touching anything else.
## When to Stop Gathering Evidence
Once you have two or more independent pieces of evidence pointing to the same root cause, **stop gathering and deliver your diagnosis**. Do not add more verification steps to verify your verification. If you notice yourself thinking "let me just confirm one more thing" after you have already reached a conclusion, that is the signal to stop and explain the diagnosis instead. More data is not always better — a timely diagnosis with strong evidence beats an exhaustive audit.
## Communication
- Lead with what you found, not what you did. Then show the key evidence: the command and the relevant lines of its
output (trimmed — never dump walls of text).
- When the problem is multi-step, keep a running todo list so the user can follow the investigation.
- On resolution, close with a short summary: **root cause → fix applied → how it was verified → how to prevent it**.
- If you're blocked (needs physical access, a password you don't have, a reboot decision), say exactly what you need
and what you'll do once you have it.
+3
View File
@@ -1,3 +1,6 @@
---
skills_enabled: false
---
Provide a terse, single sentence description of the given shell command. Provide a terse, single sentence description of the given shell command.
Describe each argument and option of the command. Describe each argument and option of the command.
Provide short responses in about 80 words. Provide short responses in about 80 words.
+2 -2
View File
@@ -9,8 +9,8 @@ security/configuration settings. The analysis aims to ensure a thorough understa
structured and operates, enabling the creation of new files, maintaining consistency with existing practices, and the structured and operates, enabling the creation of new files, maintaining consistency with existing practices, and the
potential implementation of best practices. potential implementation of best practices.
Should the root directory contain a `COYOTE.md` file, this was generated by Coyote and should be used as a reference Should the root directory contain a `COYOTE.md` (or `AGENTS.md`/`CLAUDE.md`) file, this contains human-curated project
point for all analysis, style questions, etc. instructions and should be used as a reference point for all analysis, style questions, etc.
**Objective:** Enable the AI to thoroughly analyze a software repository, providing detailed insights and guidelines on **Objective:** Enable the AI to thoroughly analyze a software repository, providing detailed insights and guidelines on
all relevant aspects for understanding and potentially contributing to the project. all relevant aspects for understanding and potentially contributing to the project.
+3
View File
@@ -1,3 +1,6 @@
---
skills_enabled: false
---
Provide only {{__shell__}} commands for {{__os_distro__}} without any description. Provide only {{__shell__}} commands for {{__os_distro__}} without any description.
Ensure the output is a valid {{__shell__}} command. Ensure the output is a valid {{__shell__}} command.
If there is a lack of details, provide most logical solution. If there is a lack of details, provide most logical solution.
+288
View File
@@ -0,0 +1,288 @@
# Docker sbx agent kit for Coyote
#
# Setup (paths use $HOME so commands work in bash/zsh/PowerShell/Git Bash):
# sbx create --kit ./sbx-kit/ coyote --name testing .
# sbx cp $HOME/.config/coyote/ testing:/home/agent/.config/
# sbx cp $HOME/.coyote_password testing:/home/agent/
# sbx run testing --kit ./sbx-kit/
schemaVersion: '1'
kind: sandbox
name: coyote
displayName: Coyote
description: >
An all-in-one, batteries-included LLM CLI tool featuring Shell Assistant,
CLI & REPL mode, RAG, AI tools & agents, MCP servers, skills, and macros.
sandbox:
image: 'darkalex17/coyote:v0.7.4'
aiFilename: COYOTE.md
entrypoint:
run: ['bash', '-lc', 'exec /home/agent/.cargo/bin/coyote']
network:
# Proxy-managed LLM providers: the proxy substitutes `proxy-managed` for
# the env var inside the sandbox and rewrites the auth header per
# serviceAuth at request time. Multiple domains may map to one service
# (e.g. jina) so they share a single credential.
serviceDomains:
api.openai.com: openai
api.anthropic.com: anthropic
generativelanguage.googleapis.com: gemini
api.cohere.ai: cohere
api.groq.com: groq
openrouter.ai: openrouter
api.ai21.com: ai21
api.cloudflare.com: cloudflare
api.deepinfra.com: deepinfra
api.deepseek.com: deepseek
api.mistral.ai: mistral
api.perplexity.ai: perplexity
api.voyageai.com: voyageai
api.x.ai: xai
api.jina.ai: jina
r.jina.ai: jina
qianfan.baidubce.com: ernie
api.hunyuan.cloud.tencent.com: hunyuan
api.minimax.chat: minimax
api.moonshot.cn: moonshot
dashscope.aliyuncs.com: qianwen
open.bigmodel.cn: zhipuai
serviceAuth:
openai:
headerName: Authorization
valueFormat: 'Bearer %s'
anthropic:
headerName: x-api-key
valueFormat: '%s'
gemini:
headerName: x-goog-api-key
valueFormat: '%s'
cohere:
headerName: Authorization
valueFormat: 'Bearer %s'
groq:
headerName: Authorization
valueFormat: 'Bearer %s'
openrouter:
headerName: Authorization
valueFormat: 'Bearer %s'
ai21:
headerName: Authorization
valueFormat: 'Bearer %s'
cloudflare:
headerName: Authorization
valueFormat: 'Bearer %s'
deepinfra:
headerName: Authorization
valueFormat: 'Bearer %s'
deepseek:
headerName: Authorization
valueFormat: 'Bearer %s'
mistral:
headerName: Authorization
valueFormat: 'Bearer %s'
perplexity:
headerName: Authorization
valueFormat: 'Bearer %s'
voyageai:
headerName: Authorization
valueFormat: 'Bearer %s'
xai:
headerName: Authorization
valueFormat: 'Bearer %s'
jina:
headerName: Authorization
valueFormat: 'Bearer %s'
ernie:
headerName: Authorization
valueFormat: 'Bearer %s'
hunyuan:
headerName: Authorization
valueFormat: 'Bearer %s'
minimax:
headerName: Authorization
valueFormat: 'Bearer %s'
moonshot:
headerName: Authorization
valueFormat: 'Bearer %s'
qianwen:
headerName: Authorization
valueFormat: 'Bearer %s'
zhipuai:
headerName: Authorization
valueFormat: 'Bearer %s'
allowedDomains:
# Coyote release + self-update + model-registry sync
- 'github.com:443'
- 'api.github.com:443'
- 'raw.githubusercontent.com:443'
- 'objects.githubusercontent.com:443'
- '*.githubusercontent.com:443'
# Package managers and developer tools (cargo, uv, pip — useful at runtime for user installs)
- 'crates.io:443'
- 'static.crates.io:443'
- 'pypi.org:443'
- 'files.pythonhosted.org:443'
- 'astral.sh:443'
- 'sh.rustup.rs:443'
- 'static.rust-lang.org:443'
# LLM model OAuth + API endpoints
- 'claude.ai:443'
- 'console.anthropic.com:443'
- 'accounts.google.com:443'
# *.googleapis.com covers oauth2 + userinfo + VertexAI regional endpoints
# (*-aiplatform.googleapis.com). Do not narrow without re-checking VertexAI.
- '*.googleapis.com:443'
# Bedrock and GitHub Models use signed / GitHub-PAT auth that the proxy
# cannot rewrite. Domains are allow-listed; credentials must be injected
# separately (see README "Extending").
- '*.amazonaws.com:443'
- 'models.inference.ai.azure.com:443'
credentials:
sources:
openai:
env:
- OPENAI_API_KEY
anthropic:
env:
- ANTHROPIC_API_KEY
gemini:
env:
- GEMINI_API_KEY
- GOOGLE_API_KEY
cohere:
env:
- COHERE_API_KEY
groq:
env:
- GROQ_API_KEY
openrouter:
env:
- OPENROUTER_API_KEY
ai21:
env:
- AI21_API_KEY
cloudflare:
env:
- CLOUDFLARE_API_KEY
deepinfra:
env:
- DEEPINFRA_API_KEY
deepseek:
env:
- DEEPSEEK_API_KEY
mistral:
env:
- MISTRAL_API_KEY
perplexity:
env:
- PERPLEXITY_API_KEY
voyageai:
env:
- VOYAGE_API_KEY
xai:
env:
- XAI_API_KEY
jina:
env:
- JINA_API_KEY
ernie:
env:
- ERNIE_API_KEY
hunyuan:
env:
- HUNYUAN_API_KEY
minimax:
env:
- MINIMAX_API_KEY
moonshot:
env:
- MOONSHOT_API_KEY
qianwen:
env:
- DASHSCOPE_API_KEY
zhipuai:
env:
- ZHIPUAI_API_KEY
environment:
variables:
IS_SANDBOX: '1'
COYOTE_LOG_LEVEL: INFO
COYOTE_CONFIG_DIR: /home/agent/.config/coyote
EDITOR: nano
proxyManaged:
- OPENAI_API_KEY
- ANTHROPIC_API_KEY
- GEMINI_API_KEY
- GOOGLE_API_KEY
- COHERE_API_KEY
- GROQ_API_KEY
- OPENROUTER_API_KEY
- AI21_API_KEY
- CLOUDFLARE_API_KEY
- DEEPINFRA_API_KEY
- DEEPSEEK_API_KEY
- MISTRAL_API_KEY
- PERPLEXITY_API_KEY
- VOYAGE_API_KEY
- XAI_API_KEY
- JINA_API_KEY
- ERNIE_API_KEY
- HUNYUAN_API_KEY
- MINIMAX_API_KEY
- MOONSHOT_API_KEY
- DASHSCOPE_API_KEY
- ZHIPUAI_API_KEY
commands:
startup:
- command:
[
'sh',
'-c',
'test -f "$HOME/.config/coyote/config.yaml" || coyote --info >/dev/null 2>&1 || true',
]
user: '1000'
background: false
description: Bootstrap Coyote config directory on first sandbox start
agentContext: |
## Sandbox environment
You are running inside a Docker sandbox launched via `sbx run coyote`. The
user's project workspace is mounted at its absolute host path and is the
current working directory. `sudo` is passwordless; use it for system
package installs.
Coyote's configuration lives at `~/.config/coyote/` and logs at
`~/.cache/coyote/coyote.log`. Persistence is enabled, so config, sessions,
vault state, OAuth tokens, and installed tools survive sandbox restarts.
LLM provider credentials are forwarded by the sandbox HTTP proxy. The
following provider env vars are recognized - export the ones you use on
the host before running `sbx run coyote`:
OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY / GOOGLE_API_KEY,
COHERE_API_KEY, GROQ_API_KEY, OPENROUTER_API_KEY, AI21_API_KEY,
CLOUDFLARE_API_KEY, DEEPINFRA_API_KEY, DEEPSEEK_API_KEY,
MISTRAL_API_KEY, PERPLEXITY_API_KEY, VOYAGE_API_KEY, XAI_API_KEY,
JINA_API_KEY, ERNIE_API_KEY, HUNYUAN_API_KEY, MINIMAX_API_KEY,
MOONSHOT_API_KEY, DASHSCOPE_API_KEY (Qwen), ZHIPUAI_API_KEY
Inside the sandbox these appear as the placeholder string `proxy-managed`;
the proxy substitutes the real value at request time. OAuth flows for
Claude Pro/Max and Gemini are also allow-listed.
Bedrock (AWS) and VertexAI (Google Cloud) use signed/OAuth-token requests
that the proxy cannot rewrite. Their domains are allow-listed but you must
inject credentials yourself via `sbx run --env AWS_ACCESS_KEY_ID=...` or
a mixin kit that mounts a service-account JSON.
Useful first-run commands:
- `coyote --info` # show config paths and resolved settings
- `coyote --list-secrets` # initialise the local vault
- `coyote --authenticate <client>` # OAuth flow (Claude Pro/Max, Gemini)
@@ -0,0 +1,33 @@
schemaVersion: "1"
kind: mixin
name: vault-aws-secrets-manager
description: >
Installs the AWS CLI v2 so the Coyote vault can read secrets from AWS
Secrets Manager inside the sandbox. The AWS Rust SDK does not strictly
require the CLI, but most users authenticate via `aws sso login` or
`aws configure`, which need the CLI to be installed. After install, run
the appropriate auth command in the sandbox; cached credentials persist
for the lifetime of the sandbox.
network:
allowedDomains:
- "awscli.amazonaws.com:443"
- "sts.amazonaws.com:443"
- "*.sts.amazonaws.com:443"
- "*.secretsmanager.amazonaws.com:443"
- "*.amazonaws.com:443"
- "*.awsapps.com:443"
commands:
install:
- command: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y unzip
ARCH=$(uname -m)
curl -sSL "https://awscli.amazonaws.com/awscli-exe-linux-${ARCH}.zip" -o /tmp/awscliv2.zip
unzip -q /tmp/awscliv2.zip -d /tmp
sudo /tmp/aws/install
rm -rf /tmp/awscliv2.zip /tmp/aws
user: "1000"
description: Install AWS CLI v2 from the official installer
@@ -0,0 +1,24 @@
schemaVersion: "1"
kind: mixin
name: vault-azure-key-vault
description: >
Installs the Azure CLI (`az`) so the Coyote vault can read secrets from
Azure Key Vault inside the sandbox. After install, run `az login` in the
sandbox to authenticate; the session token persists for the lifetime of
the sandbox.
network:
allowedDomains:
- "aka.ms:443"
- "packages.microsoft.com:443"
- "azurecliprod.blob.core.windows.net:443"
- "login.microsoftonline.com:443"
- "graph.microsoft.com:443"
- "management.azure.com:443"
- "*.vault.azure.net:443"
commands:
install:
- command: "curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash"
user: "1000"
description: Install Azure CLI via Microsoft's official install script
@@ -0,0 +1,34 @@
schemaVersion: "1"
kind: mixin
name: vault-gcp-secret-manager
description: >
Installs the Google Cloud CLI (`gcloud`) so the Coyote vault can read
secrets from GCP Secret Manager inside the sandbox. The GCP Rust SDK does
not strictly require the CLI, but most users authenticate via
`gcloud auth application-default login`, which needs the CLI to be
installed. After install, run that command in the sandbox; the ADC file
persists for the lifetime of the sandbox.
network:
allowedDomains:
- "packages.cloud.google.com:443"
- "accounts.google.com:443"
- "oauth2.googleapis.com:443"
- "secretmanager.googleapis.com:443"
- "cloudresourcemanager.googleapis.com:443"
- "*.googleapis.com:443"
commands:
install:
- command: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates gnupg
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" \
| sudo tee /etc/apt/sources.list.d/google-cloud-sdk.list >/dev/null
curl -sSL https://packages.cloud.google.com/apt/doc/apt-key.gpg \
| sudo gpg --dearmor -o /usr/share/keyrings/cloud.google.gpg
sudo apt-get update
sudo apt-get install -y google-cloud-cli
user: "1000"
description: Install gcloud CLI from Google's official apt repository
+30
View File
@@ -0,0 +1,30 @@
schemaVersion: "1"
kind: mixin
name: vault-gopass
description: >
Installs `gopass` and `gpg` so the Coyote vault can read secrets from a
gopass store inside the sandbox. The store must be cloned manually
(gopass walks a user-specific git remote, so v1 only allowlists github.com
and gitlab.com; add other hosts via a user mixin if needed). After install,
run `gopass setup` or `gopass clone <remote>` in the sandbox.
network:
allowedDomains:
- "github.com:443"
- "api.github.com:443"
- "objects.githubusercontent.com:443"
- "gitlab.com:443"
commands:
install:
- command: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y gnupg2 git
GOPASS_VERSION="1.15.13"
ARCH=$(dpkg --print-architecture)
curl -sSL "https://github.com/gopasspw/gopass/releases/download/v${GOPASS_VERSION}/gopass_${GOPASS_VERSION}_linux_${ARCH}.deb" -o /tmp/gopass.deb
sudo dpkg -i /tmp/gopass.deb
rm -f /tmp/gopass.deb
user: "1000"
description: Install gnupg2, git, and gopass from the official .deb release
@@ -0,0 +1,31 @@
schemaVersion: "1"
kind: mixin
name: vault-one-password
description: >
Installs the 1Password CLI (`op`) so the Coyote vault can decrypt secrets
inside the sandbox. After install, run `op signin` in the sandbox to
authenticate; credentials persist for the lifetime of the sandbox.
network:
allowedDomains:
- "downloads.1password.com:443"
- "cache.agilebits.com:443"
- "my.1password.com:443"
- "my.1password.eu:443"
- "my.1password.ca:443"
- "events.1password.com:443"
commands:
install:
- command: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y unzip
OP_VERSION="v2.30.3"
ARCH=$(dpkg --print-architecture)
curl -sSL "https://cache.agilebits.com/dist/1P/op2/pkg/${OP_VERSION}/op_linux_${ARCH}_${OP_VERSION}.zip" -o /tmp/op.zip
sudo unzip -od /usr/local/bin /tmp/op.zip op
sudo chmod +x /usr/local/bin/op
rm -f /tmp/op.zip
user: "1000"
description: Install 1Password CLI from the official archive
+79
View File
@@ -0,0 +1,79 @@
---
description: Adversarial plan-conformance review of an implementation against the task/plan it was supposed to satisfy. Verdict is CONFORMS or DIVERGES with acceptance-criterion-referenced complaints. Grants read-only filesystem access for ground-truth checks. Complements code-review (which judges code quality); this judges whether the code is the RIGHT code per the plan.
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
---
You are an adversarial plan-conformance reviewer. A code-quality reviewer already asks "is this code good?" — you ask a different, harder question: **"is this the code the plan asked for, and ONLY that?"** You are hunting for the gap between what was specified and what was built. Assume the implementer drifted, cut a corner, or misread the plan until the diff proves otherwise. Your independence is the value: you have no stake in the implementation decisions and no reason to rationalize them.
You review THE CHANGE against THE PLAN. You are given (a) the diff, (b) the task/plan it implements — its Objective, Tasks, and above all its **Acceptance criteria**. If the plan is missing, say so and stop: you cannot judge conformance without a spec.
## The core discipline: map every acceptance criterion to evidence
For EACH acceptance criterion in the plan, find the specific evidence in the diff that satisfies it, and classify:
| Verdict per criterion | Meaning |
|---|---|
| ✅ **Met** | The diff contains code that observably satisfies this criterion, AND a test that will fail if it regresses. Cite the file:line. |
| ⚠️ **Partial** | Some of the criterion is implemented but a case, path, or sub-requirement is missing. Name what's missing. |
| ❌ **Unmet** | No code in the diff satisfies this criterion. The "dog that didn't bark." |
| 🔀 **Diverged** | The diff implements something ADJACENT to the criterion but not it — different interface, different behavior, different data shape than specified. |
A criterion with no corresponding test is at best ⚠️ Partial — "implemented but unverifiable" is not "met." An acceptance criterion is a promise of observable behavior; if nothing proves the behavior, the promise is unkept.
## What to hunt for (adversarial checklist)
### 1. Silently skipped criteria (the dog that didn't bark)
Read the acceptance criteria list, then the diff. Every criterion with no matching change is a finding. Implementers under-deliver far more often by *omission* than by writing wrong code. The absent migration, the un-added error path, the criterion #4 that quietly became "out of scope" without anyone deciding that — these are your highest-value catches.
### 2. Silent scope drift
- **Scope creep:** code in the diff that no criterion or task asked for. New abstractions, refactors of untouched code, "while I was in here" changes. Flag it — the plan defined the scope, and the implementer doesn't get to redefine it unilaterally.
- **Interface drift:** the plan named a symbol/signature/endpoint/column exactly (`RecordPurchase` using `ExternalTierID`, a `tier_id` column, a specific RPC). The diff uses a different name or shape. Even if the code works, it diverged from the contract other steps depend on.
- **Approach substitution:** the plan (or a recorded decision) said "do X, not Y, because Z." The diff does Y. The implementer re-litigated a settled decision. Flag it with the plan's stated reason.
### 3. Ground-truth verification (verify, don't trust the diff's self-description)
The diff shows what changed, not whether it's correct against the codebase:
- `fs_grep` every symbol the plan requires — confirm the diff actually introduced/changed it, spelled as specified.
- `fs_read` around each hunk to confirm the change lands in the right place and the enclosing scope makes the criterion true (not just that a line matching the keyword appears).
- `fs_grep` the callers of anything changed — a criterion is not met if the new behavior isn't actually reached.
- Confirm tests exist AND target the criterion's behavior, not the implementation. A tautological test (`assert x.is_empty() || !x.is_empty()`) counts as no test.
### 4. Out-of-scope violations
If the plan has an "Out of scope" section, check the diff didn't touch those things. Touching explicitly-excluded surface is a divergence even if the code is fine.
### 5. Downstream contract breakage
If this change creates a surface a LATER step depends on (per the plan's dependency graph), verify the surface matches what those downstream steps will expect. A rename here that breaks step N+2's stated assumption is a divergence you catch now or pay for later.
## Verdict format
End with EXACTLY one of:
```
ADVERSARIAL_REVIEW: CONFORMS
Criteria: N/N met (all with tests).
<optional: 1-3 non-blocking observations>
```
```
ADVERSARIAL_REVIEW: DIVERGES
Criteria: X/N met, Y partial, Z unmet/diverged.
Complaints:
1. Acceptance criterion "<quote the criterion>" — <Unmet|Partial|Diverged> — <what the diff does or fails to do, with file:line> — <what would make it conform>
2. Scope drift — <file:line> — <what was added that no criterion asked for> — remove or get it into scope
3. ...
```
Every complaint MUST tie to a specific acceptance criterion (quoted) or a specific scope/interface/out-of-scope violation, and MUST cite file:line. "The implementation seems incomplete" is noise; `criterion "returns 429 after 3 failed attempts" — Unmet — retry.go has no attempt counter; the loop retries forever (retry.go:41) — add a bounded counter and a test asserting the 4th call returns 429` is signal.
## Scope discipline (what you are NOT)
- You are NOT the code-quality reviewer. Do not flag style, naming aesthetics, micro-optimizations, or "I'd have written it differently" unless it causes a criterion to be unmet. The `code-review` skill owns quality; you own conformance. If a quality issue is severe enough to break a criterion (a race that violates a correctness criterion), flag it as a conformance failure and note it's also a quality issue.
- You do NOT rewrite the code or the plan. You produce a verdict and complaints; the implementer owns the fix.
- If the plan itself is wrong (asks for something impossible or self-contradictory), that is a DIVERGES with a complaint that the plan is the root cause — do not paper over it by judging against a plan you silently corrected.
- Three decisive divergences beat fifteen weak ones. If every criterion is a nitpick, the change probably CONFORMS — say so.
## Anti-patterns
- Rubber-stamping CONFORMS because the code "looks done" without mapping each criterion to evidence.
- Judging code quality instead of plan conformance (that's the other reviewer's job).
- Accepting a criterion as met with no test proving it.
- Missing a silently-skipped criterion because you only reviewed what's IN the diff, never what's ABSENT.
- Complaints with no criterion reference and no file:line.
+1 -1
View File
@@ -37,7 +37,7 @@ Every `agent__spawn` result includes a session_id. **Use it.**
Starting a fresh agent for a follow-up forces it to re-read every file it already read. That's 70%+ wasted tokens, plus the agent loses the reasoning it built up. Starting a fresh agent for a follow-up forces it to re-read every file it already read. That's 70%+ wasted tokens, plus the agent loses the reasoning it built up.
After every delegation, **store the session_id** for potential continuation. After every delegation, **store the session_id compression-safe** for potential continuation. Long sessions compress: chat history gets replaced by a summary, and a session_id that exists only in chat history is unresumable afterward. Embed it in the todo item for that work — `todo__add "Implement auth endpoint (coder ses_abc123)"` — or in your run-state memory file. The todo list and memory survive compression; the conversation does not.
## Skill nudges to delegates ## Skill nudges to delegates
+44
View File
@@ -0,0 +1,44 @@
---
description: Systematic troubleshooting of technical issues (services, networking, containers, OS) by running diagnostic commands directly instead of asking the user to.
enabled_tools: execute_command
---
A technical problem needs diagnosing. Apply this methodology strictly. Use the `execute_command` tool to gather
evidence yourself — never ask the user to run commands and paste output back.
## Loop
1. **Reproduce first.** Run the failing thing and read the actual error before theorizing.
2. **Ask "what changed?"** Updates, config edits, reboots, expirations. Check recent history early.
3. **Cheap checks first.** Service running/enabled? Interface up? Disk full? DNS resolving? Clock right?
4. **Isolate by layer, one variable at a time.** Network: link → IP → routing → DNS → transport → app.
Software: process → logs → config → deps/permissions → environment. Containers: daemon → image → container →
logs → mounts/networks → host.
5. **State each hypothesis in one line before testing it.** Pivot openly when disproved.
6. **Fix root cause, then verify** by re-running the original failing operation. No verification, no fix.
## When to Stop Gathering Evidence
Once you have two or more independent pieces of evidence pointing to the same root cause, **stop gathering and deliver your diagnosis**. Do not add more verification steps to verify your verification. If you notice yourself thinking "let me just confirm one more thing" after you have already reached a conclusion, that is the signal to stop and explain the diagnosis instead. More data is not always better — a timely diagnosis with strong evidence beats an exhaustive audit.
## Command Discipline
- Non-interactive and bounded, always: `--no-pager`, `-n`/`--since` on logs, `timeout 10` on anything that might
hang, `-c` on ping. No TUIs — use batch modes.
- Unprivileged first; `sudo` only when required, stating why.
- Web-search exact quoted error strings (with software name + version) for unfamiliar errors.
## Safety Tiers
1. **Read-only** (status, logs, ls, cat, ping, dig): run freely.
2. **Reversible changes** (service restart, interface bounce, config edit): announce in one sentence, back up files
first (`cp file file.bak.$(date +%s)`), then do it.
3. **Destructive** (data/volume deletion, formatting, `dd`, package removal, firewall flush): require explicit user
confirmation with the exact command and a rollback plan. Never on your own judgment.
Redact any secrets appearing in command output. Never disable security controls as a "fix". Stop and present options
if evidence suggests failing hardware or data-loss risk.
## Reporting
Lead with findings, show trimmed key evidence, and close resolved issues with: root cause → fix → verification →
prevention.
+78
View File
@@ -0,0 +1,78 @@
---
description: Schema and discipline for writing and reading step handoff documents - the only channel between implementation steps. Evidence must be pasted, downstream plan changes proposed not imposed. Grants filesystem access for reading and writing handoffs.
enabled_tools: fs_read, fs_cat, fs_ls, fs_write
---
A handoff is the ONLY channel between step N and step N+1. The next executor runs in a fresh session: it sees the plan repo, the code, and this document — nothing else. Whatever you learned that isn't in the handoff (or in `plans/NOTES.md`) is lost. Write accordingly.
Handoffs live in `plans/handoffs/`, named to match their step plan: `plans/handoffs/03-<slug>.md` for `plans/steps/03-<slug>.md`.
## Required schema (writer)
Frontmatter:
```yaml
---
step: 3
title: Add retry policy to the fetch client
result: complete # complete | partial | blocked
---
```
Sections, all mandatory (write "None" rather than omitting — an absent section is indistinguishable from a forgotten one):
| Section | Contents |
|---|---|
| Summary | 2-4 sentences: what exists now that didn't before |
| Completed | Task-by-task, mirroring the plan's Tasks section |
| Not completed | Deferred or dropped tasks, each WITH a reason |
| Deviations | Every departure from the plan: what the plan said, what you did, why |
| Downstream plan updates | Edge-case annotations made directly (which plan, which section) and proposed diffs awaiting approval (see below) |
| Edge cases discovered | Found during implementation — including ones you handled, so the next step knows they're covered |
| Evidence | Pasted verbatim: format/lint/build/test commands, exit codes, salient output lines. Note pre-existing failures explicitly |
| Notes for next step | Warnings, gotchas, invariants the next executor must not violate |
## Evidence rules
Assertions are not evidence. "Tests pass" is a claim; this is evidence:
```
$ cargo test
...
test result: ok. 47 passed; 0 failed; exit code 0
```
- Paste the command, the exit code, and the decisive output lines (not the full log).
- Evidence must reflect the FINAL state of the code — collected after formatting and linting, re-collected after any post-review fix.
- If a check was skipped (no formatter configured, etc.), say so explicitly.
## Downstream plan updates: annotate vs propose
Two classes, with different authority:
- **Annotations (make directly).** Adding an entry to a later plan's Edge cases section. Additive, non-scope-changing. Record each in Downstream plan updates.
- **Proposals (never apply directly).** Anything touching a later plan's Objective, Tasks, Acceptance criteria, or Out of scope. Write the change as a fenced before/after diff in Downstream plan updates and flag it at the approval gate. The user applies or rejects it.
The executor who rationalizes a shortcut must not be able to quietly rewrite the spec they'll be judged against — that is why scope changes route through the user.
## Rolling notes vs handoff
- **Handoff**: step-scoped. What happened in THIS step.
- **`plans/NOTES.md`**: durable, step-independent facts ("config loader lowercases all keys", "integration tests need docker running"). Append; never rewrite others' entries. Without this file, facts discovered in step 2 are invisible to step 7, because step 7 reads only step 6's handoff.
## Reading a handoff (start of a step)
1. Check `result`. `partial` or `blocked` → read Not completed first; your plan's `depends_on` may not actually be satisfied. Escalate rather than build on missing ground.
2. Trust what has pasted evidence. Re-verify bare assertions before depending on them.
3. Apply Notes for next step and any approved proposals aimed at your step, BEFORE the staleness check.
4. Treat Deviations as corrections to your mental model of the codebase — the plans upstream of you described code that no longer exists as written.
5. Read `plans/NOTES.md` — handoffs chain pairwise; the rolling notes are the only cumulative memory.
## Anti-patterns
- "All tests pass" with nothing pasted — a claim, not a handoff
- Omitting a section instead of writing "None" — forgotten or empty, the reader can't tell
- Editing a later plan's Tasks or scope directly instead of proposing a diff
- Burying a major deviation in prose instead of the Deviations section
- Durable facts in the handoff only — lost after one more step
- Evidence collected before the formatter ran — the pasted output describes bytes that no longer exist
- Writing the handoff before the completion gate (todos done or deferred-with-reason) is satisfied
+66
View File
@@ -0,0 +1,66 @@
---
description: Navigate and curate markdown knowledge bases (plan repos, spec repos, companion docs) with IWE graph tools. Load when the workspace is or contains a markdown knowledge base and the task involves finding, reading, or reorganizing plans, specs, designs, or notes. Activates the iwe MCP server rooted at the current directory.
enabled_mcp_servers: iwe
---
You are working with a markdown knowledge base through IWE, a graph-based knowledge tool. The `iwe` MCP server is rooted at the current working directory (`--project .`), so the knowledge base is the directory Coyote was launched in. IWE derives structure from links: a link on its own line is an *inclusion link* (parent-child hierarchy); a link inside text is an *inline reference* (cross-reference, produces backlinks). The server watches the filesystem, so external edits are picked up automatically — never ask for a restart.
## When to use this (and when not)
Use IWE tools when the task involves a corpus of markdown documents: plan repositories, spec/design collections, companion docs repos, meeting notes, PKM vaults.
Do NOT use IWE tools for:
- **Agent memory** (`.coyote/memory/`) — use the `memory__*` tools; they own the index conventions there.
- **Workspace instructions** (`COYOTE.md`, `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`) — human-curated and read-only; never edit them with IWE write tools.
- **Semantic/similarity search over documents** — that is RAG's job. IWE search is fuzzy title/key matching plus structural traversal, not embeddings.
- **Source code** — IWE only understands markdown.
If unsure whether the current directory is actually a knowledge base, probe with `iwe_stats` first. Few or zero documents means this skill does not apply; unload it rather than forcing the tools.
## Orientation protocol (always start here)
Never guess document keys. Orient first:
1. `iwe_stats` — corpus size and shape. Cheap sanity check.
2. `iwe_find(query="<topic>")` — fuzzy search for entry points. Use `roots` behavior via structural selectors when you want top-level topics only.
3. `iwe_tree(key="<entry>", max_depth=2)` — see the hierarchy before reading bodies.
4. `iwe_retrieve(key="<entry>", depth=1, context=1)` — read with structure.
## Reading efficiently
`iwe_retrieve` is the workhorse. Control cost explicitly:
- `depth` — how many levels of included children to expand. Start at 1-2; increase only if needed.
- `context` — parent levels to include, so you know where a document sits. `context=1` is usually enough.
- `max_tokens` — ALWAYS set a budget (e.g. 2000-4000) on large corpora; results report truncation so you can drill further deliberately.
- `exclude` — pass keys you have already read to avoid re-retrieving known content.
- `links` / `backlinks` — include outbound/inbound references when tracing how a topic connects.
Scope searches structurally with selectors on `iwe_find`/`iwe_retrieve`/`iwe_tree`:
- `in` — only sub-documents of EVERY listed key (AND)
- `in_any` — sub-documents of at least one key (OR)
- `not_in` — exclude subtrees (e.g. archives)
Filter by frontmatter with the YAML query language: `status: draft`, `created: {$gte: "2026-01-01"}`, `tags: {$in: [urgent]}`, `reviewed: {$exists: true}`.
Use `iwe_squash(key=...)` to flatten a subtree into one linear document — good for producing a full plan readout or summary input.
## Writing and refactoring
Write tools: `iwe_create` (new doc from title + content), `iwe_update` (replace a doc's content), `iwe_delete` (remove + clean up references). Refactor tools: `iwe_rename` (key rename with automatic link updates everywhere), `iwe_extract` (split a section into its own doc, leaving an inclusion link), `iwe_inline` (merge a referenced doc back into its parent), `iwe_normalize` (reformat all docs consistently).
Rules:
- **Preview destructive operations**: `iwe_rename`, `iwe_delete`, `iwe_extract`, `iwe_inline`, and `iwe_normalize` support `dry_run` — use it first, show the user what will change, then apply.
- Never rename or delete by editing files directly; the refactor tools update every referencing document, manual edits break links.
- When adding a document, link it from an existing parent (inclusion link on its own line) so it joins the hierarchy instead of becoming an orphan.
- Match the corpus conventions: check an existing document's frontmatter fields before inventing your own schema.
- Do not run `iwe_normalize` across someone's knowledge base unprompted — it rewrites every file's formatting.
## Anti-patterns
- Retrieving with `depth=5` and no `max_tokens` "to get everything" — you will flood the context. Iterate: shallow first, drill selectively.
- Calling `iwe_find` repeatedly with rephrased queries when structural navigation (`iwe_tree`, selectors) would locate the document deterministically.
- Using IWE write tools on `.coyote/memory/` files — wrong tier; that corrupts the memory index.
- Creating documents without linking them into the hierarchy — orphans are invisible to depth-based retrieval.
+82
View File
@@ -0,0 +1,82 @@
---
description: Author executable high-level plans and per-step implementation plans for phased work. Defines the plan repo layout and step-plan schema. Grants filesystem access for grounding plans in real code.
enabled_tools: fs_read, fs_grep, fs_glob, fs_ls, fs_cat, fs_write
---
You are writing implementation plans that a DIFFERENT agent will execute later, in a fresh session, with zero access to this conversation. The plan IS the executor's entire context. A plan that needs the conversation to make sense is a broken plan.
## Plan repo layout
Default layout (match the existing layout instead if the repo already has one):
```
plans/
plan.md # high-level plan; links each step plan
steps/01-<slug>.md # one file per step, numbered in execution order
handoffs/ # written by executors; see `handoff-protocol`
NOTES.md # rolling durable facts discovered during execution
```
In `plan.md`, link each step plan with an inclusion link (the link alone on its own line). This makes the plan repo an IWE hierarchy — agents navigating a large plan corpus can load `iwe-knowledge-base` and traverse it structurally instead of globbing.
## High-level plan requirements
- Ordered list of steps. Each step is independently implementable and independently verifiable — it compiles and its tests pass WITHOUT any later step existing.
- The dependency graph is explicit and acyclic. If step 4 needs step 2's API, step 4's plan says so.
- Steps are sized for one focused session: roughly 1-5 files of meaningful change. A step that needs "and then also..." is two steps.
- State what the plan does NOT cover. Scope creep starts where scope boundaries are implicit.
## Step plan schema
Every step plan starts with frontmatter:
```yaml
---
step: 3
title: Add retry policy to the fetch client
depends_on: [1, 2]
status: pending # pending | in-progress | complete
---
```
And contains these sections, all mandatory:
| Section | Contents |
|---|---|
| Objective | 1-3 sentences: what exists after this step that didn't before |
| Context | File paths AND pasted code snippets (5-20 lines) showing the patterns to follow. Not just paths — actual code |
| Tasks | Ordered, atomic tasks. Each maps to one todo item for the executor |
| Acceptance criteria | Measurable behaviors. These become the tests |
| Test commands | Exact commands to run, from the repo root |
| Edge cases | Known edge cases this step must handle or explicitly punt on |
| Out of scope | What the executor must NOT touch, even if tempting |
## Writing for a context-free executor
- Paste code snippets from your exploration into Context. "Follow the pattern in foo.rs" forces the executor to re-do exploration you already did.
- Use repo-relative paths from the project root. Never "the file we discussed."
- Name symbols exactly: `RetryPolicy::backoff`, not "the backoff logic."
- If a decision was made in discussion (X over Y), record the decision AND the one-line reason. The executor will face the same fork and must not re-litigate it.
- Write acceptance criteria as observable behavior ("returns 429 after 3 failed attempts"), not implementation ("uses a for loop"). Criteria that describe implementation produce tautological tests.
## Grounding (before the plan is done)
Plans rot when written from memory. Before finalizing each step plan:
1. `fs_grep` every symbol the plan references — confirm it exists and is spelled right.
2. `fs_read` the files listed in Context — confirm the pasted snippets are current.
3. Confirm the test commands actually exist (check `justfile`, `Makefile`, `package.json` scripts, CI config).
A plan referencing a function that doesn't exist fails the executor at the worst possible time: mid-implementation.
## Edge cases are a first-class section
For every step, enumerate the edge cases you can foresee: empty inputs, concurrent access, error paths, partial failures, migration/compat concerns. If an edge case belongs to a LATER step, write it in that step's plan now — not in a comment, not in your head. Executors are instructed to propagate newly discovered edge cases downstream; make their diff small by having the section exist.
## Anti-patterns
- "As discussed above" / "per our conversation" — the executor has no conversation
- File paths without pasted snippets in Context — forces re-exploration
- Acceptance criteria like "works correctly" — unmeasurable, untestable
- A step that depends on a later step — cycle; re-order or merge
- Omitting Out of scope — the executor will helpfully refactor things you didn't ask for
- Frontmatter without `depends_on` or `status` — breaks status queries and dependency checks
+83
View File
@@ -0,0 +1,83 @@
---
description: Adversarial review of implementation plans against executability, verifiability, and completeness standards. Verdict is OKAY or REJECT with line-referenced complaints. Grants read-only filesystem access for ground-truth checks.
enabled_tools: fs_read, fs_grep, fs_glob, fs_ls, fs_cat
---
You are reviewing an implementation plan BEFORE any code is written. You are the critic, not a co-author: your job is to find the ways this plan fails an executor who has zero conversation context, not to redesign the approach. A flaw caught here costs one plan edit; the same flaw caught mid-implementation costs a deviation, a handoff note, and possibly rework across steps.
The plan schema you are checking against is defined in the `plan-authoring` skill — load it alongside this one if it is not already loaded.
## Review checklist (in order)
### 1. Executability without context
Read the plan as if you know nothing but what is on the page.
- Does every referenced decision carry its rationale, or does it assume a conversation you can't see?
- Does Context contain pasted code snippets, or only file paths (which force re-exploration)?
- Are symbols named exactly? "The validation logic" is not a name.
### 2. Ground truth (verify, don't trust)
Plans are written from exploration that may be stale or wrong. Spot-check claims against the actual codebase:
- `fs_grep` for every function, type, and file the plan references. Flag anything that doesn't exist or is spelled differently.
- `fs_read` 1-2 of the pasted Context snippets at their claimed locations. Flag drift.
- Check that the Test commands exist (`justfile`, `Makefile`, `package.json`, CI config).
A plan that references phantom code is an automatic REJECT.
### 3. Verifiability
- Is every acceptance criterion a measurable, observable behavior? "Works correctly" and "is robust" are unmeasurable — flag them.
- Do the criteria describe behavior rather than implementation? Implementation-shaped criteria produce tautological tests.
- Can each criterion be checked by the listed Test commands, or is there a criterion with no way to verify it?
### 4. Dependencies and ordering
- Is `depends_on` present, acyclic, and complete? If the step uses an API introduced in step N, is N listed?
- Does anything in this step silently assume a LATER step's output? That's a cycle the frontmatter hides.
- Is the step independently verifiable — will it build and pass tests without later steps existing?
### 5. Scope and sizing
- Is Out of scope present and specific? Absent scope boundaries invite helpful refactoring.
- Is the step sized for one focused session (~1-5 files of meaningful change)? Flag steps hiding an "and then also".
- Do two steps touch the same code region without an ordering constraint between them?
### 6. Edge cases
- Is the Edge cases section present and non-empty (or explicitly "none foreseen — <reason>")?
- Think adversarially for 60 seconds: empty inputs, concurrency, error paths, partial failure, compat. Anything obvious the plan misses?
- If this step creates a new surface (API, config, schema), do DOWNSTREAM step plans account for it where they must?
## Verdict format
End with exactly one of:
```
PLAN_REVIEW: OKAY
<optional: 1-3 non-blocking observations>
```
```
PLAN_REVIEW: REJECT
Complaints:
1. <file>:<line or section> — <what is wrong> — <what would fix it>
2. ...
```
Every complaint must be actionable and point at a specific location. "The plan could be clearer" is noise; "steps/03-retry.md, Acceptance criteria #2 — 'handles errors gracefully' is unmeasurable — specify the expected behavior per error class" is signal.
## Scope discipline
- Review THE PLAN, not the design. If the approach is defensible, do not relitigate it because you'd have chosen differently. Flag design only when it is factually broken (races, missing dependency, contradicts the codebase).
- Do not rewrite the plan yourself. Complaints, not patches — the author owns the fix.
- Three strong complaints beat fifteen weak ones. If you have fifteen, the plan needs a rewrite, not a list: say so.
## Anti-patterns
- Approving without running a single ground-truth check — a syntax review, not a plan review
- REJECT for style or phrasing while missing a phantom-symbol reference
- Redesigning the author's approach in your complaints
- Vague complaints with no location and no fix direction
- Rubber-stamping a step with no acceptance criteria because "the tasks look reasonable"
@@ -0,0 +1,85 @@
---
description: End-to-end protocol for executing one step of a phased implementation plan - orient, staleness check, checklist, implement, edge-case sweep, verify, review, handoff, approval. Grants shell access for build/test commands.
enabled_tools: execute_command
---
You are executing ONE step of a phased implementation plan. Previous steps were executed in sessions you cannot see; later steps depend on what you do and document. The protocol below is ordered — do not skip phases, do not reorder them.
Companion skills: load `handoff-protocol` before Phase 1 (you must READ a handoff correctly) and keep it loaded for Phase 8 (you must WRITE one). Load `verification-gates` for Phase 6. The plan schema is defined in `plan-authoring`.
## Phase 1 - Orient
1. Read the previous step's handoff (`plans/handoffs/`, highest step number below yours). If none exists, you are step 1.
2. Read the current step plan (`plans/steps/`). Note its `depends_on` — confirm those steps' handoffs exist and report success. If a dependency failed or is missing, STOP and escalate via `user__ask`.
3. Read `plans/NOTES.md` for durable facts discovered by earlier steps.
4. Apply anything the previous handoff directed at your step (approved plan updates, warnings).
5. Set the plan's frontmatter `status: in-progress`.
## Phase 2 - Staleness check (BEFORE any edit)
The plan was written before steps 1..N-1 changed the codebase. Verify its assumptions still hold:
- Grep the symbols the plan references — do they still exist, with the claimed signatures?
- Read the plan's Context snippets at their claimed locations — has the code drifted?
- Confirm the Test commands still work.
Discrepancies are deviations — handle them via Phase 5's protocol BEFORE implementing. Executing a stale plan literally is the primary failure mode of phased work.
## Phase 3 - Checklist
`todo__init` with the step objective, then one `todo__add` per task in the plan's Tasks section, in order. Append the protocol's own gates as todos: edge-case sweep, verify, review, handoff. Mark items done with `todo__done` as you go — never batch. The checklist is what survives context compression; keep it truthful.
When you spawn an agent whose session you may need to resume, embed its session_id in the corresponding todo item text (`"Implement task 3 (coder ses_abc123)"`). If your context gets compressed mid-step, the plan repo tells you WHAT the step is and the todo list tells you WHERE you are and WHICH sessions to resume — re-orient from those, not from the summary's recollection.
## Phase 4 - Implement
- Implement ONLY what the plan's Tasks and Objective ask. Out of scope means out of scope.
- Follow the patterns pasted in the plan's Context. When plan and current codebase disagree, the codebase wins — record the deviation.
- Write tests from the plan's Acceptance criteria, not from your implementation. Criteria-first tests catch what tautological tests cannot.
- While in the code, note (do not fix) anything the planning exploration missed — feed it to Phase 5.
## Phase 5 - Edge-case sweep and deviations
**Edge cases.** For each edge case you discovered: if it belongs to THIS step, handle it (or punt explicitly in the handoff with a reason). If it belongs to a LATER step, check that step's plan — if the plan already covers it, done; if not, add it to that plan's Edge cases section and record the addition in your handoff.
**Deviations.** Classify each:
| Class | Definition | Action |
|---|---|---|
| Minor | Same objective and scope, mechanics differ (renamed symbol, moved file, extra helper) | Resolve it, document in handoff |
| Major | Changes scope, approach, interfaces, or invalidates a later step's assumptions | Do NOT silently proceed. Either escalate via `user__ask`, or write a proposed downstream-plan diff into the handoff per `handoff-protocol` |
Never rewrite a later step's Objective, Tasks, or Out of scope directly — edge-case annotations are the only direct downstream edit you may make.
## Phase 6 - Verify (order matters)
1. Formatter (if configured) — format BEFORE collecting evidence, so evidence reflects final code.
2. Linter (if configured) — fix findings your change introduced.
3. Build/typecheck — exit code 0.
4. FULL test suite — not just your new tests; regressions in untouched code are your problem if your change caused them.
Capture commands and exit codes verbatim — they go in the handoff as evidence. Pre-existing failures: note explicitly, don't fix, don't hide. Apply the 3-strike rule: after 3 failed fix attempts, stop, revert to working state, escalate.
## Phase 7 - Review
Self-review the diff with `code-review` + `ai-slop-remover` loaded. For broad steps (5+ files or crossing architectural boundaries), request an independent pass (`code-reviewer` agent) instead. Fix blockers; re-run Phase 6 after any fix.
## Phase 8 - Handoff
Gate: every todo is either done or explicitly deferred with a reason. No silent drops.
Write the handoff per `handoff-protocol` — schema, pasted evidence, deviations, downstream updates, notes for the next step. Append durable, step-independent facts to `plans/NOTES.md`. Set the plan's frontmatter `status: complete`.
## Phase 9 - User approval
Present: what was done, deviations, downstream plan changes (made or proposed), evidence summary, handoff location. Then STOP — do not begin the next step. If the user requests changes, address them, re-run Phase 6, update the handoff, and present again.
## Anti-patterns
- Editing code before the staleness check — the primary source of mid-step surprises
- Implementing "while I'm here" improvements outside the plan's scope
- Tests derived from the implementation instead of the acceptance criteria
- Collecting build/test evidence BEFORE formatting/linting, then shipping different bytes
- Running only your new tests and claiming "tests pass"
- Silently absorbing a major deviation instead of escalating or proposing a plan diff
- Rewriting downstream plan scope directly instead of proposing per `handoff-protocol`
- Starting the next step without user approval
+18
View File
@@ -7,12 +7,15 @@
# - <agent-name>_TOP_P # - <agent-name>_TOP_P
# - <agent-name>_GLOBAL_TOOLS (as a JSON string array) # - <agent-name>_GLOBAL_TOOLS (as a JSON string array)
# - <agent-name>_MCP_SERVERS (as a JSON string array) # - <agent-name>_MCP_SERVERS (as a JSON string array)
# - <agent-name>_SPAWNABLE_AGENTS (as a JSON string array; see spawnable_agents below)
# - <agent-name>_AGENT_SESSION # - <agent-name>_AGENT_SESSION
# - <agent-name>_VARIABLES (as JSON array of key-value pairs; e.g. '[{"name": "username", "value": "alex"}]') # - <agent-name>_VARIABLES (as JSON array of key-value pairs; e.g. '[{"name": "username", "value": "alex"}]')
model: openai:gpt-4o # Specify the LLM to use model: openai:gpt-4o # Specify the LLM to use
temperature: null # Set default temperature parameter, range (0, 1) temperature: null # Set default temperature parameter, range (0, 1)
top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model
reasoning_effort: null # Reasoning effort level for models that support it (e.g. low, medium, high).
# Only valid when the agent's model declares reasoning_levels.
agent_session: null # Set a session to use when starting the agent. (e.g. temp, default); defaults to globally set agent_session agent_session: null # Set a session to use when starting the agent. (e.g. temp, default); defaults to globally set agent_session
name: <agent-name> # Name of the agent, used in the UI and logs name: <agent-name> # Name of the agent, used in the UI and logs
description: <description> # Description of the agent, used in the UI description: <description> # Description of the agent, used in the UI
@@ -30,6 +33,12 @@ continuation_prompt: null # Custom prompt used when auto-continuing (opti
# Enable this agent to spawn and manage child agents in parallel. # Enable this agent to spawn and manage child agents in parallel.
# See https://github.com/Dark-Alex-17/coyote/wiki/Agents for detailed documentation. # See https://github.com/Dark-Alex-17/coyote/wiki/Agents for detailed documentation.
can_spawn_agents: false # Enable the agent to spawn child agents can_spawn_agents: false # Enable the agent to spawn child agents
# spawnable_agents: # Optional whitelist restricting which agents can be spawned via `agent__spawn`.
# - explore # If omitted (the default), ALL installed agents are spawnable. This is the unrestricted default.
# - coder # Provide a list to restrict. Match is exact and case-sensitive (use directory names).
# - oracle # An empty list ([]) means literally nothing spawnable.
# Also filters `agent__list_available` output so the LLM only sees what it can spawn.
# Graph agents (graph.yaml) ignore this; they declare spawn targets in agent nodes.
max_concurrent_agents: 4 # Maximum number of agents that can run simultaneously max_concurrent_agents: 4 # Maximum number of agents that can run simultaneously
max_agent_depth: 3 # Maximum nesting depth for sub-agents (prevents runaway spawning) max_agent_depth: 3 # Maximum nesting depth for sub-agents (prevents runaway spawning)
inject_spawn_instructions: true # Inject the default agent spawning instructions into the agent's system prompt inject_spawn_instructions: true # Inject the default agent spawning instructions into the agent's system prompt
@@ -48,6 +57,12 @@ enabled_skills: # Optional list of skills available when this a
# Must be a subset of global `visible_skills`. Omit to inherit the global default. # Must be a subset of global `visible_skills`. Omit to inherit the global default.
- git-master - git-master
- ai-slop-remover - ai-slop-remover
inject_skill_instructions: true # Inject a short hint pointing the model at `skill__list` when skills are enabled
# (default: true). Suppressed automatically when no skills are available.
skill_instructions: null # Custom text for the skill hint (optional; uses built-in default if null)
memory: null # Per-agent memory override (default: inherit). Set to `false` to disable memory
# for this agent regardless of workspace/global presence. See the Memory wiki page.
dynamic_instructions: false # Whether to use dynamic instructions for the agent; if false, static instructions are used dynamic_instructions: false # Whether to use dynamic instructions for the agent; if false, static instructions are used
instructions: | # Static instructions for the agent; ignored if dynamic instructions are used instructions: | # Static instructions for the agent; ignored if dynamic instructions are used
You are a AI agent designed to demonstrate agent capabilities. You are a AI agent designed to demonstrate agent capabilities.
@@ -86,6 +101,9 @@ conversation_starters: # Optional conversation starters for the agent
- What is the best way to exercise? - What is the best way to exercise?
- How do I manage my time effectively? - How do I manage my time effectively?
documents: # Optional documents to load for the agent documents: # Optional documents to load for the agent
# To enable graph-based RAG (entity/relationship extraction + knowledge graph retrieval),
# set `rag_extractor_model` in your global config.yaml.
# See https://github.com/Dark-Alex-17/coyote/wiki/RAG#graph-based-rag
- git:/some/repo # Explicitly tell Coyote to use the 'git' document loader using an absolute path - git:/some/repo # Explicitly tell Coyote to use the 'git' document loader using an absolute path
- pdf:some-pdf-file.pdf # Explicitly tell Coyote to use the 'pdf' document loader using a relative path - pdf:some-pdf-file.pdf # Explicitly tell Coyote to use the 'pdf' document loader using a relative path
- https://some-website.com/some-page - https://some-website.com/some-page
+75 -2
View File
@@ -2,6 +2,8 @@
model: openai:gpt-4o # Specify the LLM to use model: openai:gpt-4o # Specify the LLM to use
temperature: null # Set default temperature parameter (0, 1) temperature: null # Set default temperature parameter (0, 1)
top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model
reasoning_effort: null # Reasoning effort level for models that support it (e.g. low, medium, high).
# Only valid when the active model declares reasoning_levels. See the Clients docs.
# ---- Behavior ---- # ---- Behavior ----
stream: true # Controls whether to use the stream-style APIs when querying for completions from LLM clients. stream: true # Controls whether to use the stream-style APIs when querying for completions from LLM clients.
@@ -18,6 +20,7 @@ agent_session: null # Set a session to use when starting an agent (
# ---- Appearance ---- # ---- Appearance ----
highlight: true # Controls syntax highlighting highlight: true # Controls syntax highlighting
raw_markdown: false # When true, render markdown as raw text with syntax highlighting only. When false (default), transforms markdown syntax (headings, bold, lists, etc.) into styled terminal output
light_theme: false # Activates a light color theme when true. env: COYOTE_LIGHT_THEME light_theme: false # Activates a light color theme when true. env: COYOTE_LIGHT_THEME
# ---- Miscellaneous ---- # ---- Miscellaneous ----
@@ -31,7 +34,7 @@ sync_models_url: > # URL to sync model changes from
left_prompt: left_prompt:
'{color.red}{model}){color.green}{?session {?agent {agent}>}{session}{?role /}}{!session {?agent {agent}>}}{role}{?rag @{rag}}{color.cyan}{?session )}{!session >}{color.reset} ' '{color.red}{model}){color.green}{?session {?agent {agent}>}{session}{?role /}}{!session {?agent {agent}>}}{role}{?rag @{rag}}{color.cyan}{?session )}{!session >}{color.reset} '
right_prompt: right_prompt:
'{color.purple}{?session {?consume_tokens {consume_tokens}({consume_percent}%)}{!consume_tokens {consume_tokens}}}{color.reset}' '{color.cyan}{?reasoning_effort [{reasoning_effort}] }{color.purple}{?session {?consume_tokens {consume_tokens}({consume_percent}%)}{!consume_tokens {consume_tokens}}}{color.reset}'
# ---- Vault ---- # ---- Vault ----
# See the [Vault documentation](https://github.com/Dark-Alex-17/coyote/wiki/Vault) for more information on the Coyote vault. # See the [Vault documentation](https://github.com/Dark-Alex-17/coyote/wiki/Vault) for more information on the Coyote vault.
@@ -91,6 +94,7 @@ enabled_tools: null # Which tools to enable by default.
# Example (comma-separated form): # Example (comma-separated form):
# enabled_tools: fs,web_search_coyote # enabled_tools: fs,web_search_coyote
visible_tools: # Which tools are visible to be compiled (and are thus able to be defined in 'enabled_tools') visible_tools: # Which tools are visible to be compiled (and are thus able to be defined in 'enabled_tools')
# - ast_grep.sh
# - demo_py.py # - demo_py.py
# - demo_sh.sh # - demo_sh.sh
# - demo_ts.ts # - demo_ts.ts
@@ -133,6 +137,14 @@ enabled_mcp_servers: null # Which MCP servers to enable by default.
# - slack # - slack
# Example (comma-separated form): # Example (comma-separated form):
# enabled_mcp_servers: github,slack,ddg-search # enabled_mcp_servers: github,slack,ddg-search
no_workspace_mcp: false # Disable loading workspace-local MCP servers (default: false).
# When false (the default), Coyote merges the first workspace MCP config it finds
# into the global MCP registry at startup, checking in order:
# 1. .coyote/mcp.json
# 2. .coyote/.mcp.json (Claude-style file name)
# 3. .mcp.json (project root; Claude Code convention)
# Workspace entries shadow global ones on name collision.
# Set to true (or pass --no-workspace-mcp) to skip this entirely.
# ---- Skills ---- # ---- Skills ----
# Skills are modular knowledge or capability packs the LLM can load and unload mid-conversation. # Skills are modular knowledge or capability packs the LLM can load and unload mid-conversation.
@@ -152,6 +164,10 @@ enabled_skills: null # Which skills are available by default (no rol
# - ai-slop-remover # - ai-slop-remover
# Example (comma-separated form): # Example (comma-separated form):
# enabled_skills: git-master,ai-slop-remover # enabled_skills: git-master,ai-slop-remover
inject_skill_instructions: true # Inject a short hint pointing the model at `skill__list` when skills are enabled in
# this context. Only injected if `function_calling_support`, `skills_enabled`, and the
# effective enabled skill set is non-empty (default: true).
skill_instructions: null # Custom text used for the skill hint when injected. If null, uses built-in default.
# ---- Auto-Continue (Todo System) ---- # ---- Auto-Continue (Todo System) ----
# The auto-continue system provides built-in task tracking for improved reliability. # The auto-continue system provides built-in task tracking for improved reliability.
@@ -171,6 +187,33 @@ summarization_prompt: > # The text prompt used for creating a concise s
'Summarize the discussion briefly in 200 words or less to use as a prompt for future context.' 'Summarize the discussion briefly in 200 words or less to use as a prompt for future context.'
summary_context_prompt: > # The text prompt used for including the summary of the entire session as context to the model summary_context_prompt: > # The text prompt used for including the summary of the entire session as context to the model
'This is a summary of the chat history as a recap: ' 'This is a summary of the chat history as a recap: '
compression_keep_last: 0 # Number of most-recent messages to keep visible after compression (0 = compress all messages)
max_tool_result_chars: null # Cap on tool result characters forwarded to the model per call (null = no cap)
# ---- Memory ----
# See the [Memory documentation](https://github.com/Dark-Alex-17/coyote/wiki/Memory) for more information.
# Memory is opt-in by workspace presence (`.coyote/memory/MEMORY.md`) and global
# presence (`<config_dir>/memory/MEMORY.md`). Set `memory: false` to disable
# even when memory files exist. The cascade is: agent > session > role > app.
# Bootstrap with `coyote --init-memory [global|workspace]` to create the marker file
# the LLM needs before it will write any memory.
memory: null # null = enabled when memory exists on disk; true = force on; false = force off
memory_cap_with_tools: null # Char cap for injected memory when function calling is available (default: 6000).
# Only MEMORY.md indexes are injected; the LLM uses memory__read to fetch drill files.
memory_cap_without_tools: null # Char cap when function calling is unavailable (default: 12000).
# Indexes plus drill file bodies are injected up to this cap.
# ---- Workspace Instructions ----
# Human-curated project instructions injected read-only into the system prompt, in full.
# Coyote walks up from the current directory and injects the first match from the file
# chain below (per directory, in order). Scaffold with `coyote --init-instructions`.
# Disable per-invocation with --no-workspace-instructions, or override the chain with
# repeatable --workspace-instructions-file flags.
workspace_instructions: null # null/true = inject when an instructions file exists; false = never inject
workspace_instructions_files: null # File name chain to search, in priority order.
# Default: [COYOTE.md, AGENTS.md, CLAUDE.md, GEMINI.md]
# Set to a custom list to reorder or drop fallbacks, e.g.:
# workspace_instructions_files: [COYOTE.md]
# ---- RAG ---- # ---- RAG ----
# See the [RAG Docs](https://github.com/Dark-Alex-17/coyote/wiki/RAG) for more details. # See the [RAG Docs](https://github.com/Dark-Alex-17/coyote/wiki/RAG) for more details.
@@ -179,6 +222,9 @@ rag_reranker_model: null # Specifies the reranker model used for sorting
rag_top_k: 5 # Specifies the number of documents to retrieve for answering queries rag_top_k: 5 # Specifies the number of documents to retrieve for answering queries
rag_chunk_size: null # Defines the size of chunks for document processing in characters rag_chunk_size: null # Defines the size of chunks for document processing in characters
rag_chunk_overlap: null # Defines the overlap between chunks rag_chunk_overlap: null # Defines the overlap between chunks
rag_extractor_model: null # LLM model for graph-based entity/relationship extraction; when set, enables a graph RAG signal alongside vector and BM25
rag_extractor_prompt: null # Custom extraction prompt template; must contain __CHUNK__ placeholder; defaults to built-in prompt when null
rag_graph_hops: 1 # Number of hops to expand from matched entities at query time (0 = seed nodes only; 1 = direct neighbors; increase for denser graphs)
# Defines the query structure using variables like __CONTEXT__, __SOURCES__, and __INPUT__ to tailor searches to specific needs # Defines the query structure using variables like __CONTEXT__, __SOURCES__, and __INPUT__ to tailor searches to specific needs
rag_template: | rag_template: |
Answer the query based on the context while respecting the rules. (user query, some textual context and rules, all inside xml tags) Answer the query based on the context while respecting the rules. (user query, some textual context and rules, all inside xml tags)
@@ -305,11 +351,38 @@ clients:
api_base: https://api.mistral.ai/v1 api_base: https://api.mistral.ai/v1
api_key: '{{MISTRAL_API_KEY}}' # You can either hard-code or inject secrets from the Coyote vault api_key: '{{MISTRAL_API_KEY}}' # You can either hard-code or inject secrets from the Coyote vault
# See https://docs.x.ai/docs # See https://docs.x.ai/docs - OAuth via SuperGrok / X Premium+ subscription
- type: openai-compatible - type: openai-compatible
name: xai name: xai
api_base: https://api.x.ai/v1 api_base: https://api.x.ai/v1
api_key: '{{XAI_API_KEY}}' # You can either hard-code or inject secrets from the Coyote vault api_key: '{{XAI_API_KEY}}' # You can either hard-code or inject secrets from the Coyote vault
auth: null # When set to 'oauth', Coyote will use OAuth instead of an API key
# Authenticate with `coyote --authenticate` or `.authenticate` in the REPL
# Note: Oauth requires SuperGrok/X Premium+ subscription
# Example: private OpenAI-compatible gateway with client_credentials OAuth
# - type: openai-compatible
# name: acme-gateway
# api_base: https://gateway.acme.com/v1
# auth: oauth
# oauth:
# client_id: '{{ACME_CLIENT_ID}}'
# client_secret: '{{ACME_CLIENT_SECRET}}'
# token_url: https://auth.acme.com/oauth/token
# scopes: [openai.chat]
# flow: client_credentials
# Example: OAuth via Device Authorization Grant (RFC 8628 — for CLIs like Moonshot's kimi-code, MiniMax mmx, etc.)
# - type: openai-compatible
# name: moonshot
# api_base: https://api.kimi.com/coding/v1
# auth: oauth
# oauth:
# client_id: '{{MOONSHOT_CLIENT_ID}}'
# device_authorization_url: https://auth.kimi.com/api/oauth/device_authorization
# token_url: https://auth.kimi.com/api/oauth/token
# flow: device_code
# # use_pkce_in_device_flow: true # enable if your provider requires PKCE with device flow
# See https://docs.ai21.com/docs/overview # See https://docs.ai21.com/docs/overview
- type: openai-compatible - type: openai-compatible
+8
View File
@@ -8,6 +8,8 @@ name: <role-name> # The name of the role
model: openai:gpt-4o # The model to use for this role model: openai:gpt-4o # The model to use for this role
temperature: 0.2 # The temperature to use for this role when querying the model temperature: 0.2 # The temperature to use for this role when querying the model
top_p: 0 # The top_p to use for this role when querying the model top_p: 0 # The top_p to use for this role when querying the model
reasoning_effort: null # Reasoning effort level for models that support it (e.g. low, medium, high).
# Only valid when the role's model declares reasoning_levels.
enabled_tools: # Tools to enable for this role. Accepts a YAML list (preferred) enabled_tools: # Tools to enable for this role. Accepts a YAML list (preferred)
- fs_ls # or a comma-separated string (e.g. `enabled_tools: fs_ls,fs_cat`). - fs_ls # or a comma-separated string (e.g. `enabled_tools: fs_ls,fs_cat`).
- fs_cat # Use `all` to enable every visible tool. - fs_cat # Use `all` to enable every visible tool.
@@ -19,6 +21,12 @@ skills_enabled: true # Master switch for skills in this role (d
enabled_skills: # Skills available when this role is active. Accepts a YAML list (preferred) enabled_skills: # Skills available when this role is active. Accepts a YAML list (preferred)
- git-master # or a comma-separated string (e.g. `enabled_skills: git-master,ai-slop-remover`). - git-master # or a comma-separated string (e.g. `enabled_skills: git-master,ai-slop-remover`).
- ai-slop-remover # Must be a subset of global `visible_skills`. Omit to inherit the global default. - ai-slop-remover # Must be a subset of global `visible_skills`. Omit to inherit the global default.
inject_skill_instructions: true # Inject a short hint pointing the model at `skill__list` when skills are enabled
# (default: true). Suppressed automatically when no skills are available.
skill_instructions: null # Custom text for the skill hint (optional; uses built-in default if null)
memory: null # Per-role memory override (default: inherit). Set to `false` to disable memory
# when this role is active. See the Memory wiki page.
prompt: null # A custom prompt to use for this role that will immediately query prompt: null # A custom prompt to use for this role that will immediately query
# the model for output instead of using the instructions below # the model for output instead of using the instructions below
# Auto-Continue (Todo System) # Auto-Continue (Todo System)
+13
View File
@@ -33,6 +33,8 @@ version: "1.0" # Graph schema version. Only "1.0" is accepte
model: claude:claude-sonnet-4-6 # Default model for `llm` nodes that don't override it model: claude:claude-sonnet-4-6 # Default model for `llm` nodes that don't override it
temperature: 0.0 # Default sampling temperature for `llm` nodes temperature: 0.0 # Default sampling temperature for `llm` nodes
top_p: null # Default sampling top-p for `llm` nodes top_p: null # Default sampling top-p for `llm` nodes
reasoning_effort: null # Default reasoning effort for `llm` nodes that don't override it.
# Only valid when the model declares reasoning_levels.
global_tools: # Tool universe an `llm` node's `tools:` whitelist draws from global_tools: # Tool universe an `llm` node's `tools:` whitelist draws from
- web_search_coyote.sh - web_search_coyote.sh
@@ -63,6 +65,9 @@ enabled_skills:
- code-review - code-review
- git-master - git-master
- ai-slop-remover - ai-slop-remover
inject_skill_instructions: true # Inject a hint pointing the model at `skill__list`. Defaults to true; suppressed
# automatically when no skills are available.
skill_instructions: null # Custom text for the skill hint (optional; uses the built-in default if omitted).
conversation_starters: # Suggested prompts surfaced in the UI conversation_starters: # Suggested prompts surfaced in the UI
- "Research the current state of WebAssembly outside the browser" - "Research the current state of WebAssembly outside the browser"
@@ -173,8 +178,12 @@ nodes:
# catches violations at load time). `skills_enabled: false` would # catches violations at load time). `skills_enabled: false` would
# disable skills entirely for this node (no meta-tools exposed). # disable skills entirely for this node (no meta-tools exposed).
# Nothing is auto-loaded: the model decides when to load a skill. # Nothing is auto-loaded: the model decides when to load a skill.
skills_enabled: true # Whether skills are enabled on this llm node; defaults to 'true'
enabled_skills: enabled_skills:
- ai-slop-remover - ai-slop-remover
inject_skill_instructions: true # Override skill-hint injection for just this node. Falls back to
# agent/graph/global default when omitted.
skill_instructions: null # Per-node skill-hint text override; uses the built-in default when omitted.
output_schema: # Optional JSON Schema. The output is parsed to JSON output_schema: # Optional JSON Schema. The output is parsed to JSON
type: object # and its top-level object keys auto-merge into state type: object # and its top-level object keys auto-merge into state
properties: # (so `topic` / `needs_deep_dive` become {{topic}} etc). properties: # (so `topic` / `needs_deep_dive` become {{topic}} etc).
@@ -218,6 +227,9 @@ nodes:
chunk_size: 1000 chunk_size: 1000
chunk_overlap: 100 chunk_overlap: 100
reranker_model: null # Optional reranker for hybrid-search results reranker_model: null # Optional reranker for hybrid-search results
extractor_model: null # Optional chat model for graph-based entity/relationship extraction; enables graph RAG signal when set
extractor_prompt: null # Optional custom extraction prompt; must contain __CHUNK__ placeholder; uses built-in prompt when null
graph_hops: 1 # Graph expansion depth at query time (0 = seed nodes only; 1 = direct neighbors; increase for denser knowledge graphs)
batch_size: 100 # Optional embedding-request batch size batch_size: 100 # Optional embedding-request batch size
state_updates: # {{output}} = { context: <str>, sources: [<path>, ...] } state_updates: # {{output}} = { context: <str>, sources: [<path>, ...] }
context: "{{output.context}}" # writes `context` -> `reducers.context = concat` context: "{{output.context}}" # writes `context` -> `reducers.context = concat`
@@ -384,6 +396,7 @@ nodes:
- mcp:ddg-search # `mcp:<server>` includes that server's functions - mcp:ddg-search # `mcp:<server>` includes that server's functions
model: claude:claude-haiku-4-5 # Optional per-node model override model: claude:claude-haiku-4-5 # Optional per-node model override
temperature: 0.3 # Optional per-node sampling override temperature: 0.3 # Optional per-node sampling override
reasoning_effort: null # Optional per-node reasoning effort override (e.g. low, medium, high)
max_attempts: 2 # Retry count on transient errors only. Default 1. max_attempts: 2 # Retry count on transient errors only. Default 1.
max_iterations: 10 # Tool-call-loop turn cap. Default 10. max_iterations: 10 # Tool-call-loop turn cap. Default 10.
fallback: review # Route here if all attempts fail fallback: review # Route here if all attempts fail
+13
View File
@@ -23,3 +23,16 @@ fmt:
[arg('build_type', pattern="debug|release")] [arg('build_type', pattern="debug|release")]
build build_type='debug': build build_type='debug':
@cargo build {{ if build_type == "release" { "--release" } else { "" } }} @cargo build {{ if build_type == "release" { "--release" } else { "" } }}
# Build a multi-platform Docker image (linux/amd64 + linux/arm64).
# Requires an active buildx builder with multi-platform support and a registry login.
# version: must match an existing GitHub release tag (e.g. 0.7.4)
# image: registry/image name to push to (default: darkalex17/coyote)
[group: 'build']
docker-build version image='darkalex17/coyote':
docker buildx build \
--platform linux/amd64,linux/arm64 \
--build-arg COYOTE_VERSION={{ version }} \
--tag {{ image }}:{{ version }} \
--tag {{ image }}:latest \
.
+412 -2
View File
@@ -3,6 +3,33 @@
# - https://platform.openai.com/docs/api-reference/chat # - https://platform.openai.com/docs/api-reference/chat
- provider: openai - provider: openai
models: models:
- name: gpt-5.6-sol
max_input_tokens: 1050000
max_output_tokens: 128000
input_price: 5
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh, max]
default_reasoning_effort: medium
- name: gpt-5.6-terra
max_input_tokens: 1050000
max_output_tokens: 128000
input_price: 5
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh, max]
default_reasoning_effort: medium
- name: gpt-5.6-luna
max_input_tokens: 1050000
max_output_tokens: 128000
input_price: 5
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh, max]
default_reasoning_effort: medium
- name: gpt-5.5 - name: gpt-5.5
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -10,6 +37,8 @@
output_price: 30 output_price: 30
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: medium
- name: gpt-5.5-pro - name: gpt-5.5-pro
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -17,6 +46,8 @@
output_price: 180 output_price: 180
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: high
- name: gpt-5.4 - name: gpt-5.4
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -24,6 +55,8 @@
output_price: 15 output_price: 15
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.4-pro - name: gpt-5.4-pro
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -31,6 +64,8 @@
output_price: 180 output_price: 180
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: medium
- name: gpt-5.4-mini - name: gpt-5.4-mini
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -38,6 +73,8 @@
output_price: 4.5 output_price: 4.5
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.4-nano - name: gpt-5.4-nano
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -45,6 +82,8 @@
output_price: 1.25 output_price: 1.25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.3-codex - name: gpt-5.3-codex
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -52,6 +91,8 @@
output_price: 14 output_price: 14
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh]
default_reasoning_effort: medium
- name: chat-latest - name: chat-latest
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -66,6 +107,17 @@
output_price: 14 output_price: 14
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.2-pro
max_input_tokens: 400000
max_output_tokens: 128000
input_price: 21
output_price: 168
supports_vision: true
supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: medium
- name: gpt-5.1 - name: gpt-5.1
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -73,6 +125,8 @@
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high]
default_reasoning_effort: none
- name: gpt-5.1-chat-latest - name: gpt-5.1-chat-latest
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -80,6 +134,8 @@
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high]
default_reasoning_effort: none
- name: gpt-5 - name: gpt-5
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -87,6 +143,8 @@
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: gpt-5-chat-latest - name: gpt-5-chat-latest
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -94,6 +152,8 @@
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: gpt-5-mini - name: gpt-5-mini
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -151,6 +211,8 @@
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
system_prompt_prefix: Formatting re-enabled system_prompt_prefix: Formatting re-enabled
reasoning_levels: [low, medium, high]
default_reasoning_effort: medium
patch: patch:
body: body:
max_tokens: null max_tokens: null
@@ -258,24 +320,38 @@
# - https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent # - https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent
- provider: gemini - provider: gemini
models: models:
- name: gemini-3.6-flash
max_input_tokens: 1048576
max_output_tokens: 65536
input_price: 1.5
output_price: 7.5
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_level: medium
- name: gemini-3.5-flash - name: gemini-3.5-flash
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
input_price: 0.2 input_price: 0.2
output_price: 1.5 output_price: 1.5
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: gemini-3-flash-preview - name: gemini-3-flash-preview
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
input_price: 0.2 input_price: 0.2
output_price: 1.5 output_price: 1.5
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: high
- name: gemini-3.1-flash-lite - name: gemini-3.1-flash-lite
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
input_price: 0.2 input_price: 0.2
output_price: 1.5 output_price: 1.5
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: minimal
- name: gemini-3.1-pro-preview - name: gemini-3.1-pro-preview
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65535 max_output_tokens: 65535
@@ -283,6 +359,8 @@
output_price: 2.5 output_price: 2.5
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash - name: gemini-2.5-flash
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
@@ -297,6 +375,8 @@
output_price: 0 output_price: 0
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash-lite - name: gemini-2.5-flash-lite
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 64000 max_output_tokens: 64000
@@ -308,10 +388,14 @@
max_input_tokens: 1048576 max_input_tokens: 1048576
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, high]
default_reasoning_level: high
- name: gemini-3-flash-preview - name: gemini-3-flash-preview
max_input_tokens: 1048576 max_input_tokens: 1048576
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_level: high
- name: gemma-3-27b-it - name: gemma-3-27b-it
max_input_tokens: 131072 max_input_tokens: 131072
max_output_tokens: 8192 max_output_tokens: 8192
@@ -329,6 +413,16 @@
# - https://docs.anthropic.com/en/api/messages # - https://docs.anthropic.com/en/api/messages
- provider: claude - provider: claude
models: models:
- name: claude-fable-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 10
output_price: 50
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-8 - name: claude-opus-4-8
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -337,6 +431,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-7 - name: claude-opus-4-7
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -345,6 +441,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-6 - name: claude-opus-4-6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -353,6 +451,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: claude-opus-4-6:thinking - name: claude-opus-4-6:thinking
real_name: claude-opus-4-6 real_name: claude-opus-4-6
max_input_tokens: 200000 max_input_tokens: 200000
@@ -369,6 +469,16 @@
thinking: thinking:
type: enabled type: enabled
budget_tokens: 16000 budget_tokens: 16000
- name: claude-sonnet-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 3
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-sonnet-4-6 - name: claude-sonnet-4-6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -377,6 +487,8 @@
output_price: 15 output_price: 15
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: claude-sonnet-4-6:thinking - name: claude-sonnet-4-6:thinking
real_name: claude-sonnet-4-6 real_name: claude-sonnet-4-6
max_input_tokens: 200000 max_input_tokens: 200000
@@ -700,14 +812,65 @@
# - https://docs.x.ai/docs/models # - https://docs.x.ai/docs/models
# - https://docs.x.ai/docs/api-reference#chat-completions # - https://docs.x.ai/docs/api-reference#chat-completions
- provider: xai - provider: xai
oauth:
client_id: b1a00492-073a-47ea-816f-4c329264a828
authorize_url: https://auth.x.ai/oauth2/authorize
token_url: https://auth.x.ai/oauth2/token
scopes:
- openid
- profile
- email
- offline_access
- grok-cli:access
- api:access
redirect_port: 56121
flow: pkce
token_request_format: form_url_encoded
extra_authorize_params:
plan: generic
referrer: coyote
echo_pkce_in_token_exchange: true
models: models:
- name: grok-4.5
input_price: 2
output_price: 6
max_input_tokens: 256000
supports_function_calling: true
- name: grok-build-0.1
input_price: 1
output_price: 2
max_input_tokens: 256000
supports_function_calling: true
- name: grok-4.3
input_price: 1.25
output_price: 2.5
max_input_tokens: 1000000
supports_function_calling: true
- name: grok-4.20
real_name: grok-4.20-multi-agent-0309
input_price: 1.25
output_price: 2.5
max_input_tokens: 1000000
supports_function_calling: true
- name: grok-4.20-reasoning
real_name: grok-4.20-0309-reasoning
input_price: 1.25
output_price: 2.5
max_input_tokens: 1000000
supports_function_calling: true
- name: grok-4.20-non-reasoning
real_name: grok-4.20-0309-non-reasoning
input_price: 1.25
output_price: 2.5
max_input_tokens: 1000000
supports_function_calling: true
- name: grok-4-1-fast-non-reasoning - name: grok-4-1-fast-non-reasoning
max_input_tokens: 2000000 max_input_tokens: 1000000
input_price: 0.2 input_price: 0.2
output_price: 0.5 output_price: 0.5
supports_function_calling: true supports_function_calling: true
- name: grok-4-1-fast-reasoning - name: grok-4-1-fast-reasoning
max_input_tokens: 2000000 max_input_tokens: 1000000
input_price: 0.2 input_price: 0.2
output_price: 0.5 output_price: 0.5
supports_function_calling: true supports_function_calling: true
@@ -819,18 +982,24 @@
input_price: 0.2 input_price: 0.2
output_price: 1.5 output_price: 1.5
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: gemini-3-flash-preview - name: gemini-3-flash-preview
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
input_price: 0.2 input_price: 0.2
output_price: 1.5 output_price: 1.5
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: high
- name: gemini-3.1-flash-lite - name: gemini-3.1-flash-lite
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
input_price: 0.2 input_price: 0.2
output_price: 1.5 output_price: 1.5
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, high]
default_reasoning_effort: minimal
- name: gemini-3.1-pro-preview - name: gemini-3.1-pro-preview
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
@@ -838,6 +1007,8 @@
output_price: 12 output_price: 12
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash - name: gemini-2.5-flash
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65535 max_output_tokens: 65535
@@ -845,6 +1016,8 @@
output_price: 2.5 output_price: 2.5
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: medium
- name: gemini-2.5-pro - name: gemini-2.5-pro
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
@@ -852,6 +1025,8 @@
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash-lite - name: gemini-2.5-flash-lite
max_input_tokens: 1048576 max_input_tokens: 1048576
max_output_tokens: 65536 max_output_tokens: 65536
@@ -863,10 +1038,24 @@
max_input_tokens: 1048576 max_input_tokens: 1048576
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, high]
default_reasoning_effort: high
- name: gemini-3-flash-preview - name: gemini-3-flash-preview
max_input_tokens: 1048576 max_input_tokens: 1048576
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: high
- name: claude-fable-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 10
output_price: 50
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-8 - name: claude-opus-4-8
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -875,6 +1064,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-7 - name: claude-opus-4-7
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -883,6 +1074,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-6 - name: claude-opus-4-6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -906,6 +1099,16 @@
thinking: thinking:
type: enabled type: enabled
budget_tokens: 16000 budget_tokens: 16000
- name: claude-sonnet-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 3
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-sonnet-4-6 - name: claude-sonnet-4-6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -914,6 +1117,8 @@
output_price: 15 output_price: 15
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: claude-sonnet-4-6:thinking - name: claude-sonnet-4-6:thinking
real_name: claude-sonnet-4-6 real_name: claude-sonnet-4-6
max_input_tokens: 200000 max_input_tokens: 200000
@@ -1038,6 +1243,16 @@
# - https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference-call.html # - https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference-call.html
- provider: bedrock - provider: bedrock
models: models:
- name: us.anthropic.claude-fable-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 10
output_price: 50
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-8 - name: us.anthropic.claude-opus-4-8
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1046,6 +1261,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-7 - name: us.anthropic.claude-opus-4-7
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1054,6 +1271,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-6-v1 - name: us.anthropic.claude-opus-4-6-v1
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -1062,6 +1281,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-6-v1:thinking - name: us.anthropic.claude-opus-4-6-v1:thinking
real_name: us.anthropic.claude-opus-4-6-v1 real_name: us.anthropic.claude-opus-4-6-v1
max_input_tokens: 200000 max_input_tokens: 200000
@@ -1079,6 +1300,16 @@
thinking: thinking:
type: enabled type: enabled
budget_tokens: 16000 budget_tokens: 16000
- name: us.anthropic.claude-sonnet-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 3
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: us.anthropic.claude-sonnet-4-6 - name: us.anthropic.claude-sonnet-4-6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -1087,6 +1318,8 @@
output_price: 15 output_price: 15
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: us.anthropic.claude-sonnet-4-6:thinking - name: us.anthropic.claude-sonnet-4-6:thinking
real_name: us.anthropic.claude-sonnet-4-6 real_name: us.anthropic.claude-sonnet-4-6
max_input_tokens: 200000 max_input_tokens: 200000
@@ -1468,6 +1701,30 @@
# - https://platform.moonshot.cn/docs/api/chat#%E5%85%AC%E5%BC%80%E7%9A%84%E6%9C%8D%E5%8A%A1%E5%9C%B0%E5%9D%80 # - https://platform.moonshot.cn/docs/api/chat#%E5%85%AC%E5%BC%80%E7%9A%84%E6%9C%8D%E5%8A%A1%E5%9C%B0%E5%9D%80
- provider: moonshot - provider: moonshot
models: models:
- name: kimi-k3
max_input_tokens: 1048576
input_price: 3
output_price: 15
supports_vision: true
supports_function_calling: true
- name: kimi-k2.7-code
max_input_tokens: 262144
input_price: 0.95
output_price: 4
supports_vision: true
supports_function_calling: true
- name: kimi-k2.7-code-highspeed
max_input_tokens: 262144
input_price: 1.9
output_price: 8
supports_vision: true
supports_function_calling: true
- name: kimi-k2.6
max_input_tokens: 262144
input_price: 0.95
output_price: 4
supports_vision: true
supports_function_calling: true
- name: kimi-k2.5 - name: kimi-k2.5
max_input_tokens: 262144 max_input_tokens: 262144
input_price: 0.56 input_price: 0.56
@@ -1502,6 +1759,18 @@
# - https://platform.deepseek.com/api-docs/api/create-chat-completion # - https://platform.deepseek.com/api-docs/api/create-chat-completion
- provider: deepseek - provider: deepseek
models: models:
- name: deepseek-v4-pro
max_input_tokens: 1000000
max_output_tokens: 384000
input_price: 0.435
output_price: 0.87
supports_function_calling: true
- name: deepseek-v4-flash
max_input_tokens: 1000000
max_output_tokens: 384000
input_price: 0.14
output_price: 0.28
supports_function_calling: true
- name: deepseek-chat - name: deepseek-chat
max_input_tokens: 64000 max_input_tokens: 64000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -1570,6 +1839,16 @@
# - https://platform.minimaxi.com/document/ChatCompletion%20v2 # - https://platform.minimaxi.com/document/ChatCompletion%20v2
- provider: minimax - provider: minimax
models: models:
- name: minimax-m3
max_input_tokens: 1000000
input_price: 4.2
output_price: 16.8
supports_function_calling: true
- name: minimax-m2.7
max_input_tokens: 204800
input_price: 0.294
output_price: 1.176
supports_function_calling: true
- name: minimax-m2.5 - name: minimax-m2.5
max_input_tokens: 204800 max_input_tokens: 204800
input_price: 0.294 input_price: 0.294
@@ -1596,6 +1875,33 @@
# - https://openrouter.ai/docs/api-reference/chat-completion # - https://openrouter.ai/docs/api-reference/chat-completion
- provider: openrouter - provider: openrouter
models: models:
- name: openai/gpt-5.6-sol
max_input_tokens: 1050000
max_output_tokens: 128000
input_price: 5
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh, max]
default_reasoning_effort: medium
- name: openai/gpt-5.6-terra
max_input_tokens: 1050000
max_output_tokens: 128000
input_price: 5
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh, max]
default_reasoning_effort: medium
- name: openai/gpt-5.6-luna
max_input_tokens: 1050000
max_output_tokens: 128000
input_price: 5
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh, max]
default_reasoning_effort: medium
- name: openai/gpt-5.5 - name: openai/gpt-5.5
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1603,6 +1909,8 @@
output_price: 30 output_price: 30
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5.5-pro - name: openai/gpt-5.5-pro
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1610,6 +1918,8 @@
output_price: 180 output_price: 180
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: high
- name: openai/gpt-5.4 - name: openai/gpt-5.4
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1617,6 +1927,8 @@
output_price: 15 output_price: 15
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.4-pro - name: openai/gpt-5.4-pro
max_input_tokens: 1050000 max_input_tokens: 1050000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1624,6 +1936,8 @@
output_price: 180 output_price: 180
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5.4-mini - name: openai/gpt-5.4-mini
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1631,6 +1945,8 @@
output_price: 4.5 output_price: 4.5
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.4-nano - name: openai/gpt-5.4-nano
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1638,6 +1954,8 @@
output_price: 1.25 output_price: 1.25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.3-codex - name: openai/gpt-5.3-codex
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1645,6 +1963,8 @@
output_price: 14 output_price: 14
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5.2 - name: openai/gpt-5.2
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1652,6 +1972,17 @@
output_price: 14 output_price: 14
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.2-pro
max_input_tokens: 400000
max_output_tokens: 128000
input_price: 21
output_price: 168
supports_vision: true
supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5 - name: openai/gpt-5
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1659,6 +1990,8 @@
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: openai/gpt-5-mini - name: openai/gpt-5-mini
max_input_tokens: 400000 max_input_tokens: 400000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1696,18 +2029,67 @@
input_price: 0.04 input_price: 0.04
output_price: 0.16 output_price: 0.16
supports_function_calling: true supports_function_calling: true
- name: google/gemini-3.5-flash
max_input_tokens: 1048576
max_output_tokens: 65536
input_price: 0.2
output_price: 1.5
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: google/gemini-3-flash-preview
max_input_tokens: 1048576
max_output_tokens: 65536
input_price: 0.2
output_price: 1.5
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: high
- name: google/gemini-3.1-flash-lite
max_input_tokens: 1048576
max_output_tokens: 65536
input_price: 0.2
output_price: 1.5
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: minimal
- name: google/gemini-3.1-pro-preview
max_input_tokens: 1048576
max_output_tokens: 65535
input_price: 0.3
output_price: 2.5
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: google/gemini-3-pro-preview
max_input_tokens: 1048576
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, high]
default_reasoning_level: high
- name: google/gemini-3-flash-preview
max_input_tokens: 1048576
supports_vision: true
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_level: high
- name: google/gemini-2.5-flash - name: google/gemini-2.5-flash
max_input_tokens: 1048576 max_input_tokens: 1048576
input_price: 0.3 input_price: 0.3
output_price: 2.5 output_price: 2.5
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: low
- name: google/gemini-2.5-pro - name: google/gemini-2.5-pro
max_input_tokens: 1048576 max_input_tokens: 1048576
input_price: 1.25 input_price: 1.25
output_price: 10 output_price: 10
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: google/gemini-2.5-flash-lite - name: google/gemini-2.5-flash-lite
max_input_tokens: 1048576 max_input_tokens: 1048576
input_price: 0.3 input_price: 0.3
@@ -1729,6 +2111,16 @@
max_input_tokens: 131072 max_input_tokens: 131072
input_price: 0.1 input_price: 0.1
output_price: 0.2 output_price: 0.2
- name: anthropic/claude-fable-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 10
output_price: 50
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4-8 - name: anthropic/claude-opus-4-8
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1737,6 +2129,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4-7 - name: anthropic/claude-opus-4-7
max_input_tokens: 1000000 max_input_tokens: 1000000
max_output_tokens: 128000 max_output_tokens: 128000
@@ -1745,6 +2139,8 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4.6 - name: anthropic/claude-opus-4.6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -1753,6 +2149,18 @@
output_price: 25 output_price: 25
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: anthropic/claude-sonnet-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 3
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: anthropic/claude-sonnet-4.6 - name: anthropic/claude-sonnet-4.6
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
@@ -1761,6 +2169,8 @@
output_price: 15 output_price: 15
supports_vision: true supports_vision: true
supports_function_calling: true supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4.5 - name: anthropic/claude-opus-4.5
max_input_tokens: 200000 max_input_tokens: 200000
max_output_tokens: 8192 max_output_tokens: 8192
+3 -3
View File
@@ -39,7 +39,7 @@ switch ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture) {
if (-not $BinDir) { if (-not $BinDir) {
if ($isWin) { $BinDir = Join-Path $env:LOCALAPPDATA 'coyote\bin' } if ($isWin) { $BinDir = Join-Path $env:LOCALAPPDATA 'coyote\bin' }
else { $home = $env:HOME; if (-not $home) { $home = (Get-Item -Path ~).FullName }; $BinDir = Join-Path $home '.local/bin' } else { $userHome = $env:HOME; if (-not $userHome) { $userHome = (Get-Item -Path ~).FullName }; $BinDir = Join-Path $userHome '.local/bin' }
} }
New-Item -ItemType Directory -Force -Path $BinDir | Out-Null New-Item -ItemType Directory -Force -Path $BinDir | Out-Null
@@ -95,13 +95,13 @@ if ($asset.name -match '\.zip$') {
[System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir) [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir)
} elseif ($asset.name -match '\.tar\.gz$' -or $asset.name -match '\.tgz$') { } elseif ($asset.name -match '\.tar\.gz$' -or $asset.name -match '\.tgz$') {
$tar = Get-Command tar -ErrorAction SilentlyContinue $tar = Get-Command tar -ErrorAction SilentlyContinue
if ($tar) { & $tar.FullName -xzf $archive -C $extractDir } if ($tar) { & $tar.Source -xzf $archive -C $extractDir }
else { Fail "Asset is tar archive but 'tar' is not available." } else { Fail "Asset is tar archive but 'tar' is not available." }
} else { } else {
try { Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir) } try { Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir) }
catch { catch {
$tar = Get-Command tar -ErrorAction SilentlyContinue $tar = Get-Command tar -ErrorAction SilentlyContinue
if ($tar) { & $tar.FullName -xf $archive -C $extractDir } else { Fail "Unknown archive format; neither zip nor tar workable." } if ($tar) { & $tar.Source -xf $archive -C $extractDir } else { Fail "Unknown archive format; neither zip nor tar workable." }
} }
} }
Regular → Executable
+12 -21
View File
@@ -133,30 +133,21 @@ else
echo "Error: unsupported OS for this installer: $OS" >&2; exit 1 echo "Error: unsupported OS for this installer: $OS" >&2; exit 1
fi fi
DL_URLS=$(grep -oE '"browser_download_url":[[:space:]]*"[^"]+"' "$JSON" \
| sed -E 's/.*"browser_download_url":[[:space:]]*"//; s/"$//' \
|| true)
ASSET_NAME=""; ASSET_URL="" ASSET_NAME=""; ASSET_URL=""
for candidate in "${ASSET_CANDIDATES[@]}"; do for candidate in "${ASSET_CANDIDATES[@]}"; do
NAME=$(grep -oE '"name":\s*"[^"]+"' "$JSON" | sed 's/"name":\s*"//; s/"$//' | grep -Fx "$candidate" || true) while IFS= read -r url; do
if [[ -n "$NAME" ]]; then [[ -z "$url" ]] && continue
ASSET_NAME="$NAME" if [[ "$url" == */"$candidate" ]]; then
ASSET_URL=$(awk -v pat="$NAME" ' ASSET_NAME="$candidate"
BEGIN{ FS=":"; want=0 } ASSET_URL="$url"
/"name"/ { break
line=$0;
gsub(/^\s+|\s+$/,"",line);
gsub(/"name"\s*:\s*"|"/ ,"", line);
want = (line==pat) ? 1 : 0;
next
}
want==1 && /"browser_download_url"/ {
u=$0;
gsub(/^\s+|\s+$/,"",u);
gsub(/.*"browser_download_url"\s*:\s*"|".*/ ,"", u);
print u;
exit
}
' "$JSON")
if [[ -n "$ASSET_URL" ]]; then break; fi
fi fi
done <<< "$DL_URLS"
[[ -n "$ASSET_URL" ]] && break
done done
if [[ -z "$ASSET_URL" ]]; then if [[ -z "$ASSET_URL" ]]; then
+29 -1
View File
@@ -5,9 +5,9 @@ use crate::utils::list_file_names;
use crate::vault::Vault; use crate::vault::Vault;
use clap_complete::{CompletionCandidate, Shell, generate}; use clap_complete::{CompletionCandidate, Shell, generate};
use clap_complete_nushell::Nushell; use clap_complete_nushell::Nushell;
use std::env;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::io; use std::io;
use std::{env, fs};
const COYOTE_CLI_NAME: &str = "coyote"; const COYOTE_CLI_NAME: &str = "coyote";
@@ -134,6 +134,34 @@ pub(super) fn session_completer(current: &OsStr) -> Vec<CompletionCandidate> {
.collect() .collect()
} }
pub(super) fn mcp_server_completer(current: &OsStr) -> Vec<CompletionCandidate> {
let cur = current.to_string_lossy();
let content = match fs::read_to_string(paths::mcp_config_file()) {
Ok(c) => c,
Err(_) => return vec![],
};
let json: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(_) => return vec![],
};
let servers = match json.get("mcpServers").and_then(|v| v.as_object()) {
Some(s) => s,
None => return vec![],
};
servers
.iter()
.filter(|(_, v)| {
v.get("type")
.and_then(|t| t.as_str())
.map(|t| t == "http" || t == "sse")
.unwrap_or(false)
})
.filter(|(k, _)| k.starts_with(&*cur))
.map(|(k, _)| CompletionCandidate::new(k))
.collect()
}
pub(super) fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> { pub(super) fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> {
let cur = current.to_string_lossy(); let cur = current.to_string_lossy();
match load_app_config_for_completion() { match load_app_config_for_completion() {
+256 -100
View File
@@ -1,12 +1,12 @@
mod completer; mod completer;
use crate::cli::completer::{ use crate::cli::completer::{
ShellCompletion, agent_completer, macro_completer, model_completer, rag_completer, ShellCompletion, agent_completer, macro_completer, mcp_server_completer, model_completer,
role_completer, secrets_completer, session_completer, rag_completer, role_completer, secrets_completer, session_completer,
}; };
use crate::config::{AssetCategory, InstallFilter}; use crate::config::{AssetCategory, InstallFilter, MemoryScope};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use clap::ValueHint; use clap::{ArgGroup, ValueHint};
use clap::{Parser, crate_authors, crate_description, crate_version}; use clap::{Parser, crate_authors, crate_description, crate_version};
use clap_complete::ArgValueCompleter; use clap_complete::ArgValueCompleter;
use is_terminal::IsTerminal; use is_terminal::IsTerminal;
@@ -27,9 +27,26 @@ use std::io::{Read, stdin};
{usage-heading} {usage} {usage-heading} {usage}
{all-args}{after-help} {all-args}{after-help}
" ",
group(
ArgGroup::new("sbx-mode")
.args(["sandbox", "fresh", "no_mixins"])
.multiple(true)
.conflicts_with_all([
"model", "prompt", "role", "session", "agent", "rag", "rebuild_rag",
"macro_name", "execute", "code", "file", "no_stream", "no_memory",
"init_memory", "dry_run", "info", "build_tools", "install",
"install_from", "sync_models", "list_models", "list_roles",
"list_sessions", "list_agents", "list_rags", "list_macros",
"list_skills", "skill", "tail_logs", "completions", "update",
])
),
)] )]
pub struct Cli { pub struct Cli {
/// Input text
#[arg(trailing_var_arg = true)]
text: Vec<String>,
/// Select a LLM model /// Select a LLM model
#[arg(short, long, add = ArgValueCompleter::new(model_completer))] #[arg(short, long, add = ArgValueCompleter::new(model_completer))]
pub model: Option<String>, pub model: Option<String>,
@@ -39,30 +56,6 @@ pub struct Cli {
/// Select a role /// Select a role
#[arg(short, long, add = ArgValueCompleter::new(role_completer))] #[arg(short, long, add = ArgValueCompleter::new(role_completer))]
pub role: Option<String>, pub role: Option<String>,
/// Start or join a session
#[arg(short = 's', long, add = ArgValueCompleter::new(session_completer))]
pub session: Option<Option<String>>,
/// Ensure the session is empty
#[arg(long)]
pub empty_session: bool,
/// Ensure the new conversation is saved to the session
#[arg(long)]
pub save_session: bool,
/// Start an agent
#[arg(short = 'a', long, add = ArgValueCompleter::new(agent_completer))]
pub agent: Option<String>,
/// Set agent variables
#[arg(long, value_names = ["NAME", "VALUE"], num_args = 2)]
pub agent_variable: Vec<String>,
/// Start a RAG
#[arg(long, add = ArgValueCompleter::new(rag_completer))]
pub rag: Option<String>,
/// Rebuild the RAG to sync document changes
#[arg(long)]
pub rebuild_rag: bool,
/// Execute a macro
#[arg(long = "macro", value_name = "MACRO", add = ArgValueCompleter::new(macro_completer))]
pub macro_name: Option<String>,
/// Execute commands in natural language /// Execute commands in natural language
#[arg(short = 'e', long)] #[arg(short = 'e', long)]
pub execute: bool, pub execute: bool,
@@ -75,92 +68,188 @@ pub struct Cli {
/// Turn off stream mode /// Turn off stream mode
#[arg(short = 'S', long)] #[arg(short = 'S', long)]
pub no_stream: bool, pub no_stream: bool,
/// Render markdown as raw text with syntax highlighting only (skip the rich markdown renderer)
#[arg(long)]
pub raw_markdown: bool,
/// Display the message without sending it /// Display the message without sending it
#[arg(long)] #[arg(long)]
pub dry_run: bool, pub dry_run: bool,
/// Display information /// Disable loading workspace MCP servers from .coyote/mcp.json, .coyote/.mcp.json, or .mcp.json
#[arg(long)] #[arg(long)]
pub info: bool, pub no_workspace_mcp: bool,
/// Build all configured Bash tool scripts /// Disable memory for this invocation
#[arg(long)] #[arg(long)]
pub build_tools: bool, pub no_memory: bool,
/// Reinstall bundled assets, overwriting any local changes /// Disable loading workspace instructions (COYOTE.md/AGENTS.md/CLAUDE.md/etc.) for this invocation
#[arg(long, value_name = "CATEGORY", value_enum)]
pub install: Option<AssetCategory>,
/// Install assets from a remote git repository (URL may be suffixed with #<ref>)
#[arg(long, value_name = "GIT_URL")]
pub install_from: Option<String>,
/// Restrict --install-from to a single asset category
#[arg(long, value_name = "CATEGORY", value_enum, requires = "install_from")]
pub filter: Option<InstallFilter>,
/// Overwrite all conflicts without prompting (used with --install-from)
#[arg(long, requires = "install_from")]
pub install_force: bool,
/// Sync models updates
#[arg(long)] #[arg(long)]
pub sync_models: bool, pub no_workspace_instructions: bool,
/// List all available chat models /// Override the workspace instructions file chain for this invocation (repeatable, priority order)
#[arg(long, value_name = "NAME")]
pub workspace_instructions_file: Vec<String>,
/// Skip permission prompts by setting AUTO_CONFIRM for all tools (dangerous!)
#[arg(long)] #[arg(long)]
pub list_models: bool, pub dangerously_skip_permissions: bool,
/// List all roles
#[arg(long)] /// Start or join a session
pub list_roles: bool, #[arg(short = 's', long, help_heading = "Session & Memory", add = ArgValueCompleter::new(session_completer))]
/// List all sessions pub session: Option<Option<String>>,
#[arg(long)] /// Ensure the session is empty
pub list_sessions: bool, #[arg(long, help_heading = "Session & Memory")]
/// List all agents pub empty_session: bool,
#[arg(long)] /// Ensure the new conversation is saved to the session
pub list_agents: bool, #[arg(long, help_heading = "Session & Memory")]
/// List all RAGs pub save_session: bool,
#[arg(long)] /// Bootstrap a memory marker so coyote begins loading memory next run
pub list_rags: bool, #[arg(
/// List all macros long,
#[arg(long)] value_name = "SCOPE",
pub list_macros: bool, value_enum,
/// List all installed skills help_heading = "Session & Memory"
#[arg(long)] )]
pub list_skills: bool, pub init_memory: Option<MemoryScope>,
/// Scaffold a COYOTE.md workspace instructions file in the current directory
#[arg(long, help_heading = "Session & Memory")]
pub init_instructions: bool,
/// Pre-load an existing skill into the session (repeatable). If a single /// Pre-load an existing skill into the session (repeatable). If a single
/// `--skill <NAME>` is given and the skill doesn't exist, opens $EDITOR /// `--skill <NAME>` is given and the skill doesn't exist, opens $EDITOR
/// with a scaffold to create it. /// with a scaffold to create it.
#[arg(long, value_name = "NAME")] #[arg(long, value_name = "NAME", help_heading = "Session & Memory")]
pub skill: Vec<String>, pub skill: Vec<String>,
/// Input text
#[arg(trailing_var_arg = true)] /// Start an agent
text: Vec<String>, #[arg(short = 'a', long, help_heading = "Agents, RAG & Macros", add = ArgValueCompleter::new(agent_completer))]
/// Tail logs pub agent: Option<String>,
#[arg(long)] /// Set agent variables
pub tail_logs: bool, #[arg(long, value_names = ["NAME", "VALUE"], num_args = 2, help_heading = "Agents, RAG & Macros")]
/// Disable colored log output pub agent_variable: Vec<String>,
#[arg(long, requires = "tail_logs")] /// Start a RAG
pub disable_log_colors: bool, #[arg(long, help_heading = "Agents, RAG & Macros", add = ArgValueCompleter::new(rag_completer))]
/// Add a secret to the Coyote vault pub rag: Option<String>,
#[arg(long, value_name = "SECRET_NAME", exclusive = true)] /// Rebuild the RAG to sync document changes
pub add_secret: Option<String>, #[arg(long, help_heading = "Agents, RAG & Macros")]
/// Decrypt a secret from the Coyote vault and print the plaintext pub rebuild_rag: bool,
#[arg(long, value_name = "SECRET_NAME", exclusive = true, add = ArgValueCompleter::new(secrets_completer))] /// Execute a macro
pub get_secret: Option<String>, #[arg(long = "macro", value_name = "MACRO", help_heading = "Agents, RAG & Macros", add = ArgValueCompleter::new(macro_completer))]
/// Update an existing secret in the Coyote vault pub macro_name: Option<String>,
#[arg(long, value_name = "SECRET_NAME", exclusive = true, add = ArgValueCompleter::new(secrets_completer))]
pub update_secret: Option<String>, /// List all available chat models
/// Delete a secret from the Coyote vault #[arg(long, help_heading = "List & Discovery")]
#[arg(long, value_name = "SECRET_NAME", exclusive = true, add = ArgValueCompleter::new(secrets_completer))] pub list_models: bool,
pub delete_secret: Option<String>, /// List all roles
/// List all secrets stored in the Coyote vault #[arg(long, help_heading = "List & Discovery")]
#[arg(long, exclusive = true)] pub list_roles: bool,
pub list_secrets: bool, /// List all sessions
/// Authenticate with an LLM provider using OAuth (e.g., --authenticate client_name) #[arg(long, help_heading = "List & Discovery")]
#[arg(long, exclusive = true, value_name = "CLIENT_NAME")] pub list_sessions: bool,
pub authenticate: Option<Option<String>>, /// List all agents
/// Generate static shell completion scripts #[arg(long, help_heading = "List & Discovery")]
#[arg(long, value_name = "SHELL", value_enum)] pub list_agents: bool,
pub completions: Option<ShellCompletion>, /// List all RAGs
#[arg(long, help_heading = "List & Discovery")]
pub list_rags: bool,
/// List all macros
#[arg(long, help_heading = "List & Discovery")]
pub list_macros: bool,
/// List all installed skills
#[arg(long, help_heading = "List & Discovery")]
pub list_skills: bool,
/// Reinstall bundled assets, overwriting any local changes
#[arg(
long,
value_name = "CATEGORY",
value_enum,
help_heading = "Installation & Updates"
)]
pub install: Option<AssetCategory>,
/// Install assets from a remote git repository (URL may be suffixed with #<ref>)
#[arg(long, value_name = "GIT_URL", help_heading = "Installation & Updates")]
pub install_from: Option<String>,
/// Restrict --install-from to a single asset category
#[arg(
long,
value_name = "CATEGORY",
value_enum,
requires = "install_from",
help_heading = "Installation & Updates"
)]
pub filter: Option<InstallFilter>,
/// Overwrite all conflicts without prompting (used with --install-from)
#[arg(
long,
requires = "install_from",
help_heading = "Installation & Updates"
)]
pub install_force: bool,
/// Sync models updates
#[arg(long, help_heading = "Installation & Updates")]
pub sync_models: bool,
/// Update Coyote to the latest release, or to a specific version /// Update Coyote to the latest release, or to a specific version
#[arg(long, value_name = "VERSION")] #[arg(long, value_name = "VERSION", help_heading = "Installation & Updates")]
pub update: Option<Option<String>>, pub update: Option<Option<String>>,
/// With --update, update even if Coyote was installed via a package manager /// With --update, update even if Coyote was installed via a package manager
#[arg(long, requires = "update")] #[arg(long, requires = "update", help_heading = "Installation & Updates")]
pub force: bool, pub force: bool,
/// Add a secret to the Coyote vault
#[arg(
long,
value_name = "SECRET_NAME",
exclusive = true,
help_heading = "Vault & Secrets"
)]
pub add_secret: Option<String>,
/// Decrypt a secret from the Coyote vault and print the plaintext
#[arg(long, value_name = "SECRET_NAME", exclusive = true, help_heading = "Vault & Secrets", add = ArgValueCompleter::new(secrets_completer))]
pub get_secret: Option<String>,
/// Update an existing secret in the Coyote vault
#[arg(long, value_name = "SECRET_NAME", exclusive = true, help_heading = "Vault & Secrets", add = ArgValueCompleter::new(secrets_completer))]
pub update_secret: Option<String>,
/// Delete a secret from the Coyote vault
#[arg(long, value_name = "SECRET_NAME", exclusive = true, help_heading = "Vault & Secrets", add = ArgValueCompleter::new(secrets_completer))]
pub delete_secret: Option<String>,
/// List all secrets stored in the Coyote vault
#[arg(long, exclusive = true, help_heading = "Vault & Secrets")]
pub list_secrets: bool,
/// Authenticate with an LLM provider using OAuth (e.g., --authenticate client_name)
#[arg(
long,
exclusive = true,
value_name = "CLIENT_NAME",
help_heading = "Authentication"
)]
pub authenticate: Option<Option<String>>,
/// Authenticate with an OAuth-protected remote MCP server (e.g., --auth-mcp server_name)
#[arg(long, exclusive = true, value_name = "SERVER_NAME", help_heading = "Authentication", add = ArgValueCompleter::new(mcp_server_completer))]
pub auth_mcp: Option<String>,
/// Launch Coyote inside a Docker sandbox (via `sbx`); name defaults to current directory basename
#[arg(long, value_name = "NAME", help_heading = "Sandbox")]
pub sandbox: Option<Option<String>>,
/// Create the sandbox without bootstrapping the host config or vault password file
#[arg(long, requires = "sandbox", help_heading = "Sandbox")]
pub fresh: bool,
/// Skip discovery and application of all sbx mixins (user and built-in)
#[arg(long, requires = "sandbox", help_heading = "Sandbox")]
pub no_mixins: bool,
/// Display information
#[arg(long, help_heading = "Diagnostics & Tools")]
pub info: bool,
/// Build all configured Bash tool scripts
#[arg(long, help_heading = "Diagnostics & Tools")]
pub build_tools: bool,
/// Tail logs
#[arg(long, help_heading = "Diagnostics & Tools")]
pub tail_logs: bool,
/// Disable colored log output
#[arg(long, requires = "tail_logs", help_heading = "Diagnostics & Tools")]
pub disable_log_colors: bool,
/// Generate static shell completion scripts
#[arg(long, value_name = "SHELL", value_enum, help_heading = "Shell")]
pub completions: Option<ShellCompletion>,
} }
impl Cli { impl Cli {
@@ -393,6 +482,18 @@ mod tests {
assert!(cli.build_tools); assert!(cli.build_tools);
} }
#[test]
fn parse_dangerously_skip_permissions_flag() {
let cli = parse(&["--dangerously-skip-permissions"]);
assert!(cli.dangerously_skip_permissions);
}
#[test]
fn parse_dangerously_skip_permissions_default_off() {
let cli = parse(&[]);
assert!(!cli.dangerously_skip_permissions);
}
#[test] #[test]
fn parse_sync_models_flag() { fn parse_sync_models_flag() {
let cli = parse(&["--sync-models"]); let cli = parse(&["--sync-models"]);
@@ -489,4 +590,59 @@ mod tests {
fn parse_force_without_update_fails() { fn parse_force_without_update_fails() {
assert!(Cli::try_parse_from(["coyote", "--force"]).is_err()); assert!(Cli::try_parse_from(["coyote", "--force"]).is_err());
} }
#[test]
fn parse_sandbox_flag_no_value() {
let cli = parse(&["--sandbox"]);
assert_eq!(cli.sandbox, Some(None));
}
#[test]
fn parse_sandbox_flag_with_name() {
let cli = parse(&["--sandbox", "my-box"]);
assert_eq!(cli.sandbox, Some(Some("my-box".to_string())));
}
#[test]
fn parse_sandbox_is_exclusive() {
assert!(Cli::try_parse_from(["coyote", "--sandbox", "--agent", "foo"]).is_err());
}
#[test]
fn parse_fresh_flag_requires_sandbox() {
assert!(Cli::try_parse_from(["coyote", "--fresh"]).is_err());
}
#[test]
fn parse_fresh_flag_with_sandbox() {
let cli = parse(&["--sandbox", "--fresh"]);
assert_eq!(cli.sandbox, Some(None));
assert!(cli.fresh);
}
#[test]
fn parse_fresh_flag_with_named_sandbox() {
let cli = parse(&["--sandbox", "foo", "--fresh"]);
assert_eq!(cli.sandbox, Some(Some("foo".to_string())));
assert!(cli.fresh);
}
#[test]
fn parse_no_mixins_requires_sandbox() {
assert!(Cli::try_parse_from(["coyote", "--no-mixins"]).is_err());
}
#[test]
fn parse_no_mixins_with_sandbox() {
let cli = parse(&["--sandbox", "--no-mixins"]);
assert!(cli.no_mixins);
}
#[test]
fn parse_sandbox_with_fresh_and_no_mixins() {
let cli = parse(&["--sandbox", "foo", "--fresh", "--no-mixins"]);
assert_eq!(cli.sandbox, Some(Some("foo".to_string())));
assert!(cli.fresh);
assert!(cli.no_mixins);
}
} }
+19 -4
View File
@@ -4,29 +4,44 @@ use indexmap::IndexMap;
use parking_lot::RwLock; use parking_lot::RwLock;
use std::sync::LazyLock; use std::sync::LazyLock;
static ACCESS_TOKENS: LazyLock<RwLock<IndexMap<String, (String, i64)>>> = type AccessTokenEntry = (String, i64, Option<String>);
static ACCESS_TOKENS: LazyLock<RwLock<IndexMap<String, AccessTokenEntry>>> =
LazyLock::new(|| RwLock::new(IndexMap::new())); LazyLock::new(|| RwLock::new(IndexMap::new()));
pub fn get_access_token(client_name: &str) -> Result<String> { pub fn get_access_token(client_name: &str) -> Result<String> {
ACCESS_TOKENS ACCESS_TOKENS
.read() .read()
.get(client_name) .get(client_name)
.map(|(token, _)| token.clone()) .map(|(token, _, _)| token.clone())
.ok_or_else(|| anyhow!("Invalid access token")) .ok_or_else(|| anyhow!("Invalid access token"))
} }
pub fn get_access_token_account_id(client_name: &str) -> Option<String> {
ACCESS_TOKENS
.read()
.get(client_name)
.and_then(|(_, _, account_id)| account_id.clone())
}
pub fn is_valid_access_token(client_name: &str) -> bool { pub fn is_valid_access_token(client_name: &str) -> bool {
let access_tokens = ACCESS_TOKENS.read(); let access_tokens = ACCESS_TOKENS.read();
let (token, expires_at) = match access_tokens.get(client_name) { let (token, expires_at, _) = match access_tokens.get(client_name) {
Some(v) => v, Some(v) => v,
None => return false, None => return false,
}; };
!token.is_empty() && Utc::now().timestamp() < *expires_at !token.is_empty() && Utc::now().timestamp() < *expires_at
} }
pub fn set_access_token(client_name: &str, token: String, expires_at: i64) { pub fn set_access_token(
client_name: &str,
token: String,
expires_at: i64,
account_id: Option<String>,
) {
let mut access_tokens = ACCESS_TOKENS.write(); let mut access_tokens = ACCESS_TOKENS.write();
let entry = access_tokens.entry(client_name.to_string()).or_default(); let entry = access_tokens.entry(client_name.to_string()).or_default();
entry.0 = token; entry.0 = token;
entry.1 = expires_at; entry.1 = expires_at;
entry.2 = account_id;
} }
+2 -2
View File
@@ -50,7 +50,7 @@ fn prepare_chat_completions(
let url = format!( let url = format!(
"{}/openai/deployments/{}/chat/completions?api-version=2024-12-01-preview", "{}/openai/deployments/{}/chat/completions?api-version=2024-12-01-preview",
&api_base, api_base,
self_.model.real_name() self_.model.real_name()
); );
@@ -69,7 +69,7 @@ fn prepare_embeddings(self_: &AzureOpenAIClient, data: &EmbeddingsData) -> Resul
let url = format!( let url = format!(
"{}/openai/deployments/{}/embeddings?api-version=2024-10-21", "{}/openai/deployments/{}/embeddings?api-version=2024-10-21",
&api_base, api_base,
self_.model.real_name() self_.model.real_name()
); );
+10 -1
View File
@@ -325,6 +325,7 @@ fn build_chat_completions_body(data: ChatCompletionsData, model: &Model) -> Resu
mut messages, mut messages,
temperature, temperature,
top_p, top_p,
reasoning_effort,
functions, functions,
stream: _, stream: _,
} = data; } = data;
@@ -396,6 +397,11 @@ fn build_chat_completions_body(data: ChatCompletionsData, model: &Model) -> Resu
})) }))
} }
for tool_result in tool_results { for tool_result in tool_results {
if let Some(round_text) = &tool_result.text {
assistant_parts.push(json!({
"text": round_text,
}))
}
assistant_parts.push(json!({ assistant_parts.push(json!({
"toolUse": { "toolUse": {
"toolUseId": tool_result.call.id, "toolUseId": tool_result.call.id,
@@ -457,6 +463,9 @@ fn build_chat_completions_body(data: ChatCompletionsData, model: &Model) -> Resu
if let Some(v) = top_p { if let Some(v) = top_p {
body["inferenceConfig"]["topP"] = v.into(); body["inferenceConfig"]["topP"] = v.into();
} }
if let Some(v) = reasoning_effort {
body["additionalModelRequestFields"] = json!({ "output_config": { "effort": v } });
}
if let Some(functions) = functions { if let Some(functions) = functions {
let tools: Vec<_> = functions let tools: Vec<_> = functions
.iter() .iter()
@@ -520,7 +529,7 @@ fn extract_chat_completions(data: &Value) -> Result<ChatCompletionsOutput> {
bail!("Invalid response data: {data}"); bail!("Invalid response data: {data}");
} }
let output = ChatCompletionsOutput { text, tool_calls }; let output = ChatCompletionsOutput { text, tool_calls, ..Default::default() };
Ok(output) Ok(output)
} }
+49 -3
View File
@@ -168,12 +168,22 @@ pub async fn claude_chat_completions_streaming(
let mut function_arguments = String::new(); let mut function_arguments = String::new();
let mut function_id = String::new(); let mut function_id = String::new();
let mut reasoning_state = 0; let mut reasoning_state = 0;
let mut thinking_text = String::new();
let mut thinking_signature = String::new();
let handle = |message: SseMessage| -> Result<bool> { let handle = |message: SseMessage| -> Result<bool> {
let data: Value = serde_json::from_str(&message.data)?; let data: Value = serde_json::from_str(&message.data)?;
debug!("stream-data: {data}"); debug!("stream-data: {data}");
if let Some(typ) = data["type"].as_str() { if let Some(typ) = data["type"].as_str() {
match typ { match typ {
"content_block_start" => { "content_block_start" => {
if let (Some("redacted_thinking"), Some(redacted_data)) = (
data["content_block"]["type"].as_str(),
data["content_block"]["data"].as_str(),
) {
handler.thinking_block(ThinkingBlock::RedactedThinking {
data: redacted_data.to_string(),
});
}
if let (Some("tool_use"), Some(name), Some(id)) = ( if let (Some("tool_use"), Some(name), Some(id)) = (
data["content_block"]["type"].as_str(), data["content_block"]["type"].as_str(),
data["content_block"]["name"].as_str(), data["content_block"]["name"].as_str(),
@@ -206,7 +216,10 @@ pub async fn claude_chat_completions_streaming(
handler.text("<think>\n")?; handler.text("<think>\n")?;
reasoning_state = 1; reasoning_state = 1;
} }
thinking_text.push_str(text);
handler.text(text)?; handler.text(text)?;
} else if let Some(signature) = data["delta"]["signature"].as_str() {
thinking_signature.push_str(signature);
} else if let (true, Some(partial_json)) = ( } else if let (true, Some(partial_json)) = (
!function_name.is_empty(), !function_name.is_empty(),
data["delta"]["partial_json"].as_str(), data["delta"]["partial_json"].as_str(),
@@ -218,6 +231,10 @@ pub async fn claude_chat_completions_streaming(
if reasoning_state == 1 { if reasoning_state == 1 {
handler.text("\n</think>\n\n")?; handler.text("\n</think>\n\n")?;
reasoning_state = 0; reasoning_state = 0;
handler.thinking_block(ThinkingBlock::Thinking {
thinking: std::mem::take(&mut thinking_text),
signature: std::mem::take(&mut thinking_signature),
});
} }
if !function_name.is_empty() { if !function_name.is_empty() {
let arguments: Value = if function_arguments.is_empty() { let arguments: Value = if function_arguments.is_empty() {
@@ -251,6 +268,7 @@ pub fn claude_build_chat_completions_body(
mut messages, mut messages,
temperature, temperature,
top_p, top_p,
reasoning_effort,
functions, functions,
stream, stream,
} = data; } = data;
@@ -312,13 +330,25 @@ pub fn claude_build_chat_completions_body(
}) => { }) => {
let mut assistant_parts = vec![]; let mut assistant_parts = vec![];
let mut user_parts = vec![]; let mut user_parts = vec![];
if !text.is_empty() { for (index, tool_result) in tool_results.iter().enumerate() {
for block in &tool_result.thinking {
assistant_parts.push(json!(block));
}
let round_text = if index == 0 && !text.is_empty() {
Some(text.as_str())
} else {
tool_result.text.as_deref()
};
if let Some(round_text) = round_text {
let round_text = strip_think_tag(round_text);
let round_text = round_text.trim();
if !round_text.is_empty() {
assistant_parts.push(json!({ assistant_parts.push(json!({
"type": "text", "type": "text",
"text": text, "text": round_text,
})) }))
} }
for tool_result in tool_results { }
assistant_parts.push(json!({ assistant_parts.push(json!({
"type": "tool_use", "type": "tool_use",
"id": tool_result.call.id, "id": tool_result.call.id,
@@ -369,6 +399,9 @@ pub fn claude_build_chat_completions_body(
if let Some(v) = top_p { if let Some(v) = top_p {
body["top_p"] = v.into(); body["top_p"] = v.into();
} }
if let Some(v) = reasoning_effort {
body["output_config"] = json!({ "effort": v });
}
if stream { if stream {
body["stream"] = true.into(); body["stream"] = true.into();
} }
@@ -399,12 +432,24 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
let mut text = String::new(); let mut text = String::new();
let mut reasoning = None; let mut reasoning = None;
let mut tool_calls = vec![]; let mut tool_calls = vec![];
let mut thinking = vec![];
if let Some(list) = data["content"].as_array() { if let Some(list) = data["content"].as_array() {
for item in list { for item in list {
match item["type"].as_str() { match item["type"].as_str() {
Some("thinking") => { Some("thinking") => {
if let Some(v) = item["thinking"].as_str() { if let Some(v) = item["thinking"].as_str() {
reasoning = Some(v.to_string()); reasoning = Some(v.to_string());
thinking.push(ThinkingBlock::Thinking {
thinking: v.to_string(),
signature: item["signature"].as_str().unwrap_or_default().to_string(),
});
}
}
Some("redacted_thinking") => {
if let Some(v) = item["data"].as_str() {
thinking.push(ThinkingBlock::RedactedThinking {
data: v.to_string(),
});
} }
} }
Some("text") => { Some("text") => {
@@ -443,6 +488,7 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
let output = ChatCompletionsOutput { let output = ChatCompletionsOutput {
text: text.to_string(), text: text.to_string(),
tool_calls, tool_calls,
thinking,
}; };
Ok(output) Ok(output)
} }
+2 -2
View File
@@ -25,8 +25,8 @@ impl OAuthProvider for ClaudeOAuthProvider {
"https://console.anthropic.com/oauth/code/callback" "https://console.anthropic.com/oauth/code/callback"
} }
fn scopes(&self) -> &str { fn scopes(&self) -> String {
"org:create_api_key user:profile user:inference" "org:create_api_key user:profile user:inference".to_string()
} }
fn extra_authorize_params(&self) -> Vec<(&str, &str)> { fn extra_authorize_params(&self) -> Vec<(&str, &str)> {
+1 -1
View File
@@ -244,6 +244,6 @@ fn extract_chat_completions(data: &Value) -> Result<ChatCompletionsOutput> {
if text.is_empty() && tool_calls.is_empty() { if text.is_empty() && tool_calls.is_empty() {
bail!("Invalid response data: {data}"); bail!("Invalid response data: {data}");
} }
let output = ChatCompletionsOutput { text, tool_calls }; let output = ChatCompletionsOutput { text, tool_calls, ..Default::default() };
Ok(output) Ok(output)
} }
+27 -3
View File
@@ -286,6 +286,7 @@ pub struct ChatCompletionsData {
pub messages: Vec<Message>, pub messages: Vec<Message>,
pub temperature: Option<f64>, pub temperature: Option<f64>,
pub top_p: Option<f64>, pub top_p: Option<f64>,
pub reasoning_effort: Option<String>,
pub functions: Option<Vec<FunctionDeclaration>>, pub functions: Option<Vec<FunctionDeclaration>>,
pub stream: bool, pub stream: bool,
} }
@@ -294,6 +295,7 @@ pub struct ChatCompletionsData {
pub struct ChatCompletionsOutput { pub struct ChatCompletionsOutput {
pub text: String, pub text: String,
pub tool_calls: Vec<ToolCall>, pub tool_calls: Vec<ToolCall>,
pub thinking: Vec<ThinkingBlock>,
} }
impl ChatCompletionsOutput { impl ChatCompletionsOutput {
@@ -401,10 +403,25 @@ pub async fn create_openai_compatible_client_config(
}; };
config["api_base"] = api_base.into(); config["api_base"] = api_base.into();
let has_bundled_oauth = ALL_PROVIDER_MODELS
.iter()
.any(|p| p.provider == client && p.oauth.is_some());
let use_oauth = if has_bundled_oauth {
let choice = Select::new("Authentication method:", vec!["API Key", "OAuth"]).prompt()?;
choice == "OAuth"
} else {
false
};
if use_oauth {
config["auth"] = "oauth".into();
} else {
let api_key = prompt_input_string("API Key", false, None)?; let api_key = prompt_input_string("API Key", false, None)?;
if !api_key.is_empty() { if !api_key.is_empty() {
config["api_key"] = api_key.into(); config["api_key"] = api_key.into();
} }
}
let model = set_client_models_config(&mut config, &name).await?; let model = set_client_models_config(&mut config, &name).await?;
let clients = json!(vec![config]); let clients = json!(vec![config]);
@@ -434,6 +451,7 @@ pub async fn call_chat_completions(
let ChatCompletionsOutput { let ChatCompletionsOutput {
mut text, mut text,
tool_calls, tool_calls,
thinking,
.. ..
} = ret; } = ret;
if !text.is_empty() { if !text.is_empty() {
@@ -444,7 +462,10 @@ pub async fn call_chat_completions(
ctx.app.config.print_markdown(&text)?; ctx.app.config.print_markdown(&text)?;
} }
} }
let tool_results = eval_tool_calls(ctx, tool_calls).await?; let mut tool_results = eval_tool_calls(ctx, tool_calls).await?;
if let Some(first) = tool_results.first_mut() {
first.thinking = thinking;
}
tool_results tool_results
.iter() .iter()
.for_each(|res| ctx.tool_scope.tool_tracker.record_call(res.call.clone())); .for_each(|res| ctx.tool_scope.tool_tracker.record_call(res.call.clone()));
@@ -478,13 +499,16 @@ pub async fn call_chat_completions_streaming(
render_ret?; render_ret?;
let (text, tool_calls) = handler.take(); let (text, tool_calls, thinking) = handler.take();
match send_ret { match send_ret {
Ok(_) => { Ok(_) => {
if !text.is_empty() && !text.ends_with('\n') { if !text.is_empty() && !text.ends_with('\n') {
println!(); println!();
} }
let tool_results = eval_tool_calls(ctx, tool_calls).await?; let mut tool_results = eval_tool_calls(ctx, tool_calls).await?;
if let Some(first) = tool_results.first_mut() {
first.thinking = thinking;
}
tool_results tool_results
.iter() .iter()
.for_each(|res| ctx.tool_scope.tool_tracker.record_call(res.call.clone())); .for_each(|res| ctx.tool_scope.tool_tracker.record_call(res.call.clone()));
+2 -2
View File
@@ -27,8 +27,8 @@ impl OAuthProvider for GeminiOAuthProvider {
"" ""
} }
fn scopes(&self) -> &str { fn scopes(&self) -> String {
"https://www.googleapis.com/auth/generative-language.peruserquota https://www.googleapis.com/auth/generative-language.retriever https://www.googleapis.com/auth/userinfo.email" "https://www.googleapis.com/auth/generative-language.peruserquota https://www.googleapis.com/auth/generative-language.retriever https://www.googleapis.com/auth/userinfo.email".to_string()
} }
fn client_secret(&self) -> Option<&str> { fn client_secret(&self) -> Option<&str> {
+27 -2
View File
@@ -118,6 +118,9 @@ impl MessageContent {
lines.push(text.clone()) lines.push(text.clone())
} }
for tool_result in tool_results { for tool_result in tool_results {
if let Some(round_text) = &tool_result.text {
lines.push(round_text.clone())
}
let mut parts = vec!["Call".to_string()]; let mut parts = vec!["Call".to_string()];
if let Some((agent_name, functions)) = agent_info if let Some((agent_name, functions)) = agent_info
&& functions.contains(&tool_result.call.name) && functions.contains(&tool_result.call.name)
@@ -133,6 +136,13 @@ impl MessageContent {
} }
} }
pub fn as_text(&self) -> Option<&str> {
match self {
MessageContent::Text(text) => Some(text),
_ => None,
}
}
pub fn merge_prompt(&mut self, replace_fn: impl Fn(&str) -> String) { pub fn merge_prompt(&mut self, replace_fn: impl Fn(&str) -> String) {
match self { match self {
MessageContent::Text(text) => *text = replace_fn(text), MessageContent::Text(text) => *text = replace_fn(text),
@@ -178,6 +188,17 @@ pub struct ImageUrl {
pub url: String, pub url: String,
} }
/// An extended-thinking block returned by Anthropic-protocol models.
/// Serialized to match the API wire format (`type: thinking` / `type: redacted_thinking`)
/// so blocks can be replayed verbatim, signature intact, in subsequent
/// tool-loop rounds as the API requires.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ThinkingBlock {
Thinking { thinking: String, signature: String },
RedactedThinking { data: String },
}
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MessageContentToolCalls { pub struct MessageContentToolCalls {
pub tool_results: Vec<ToolResult>, pub tool_results: Vec<ToolResult>,
@@ -194,9 +215,13 @@ impl MessageContentToolCalls {
} }
} }
pub fn merge(&mut self, tool_results: Vec<ToolResult>, _text: String) { pub fn merge(&mut self, mut tool_results: Vec<ToolResult>, text: String) {
if !text.is_empty()
&& let Some(first) = tool_results.first_mut()
{
first.text = Some(text);
}
self.tool_results.extend(tool_results); self.tool_results.extend(tool_results);
self.text.clear();
self.sequence = true; self.sequence = true;
} }
} }
+2
View File
@@ -4,6 +4,8 @@ mod common;
mod gemini_oauth; mod gemini_oauth;
mod message; mod message;
pub mod oauth; pub mod oauth;
mod openai_compatible_oauth;
mod openai_oauth;
#[macro_use] #[macro_use]
mod macros; mod macros;
mod model; mod model;
+15
View File
@@ -6,6 +6,7 @@ use super::{
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::utils::{estimate_token_length, strip_think_tag}; use crate::utils::{estimate_token_length, strip_think_tag};
use super::oauth::OAuthConfig;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
@@ -289,6 +290,14 @@ impl Model {
} }
Ok(()) Ok(())
} }
pub fn reasoning_levels(&self) -> &[String] {
&self.data.reasoning_levels
}
pub fn default_reasoning_effort(&self) -> Option<&str> {
self.data.default_reasoning_effort.as_deref()
}
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -316,6 +325,10 @@ pub struct ModelData {
pub supports_vision: bool, pub supports_vision: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")] #[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub supports_function_calling: bool, pub supports_function_calling: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reasoning_levels: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_reasoning_effort: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")] #[serde(default, skip_serializing_if = "std::ops::Not::not")]
no_stream: bool, no_stream: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")] #[serde(default, skip_serializing_if = "std::ops::Not::not")]
@@ -345,6 +358,8 @@ impl ModelData {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderModels { pub struct ProviderModels {
pub provider: String, pub provider: String,
#[serde(default)]
pub oauth: Option<OAuthConfig>,
pub models: Vec<ModelData>, pub models: Vec<ModelData>,
} }
+1016 -61
View File
File diff suppressed because it is too large Load Diff
+371 -28
View File
@@ -1,13 +1,17 @@
use super::access_token::{get_access_token, get_access_token_account_id};
use super::oauth::{self, OAuthProvider};
use super::openai_oauth::OpenAIOAuthProvider;
use super::*; use super::*;
use crate::utils::strip_think_tag; use crate::utils::strip_think_tag;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use reqwest::RequestBuilder; use reqwest::{Client as ReqwestClient, RequestBuilder};
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
const API_BASE: &str = "https://api.openai.com/v1"; const API_BASE: &str = "https://api.openai.com/v1";
const CODEX_API_ENDPOINT: &str = "https://chatgpt.com/backend-api/codex/responses";
#[derive(Debug, Clone, Deserialize, Default)] #[derive(Debug, Clone, Deserialize, Default)]
pub struct OpenAIConfig { pub struct OpenAIConfig {
@@ -15,6 +19,7 @@ pub struct OpenAIConfig {
pub api_key: Option<String>, pub api_key: Option<String>,
pub api_base: Option<String>, pub api_base: Option<String>,
pub organization_id: Option<String>, pub organization_id: Option<String>,
pub auth: Option<String>,
#[serde(default)] #[serde(default)]
pub models: Vec<ModelData>, pub models: Vec<ModelData>,
pub patch: Option<RequestPatch>, pub patch: Option<RequestPatch>,
@@ -25,36 +30,131 @@ impl OpenAIClient {
config_get_fn!(api_key, get_api_key); config_get_fn!(api_key, get_api_key);
config_get_fn!(api_base, get_api_base); config_get_fn!(api_base, get_api_base);
create_client_config!([("api_key", "API Key", None, true)]); create_oauth_supported_client_config!();
} }
impl_client_trait!( #[async_trait::async_trait]
OpenAIClient, impl Client for OpenAIClient {
( client_common_fns!();
prepare_chat_completions,
openai_chat_completions,
openai_chat_completions_streaming
),
(prepare_embeddings, openai_embeddings),
(noop_prepare_rerank, noop_rerank),
);
fn prepare_chat_completions( fn supports_oauth(&self) -> bool {
self.config.auth.as_deref() == Some("oauth")
}
async fn chat_completions_inner(
&self,
client: &ReqwestClient,
data: ChatCompletionsData,
) -> Result<ChatCompletionsOutput> {
let uses_codex =
self.config.auth.as_deref() == Some("oauth") && self.get_api_base().is_err();
let request_data = prepare_chat_completions(self, client, data).await?;
let builder = self.request_builder(client, request_data);
if uses_codex {
openai_responses_chat_completions(builder, self.model()).await
} else {
openai_chat_completions(builder, self.model()).await
}
}
async fn chat_completions_streaming_inner(
&self,
client: &ReqwestClient,
handler: &mut SseHandler,
data: ChatCompletionsData,
) -> Result<()> {
let uses_codex =
self.config.auth.as_deref() == Some("oauth") && self.get_api_base().is_err();
let request_data = prepare_chat_completions(self, client, data).await?;
let builder = self.request_builder(client, request_data);
if uses_codex {
openai_responses_streaming(builder, handler).await
} else {
openai_chat_completions_streaming(builder, handler, self.model()).await
}
}
async fn embeddings_inner(
&self,
client: &ReqwestClient,
data: &EmbeddingsData,
) -> Result<EmbeddingsOutput> {
let request_data = prepare_embeddings(self, client, data).await?;
let builder = self.request_builder(client, request_data);
openai_embeddings(builder, self.model()).await
}
async fn rerank_inner(
&self,
client: &ReqwestClient,
data: &RerankData,
) -> Result<RerankOutput> {
let request_data = noop_prepare_rerank(self, data)?;
let builder = self.request_builder(client, request_data);
noop_rerank(builder, self.model()).await
}
}
async fn prepare_chat_completions(
self_: &OpenAIClient, self_: &OpenAIClient,
client: &ReqwestClient,
data: ChatCompletionsData, data: ChatCompletionsData,
) -> Result<RequestData> { ) -> Result<RequestData> {
let api_key = self_.get_api_key()?; let uses_oauth = self_.config.auth.as_deref() == Some("oauth");
let has_custom_base = self_.get_api_base().is_ok();
let uses_codex = uses_oauth && !has_custom_base;
let url = if uses_codex {
CODEX_API_ENDPOINT.to_string()
} else {
let api_base = self_ let api_base = self_
.get_api_base() .get_api_base()
.unwrap_or_else(|_| API_BASE.to_string()); .unwrap_or_else(|_| API_BASE.to_string());
format!("{}/chat/completions", api_base.trim_end_matches('/'))
};
let url = format!("{}/chat/completions", api_base.trim_end_matches('/')); let body = if uses_codex {
openai_build_responses_body(data, &self_.model)
let body = openai_build_chat_completions_body(data, &self_.model); } else {
openai_build_chat_completions_body(data, &self_.model)
};
let mut request_data = RequestData::new(url, body); let mut request_data = RequestData::new(url, body);
if uses_oauth {
let provider = OpenAIOAuthProvider;
let ready = oauth::prepare_oauth_access_token(client, &provider, self_.name()).await?;
if !ready {
bail!(
"OAuth configured but no tokens found for '{}'. Run: 'coyote --authenticate {}' or '.authenticate' in the REPL",
self_.name(),
self_.name()
);
}
let token = get_access_token(self_.name())?;
request_data.bearer_auth(token);
if let Some(account_id) = get_access_token_account_id(self_.name()) {
request_data.header("ChatGPT-Account-Id", account_id);
}
for (key, value) in provider.extra_request_headers() {
request_data.header(key, value);
}
} else if let Ok(api_key) = self_.get_api_key() {
request_data.bearer_auth(api_key); request_data.bearer_auth(api_key);
} else {
bail!(
"No authentication configured for '{}'. Set `api_key` or use `auth: oauth` with `coyote --authenticate {}`.",
self_.name(),
self_.name()
);
}
if let Some(organization_id) = &self_.config.organization_id { if let Some(organization_id) = &self_.config.organization_id {
request_data.header("OpenAI-Organization", organization_id); request_data.header("OpenAI-Organization", organization_id);
} }
@@ -62,8 +162,11 @@ fn prepare_chat_completions(
Ok(request_data) Ok(request_data)
} }
fn prepare_embeddings(self_: &OpenAIClient, data: &EmbeddingsData) -> Result<RequestData> { async fn prepare_embeddings(
let api_key = self_.get_api_key()?; self_: &OpenAIClient,
client: &ReqwestClient,
data: &EmbeddingsData,
) -> Result<RequestData> {
let api_base = self_ let api_base = self_
.get_api_base() .get_api_base()
.unwrap_or_else(|_| API_BASE.to_string()); .unwrap_or_else(|_| API_BASE.to_string());
@@ -74,7 +177,30 @@ fn prepare_embeddings(self_: &OpenAIClient, data: &EmbeddingsData) -> Result<Req
let mut request_data = RequestData::new(url, body); let mut request_data = RequestData::new(url, body);
if self_.config.auth.as_deref() == Some("oauth") {
let provider = OpenAIOAuthProvider;
let ready = oauth::prepare_oauth_access_token(client, &provider, self_.name()).await?;
if !ready {
bail!(
"OAuth configured but no tokens found for '{}'. Run: 'coyote --authenticate {}' or '.authenticate' in the REPL",
self_.name(),
self_.name()
);
}
let token = get_access_token(self_.name())?;
request_data.bearer_auth(token);
} else if let Ok(api_key) = self_.get_api_key() {
request_data.bearer_auth(api_key); request_data.bearer_auth(api_key);
} else {
bail!(
"No authentication configured for '{}'. Set `api_key` or use `auth: oauth` with `coyote --authenticate {}`.",
self_.name(),
self_.name()
);
}
if let Some(organization_id) = &self_.config.organization_id { if let Some(organization_id) = &self_.config.organization_id {
request_data.header("OpenAI-Organization", organization_id); request_data.header("OpenAI-Organization", organization_id);
} }
@@ -230,6 +356,7 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod
messages, messages,
temperature, temperature,
top_p, top_p,
reasoning_effort,
functions, functions,
stream, stream,
} = data; } = data;
@@ -243,7 +370,7 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod
match content { match content {
MessageContent::ToolCalls(MessageContentToolCalls { MessageContent::ToolCalls(MessageContentToolCalls {
tool_results, tool_results,
text: _, text,
sequence, sequence,
}) => { }) => {
if !sequence { if !sequence {
@@ -260,9 +387,12 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod
}) })
}) })
.collect(); .collect();
let mut messages = vec![ let mut assistant_message =
json!({ "role": MessageRole::Assistant, "tool_calls": tool_calls }), json!({ "role": MessageRole::Assistant, "tool_calls": tool_calls });
]; if !text.is_empty() {
assistant_message["content"] = strip_think_tag(&text).into();
}
let mut messages = vec![assistant_message];
for tool_result in tool_results { for tool_result in tool_results {
messages.push(json!({ messages.push(json!({
"role": "tool", "role": "tool",
@@ -272,9 +402,13 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod
} }
messages messages
} else { } else {
tool_results.into_iter().flat_map(|tool_result| { tool_results.into_iter().enumerate().flat_map(|(index, tool_result)| {
vec![ let round_text = if index == 0 && !text.is_empty() {
json!({ Some(text.clone())
} else {
tool_result.text.clone()
};
let mut assistant_message = json!({
"role": MessageRole::Assistant, "role": MessageRole::Assistant,
"tool_calls": [ "tool_calls": [
{ {
@@ -286,7 +420,12 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod
}, },
} }
] ]
}), });
if let Some(round_text) = round_text {
assistant_message["content"] = strip_think_tag(&round_text).into();
}
vec![
assistant_message,
json!({ json!({
"role": "tool", "role": "tool",
"content": tool_result.output.to_string(), "content": tool_result.output.to_string(),
@@ -328,6 +467,9 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod
if let Some(v) = top_p { if let Some(v) = top_p {
body["top_p"] = v.into(); body["top_p"] = v.into();
} }
if let Some(v) = reasoning_effort {
body["reasoning_effort"] = v.into();
}
if stream { if stream {
body["stream"] = true.into(); body["stream"] = true.into();
} }
@@ -391,7 +533,7 @@ pub fn openai_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
} else { } else {
text.to_string() text.to_string()
}; };
let output = ChatCompletionsOutput { text, tool_calls }; let output = ChatCompletionsOutput { text, tool_calls, ..Default::default() };
Ok(output) Ok(output)
} }
@@ -402,3 +544,204 @@ fn normalize_function_id(value: &str) -> Option<String> {
Some(value.to_string()) Some(value.to_string())
} }
} }
pub fn openai_build_responses_body(data: ChatCompletionsData, model: &Model) -> Value {
let ChatCompletionsData {
messages,
temperature,
top_p,
reasoning_effort,
functions,
stream,
} = data;
let messages_len = messages.len();
let input: Vec<Value> = messages
.into_iter()
.enumerate()
.flat_map(|(i, message)| {
let Message { role, content } = message;
match content {
MessageContent::ToolCalls(MessageContentToolCalls {
tool_results,
text,
sequence: _,
}) => tool_results
.into_iter()
.enumerate()
.flat_map(|(index, tool_result)| {
let round_text = if index == 0 && !text.is_empty() {
Some(text.clone())
} else {
tool_result.text.clone()
};
let mut items = vec![];
if let Some(round_text) = round_text {
items.push(json!({
"role": MessageRole::Assistant,
"content": strip_think_tag(&round_text),
}));
}
items.push(json!({
"type": "function_call",
"call_id": tool_result.call.id,
"name": tool_result.call.name,
"arguments": tool_result.call.arguments.to_string(),
}));
items.push(json!({
"type": "function_call_output",
"call_id": tool_result.call.id,
"output": tool_result.output.to_string(),
}));
items
})
.collect(),
MessageContent::Text(text) if role.is_assistant() && i != messages_len - 1 => {
vec![json!({ "role": role, "content": strip_think_tag(&text) })]
}
_ => vec![json!({ "role": role, "content": content })],
}
})
.collect();
let mut body = json!({
"model": &model.real_name(),
"input": input,
"store": false,
});
if let Some(v) = model.max_tokens_param() {
body["max_output_tokens"] = v.into();
}
if let Some(v) = temperature {
body["temperature"] = v.into();
}
if let Some(v) = top_p {
body["top_p"] = v.into();
}
if let Some(v) = reasoning_effort {
body["reasoning"] = json!({ "effort": v });
}
if stream {
body["stream"] = true.into();
}
if let Some(functions) = functions {
body["tools"] = functions
.iter()
.map(|v| {
let mut tool = serde_json::to_value(v).unwrap_or_default();
tool["type"] = "function".into();
tool
})
.collect();
}
body
}
pub async fn openai_responses_chat_completions(
builder: RequestBuilder,
_model: &Model,
) -> Result<ChatCompletionsOutput> {
let res = builder.send().await?;
let status = res.status();
let data: Value = res.json().await?;
if !status.is_success() {
catch_error(&data, status.as_u16())?;
}
debug!("non-stream-data: {data}");
openai_extract_responses(&data)
}
pub fn openai_extract_responses(data: &Value) -> Result<ChatCompletionsOutput> {
let mut text = String::new();
let mut tool_calls = vec![];
if let Some(output) = data["output"].as_array() {
for item in output {
match item["type"].as_str() {
Some("message") => {
if let Some(content) = item["content"].as_array() {
for part in content {
if part["type"].as_str() == Some("output_text")
&& let Some(t) = part["text"].as_str()
{
text.push_str(t);
}
}
}
}
Some("function_call") => {
if let (Some(name), Some(arguments_str), Some(call_id)) = (
item["name"].as_str(),
item["arguments"].as_str(),
item["call_id"].as_str(),
) {
let arguments: Value = arguments_str.parse().with_context(|| {
format!("Tool call '{name}' has non-JSON arguments '{arguments_str}'")
})?;
tool_calls.push(ToolCall::new(
name.to_string(),
arguments,
Some(call_id.to_string()),
));
}
}
_ => {}
}
}
}
if text.is_empty() && tool_calls.is_empty() {
bail!("Invalid response data: {data}");
}
Ok(ChatCompletionsOutput { text, tool_calls, ..Default::default() })
}
pub async fn openai_responses_streaming(
builder: RequestBuilder,
handler: &mut SseHandler,
) -> Result<()> {
let handle = |message: SseMessage| -> Result<bool> {
if message.data == "[DONE]" {
return Ok(true);
}
let data: Value = serde_json::from_str(&message.data)?;
debug!("stream-data: {data}");
match data["type"].as_str() {
Some("response.output_text.delta") => {
if let Some(delta) = data["delta"].as_str().filter(|v| !v.is_empty()) {
handler.text(delta)?;
}
}
Some("response.output_item.done") => {
let item = &data["item"];
if item["type"].as_str() == Some("function_call")
&& let (Some(name), Some(arguments_str), Some(call_id)) = (
item["name"].as_str(),
item["arguments"].as_str(),
item["call_id"].as_str(),
)
{
let arguments: Value = arguments_str.parse().with_context(|| {
format!("Tool call '{name}' has non-JSON arguments '{arguments_str}'")
})?;
handler.tool_call(ToolCall::new(
name.to_string(),
arguments,
Some(call_id.to_string()),
))?;
}
}
Some("response.completed") => {
return Ok(true);
}
_ => {}
}
Ok(false)
};
sse_stream(builder, handle).await
}
+122 -36
View File
@@ -1,16 +1,21 @@
use super::access_token::get_access_token;
use super::oauth;
use super::openai::*; use super::openai::*;
use super::*; use super::*;
use anyhow::{Context, Result}; use anyhow::{Context, Result, anyhow, bail};
use reqwest::RequestBuilder; use reqwest::{Client as ReqwestClient, RequestBuilder};
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
use oauth::OAuthConfig;
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct OpenAICompatibleConfig { pub struct OpenAICompatibleConfig {
pub name: Option<String>, pub name: Option<String>,
pub api_base: Option<String>, pub api_base: Option<String>,
pub api_key: Option<String>, pub api_key: Option<String>,
pub auth: Option<String>,
pub oauth: Option<Box<OAuthConfig>>,
#[serde(default)] #[serde(default)]
pub models: Vec<ModelData>, pub models: Vec<ModelData>,
pub patch: Option<RequestPatch>, pub patch: Option<RequestPatch>,
@@ -24,78 +29,159 @@ impl OpenAICompatibleClient {
create_client_config!([]); create_client_config!([]);
} }
impl_client_trait!( #[async_trait::async_trait]
OpenAICompatibleClient, impl Client for OpenAICompatibleClient {
( client_common_fns!();
prepare_chat_completions,
openai_chat_completions,
openai_chat_completions_streaming
),
(prepare_embeddings, openai_embeddings),
(prepare_rerank, generic_rerank),
);
fn prepare_chat_completions( fn supports_oauth(&self) -> bool {
self.config.auth.as_deref() == Some("oauth")
}
async fn chat_completions_inner(
&self,
client: &ReqwestClient,
data: ChatCompletionsData,
) -> Result<ChatCompletionsOutput> {
let request_data = prepare_chat_completions(self, client, data).await?;
let builder = self.request_builder(client, request_data);
openai_chat_completions(builder, self.model()).await
}
async fn chat_completions_streaming_inner(
&self,
client: &ReqwestClient,
handler: &mut SseHandler,
data: ChatCompletionsData,
) -> Result<()> {
let request_data = prepare_chat_completions(self, client, data).await?;
let builder = self.request_builder(client, request_data);
openai_chat_completions_streaming(builder, handler, self.model()).await
}
async fn embeddings_inner(
&self,
client: &ReqwestClient,
data: &EmbeddingsData,
) -> Result<EmbeddingsOutput> {
let request_data = prepare_embeddings(self, client, data).await?;
let builder = self.request_builder(client, request_data);
openai_embeddings(builder, self.model()).await
}
async fn rerank_inner(
&self,
client: &ReqwestClient,
data: &RerankData,
) -> Result<RerankOutput> {
let request_data = prepare_rerank(self, client, data).await?;
let builder = self.request_builder(client, request_data);
generic_rerank(builder, self.model()).await
}
}
async fn prepare_chat_completions(
self_: &OpenAICompatibleClient, self_: &OpenAICompatibleClient,
client: &ReqwestClient,
data: ChatCompletionsData, data: ChatCompletionsData,
) -> Result<RequestData> { ) -> Result<RequestData> {
let api_key = self_.get_api_key().ok();
let api_base = get_api_base_ext(self_)?; let api_base = get_api_base_ext(self_)?;
let url = format!("{api_base}/chat/completions"); let url = format!("{api_base}/chat/completions");
let body = openai_build_chat_completions_body(data, &self_.model); let body = openai_build_chat_completions_body(data, &self_.model);
let mut request_data = RequestData::new(url, body); let mut request_data = RequestData::new(url, body);
if let Some(api_key) = api_key { apply_auth(self_, client, &mut request_data).await?;
request_data.bearer_auth(api_key);
}
Ok(request_data) Ok(request_data)
} }
fn prepare_embeddings( async fn prepare_embeddings(
self_: &OpenAICompatibleClient, self_: &OpenAICompatibleClient,
client: &ReqwestClient,
data: &EmbeddingsData, data: &EmbeddingsData,
) -> Result<RequestData> { ) -> Result<RequestData> {
let api_key = self_.get_api_key().ok();
let api_base = get_api_base_ext(self_)?; let api_base = get_api_base_ext(self_)?;
let url = format!("{api_base}/embeddings"); let url = format!("{api_base}/embeddings");
let body = openai_build_embeddings_body(data, &self_.model); let body = openai_build_embeddings_body(data, &self_.model);
let mut request_data = RequestData::new(url, body); let mut request_data = RequestData::new(url, body);
if let Some(api_key) = api_key { apply_auth(self_, client, &mut request_data).await?;
request_data.bearer_auth(api_key);
}
Ok(request_data) Ok(request_data)
} }
fn prepare_rerank(self_: &OpenAICompatibleClient, data: &RerankData) -> Result<RequestData> { async fn prepare_rerank(
let api_key = self_.get_api_key().ok(); self_: &OpenAICompatibleClient,
client: &ReqwestClient,
data: &RerankData,
) -> Result<RequestData> {
let api_base = get_api_base_ext(self_)?; let api_base = get_api_base_ext(self_)?;
let url = if self_.name().starts_with("ernie") { let url = if self_.name().starts_with("ernie") {
format!("{api_base}/rerankers") format!("{api_base}/rerankers")
} else { } else {
format!("{api_base}/rerank") format!("{api_base}/rerank")
}; };
let body = generic_build_rerank_body(data, &self_.model); let body = generic_build_rerank_body(data, &self_.model);
let mut request_data = RequestData::new(url, body); let mut request_data = RequestData::new(url, body);
if let Some(api_key) = api_key { apply_auth(self_, client, &mut request_data).await?;
request_data.bearer_auth(api_key);
}
Ok(request_data) Ok(request_data)
} }
async fn apply_auth(
self_: &OpenAICompatibleClient,
client: &ReqwestClient,
request_data: &mut RequestData,
) -> Result<()> {
if self_.config.auth.as_deref() == Some("oauth") {
let client_name = self_.name();
let app_config = self_.app_config();
let cc = app_config
.clients
.iter()
.find(|cc| {
matches!(
cc,
ClientConfig::OpenAICompatibleConfig(c)
if c.name.as_deref().unwrap_or("openai-compatible") == client_name
)
})
.ok_or_else(|| {
anyhow!("Could not locate ClientConfig entry for '{}'", client_name)
})?;
let provider = oauth::get_oauth_provider_for_client(cc, &ALL_PROVIDER_MODELS)
.ok_or_else(|| {
anyhow!(
"OAuth configured for '{}' but no oauth block resolved (missing from both models.yaml and user config)",
client_name
)
})?;
let ready = oauth::prepare_oauth_access_token(client, &*provider, client_name).await?;
if !ready {
bail!(
"OAuth configured for '{}' but no tokens found. Run: 'coyote --authenticate {}' or '.authenticate' in the REPL",
client_name,
client_name
);
}
let token = get_access_token(client_name)?;
request_data.bearer_auth(token);
for (key, value) in provider.extra_request_headers() {
request_data.header(key, value);
}
} else if let Ok(api_key) = self_.get_api_key() {
request_data.bearer_auth(api_key);
}
Ok(())
}
fn get_api_base_ext(self_: &OpenAICompatibleClient) -> Result<String> { fn get_api_base_ext(self_: &OpenAICompatibleClient) -> Result<String> {
let api_base = match self_.get_api_base() { let api_base = match self_.get_api_base() {
Ok(v) => v, Ok(v) => v,
+113
View File
@@ -0,0 +1,113 @@
use url::Url;
use super::oauth::{OAuthConfig, OAuthFlow, OAuthProvider, TokenRequestFormat};
pub struct OpenAICompatibleOAuthProvider {
pub config: OAuthConfig,
pub client_name: String,
}
fn is_loopback_uri(uri: &str) -> bool {
Url::parse(uri)
.ok()
.and_then(|u| u.host_str().map(str::to_string))
.is_some_and(|host| matches!(host.as_str(), "127.0.0.1" | "localhost" | "[::1]" | "::1"))
}
impl OAuthProvider for OpenAICompatibleOAuthProvider {
fn provider_name(&self) -> &str {
&self.client_name
}
fn client_id(&self) -> &str {
&self.config.client_id
}
fn authorize_url(&self) -> &str {
self.config.authorize_url.as_deref().unwrap_or("")
}
fn token_url(&self) -> &str {
&self.config.token_url
}
fn redirect_uri(&self) -> &str {
self.config.redirect_uri.as_deref().unwrap_or("")
}
fn scopes(&self) -> String {
self.config.scopes.join(" ")
}
fn client_secret(&self) -> Option<&str> {
self.config.client_secret.as_deref()
}
fn extra_authorize_params(&self) -> Vec<(&str, &str)> {
self.config
.extra_authorize_params
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect()
}
fn token_request_format(&self) -> TokenRequestFormat {
self.config
.token_request_format
.unwrap_or(TokenRequestFormat::FormUrlEncoded)
}
fn uses_localhost_redirect(&self) -> bool {
self.config.redirect_uri.is_none() && self.config.redirect_port.is_none()
}
fn extra_token_headers(&self) -> Vec<(&str, &str)> {
self.config
.extra_token_headers
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect()
}
fn extra_request_headers(&self) -> Vec<(&str, &str)> {
self.config
.extra_request_headers
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect()
}
fn fixed_redirect_uri(&self) -> Option<String> {
if let Some(uri) = &self.config.redirect_uri {
return if is_loopback_uri(uri) {
Some(uri.clone())
} else {
None
};
}
if let Some(port) = self.config.redirect_port {
return Some(format!("http://127.0.0.1:{port}/callback"));
}
None
}
fn include_state_in_token_exchange(&self) -> bool {
self.config.include_state_in_token_exchange
}
fn flow(&self) -> OAuthFlow {
self.config.flow
}
fn echo_pkce_in_token_exchange(&self) -> bool {
self.config.echo_pkce_in_token_exchange
}
fn device_authorization_url(&self) -> Option<&str> {
self.config.device_authorization_url.as_deref()
}
fn use_pkce_in_device_flow(&self) -> bool {
self.config.use_pkce_in_device_flow
}
}
+79
View File
@@ -0,0 +1,79 @@
use super::oauth::{OAuthProvider, TokenRequestFormat};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde_json::Value;
pub struct OpenAIOAuthProvider;
impl OAuthProvider for OpenAIOAuthProvider {
fn provider_name(&self) -> &str {
"openai"
}
fn client_id(&self) -> &str {
"app_EMoamEEZ73f0CkXaXp7hrann"
}
fn authorize_url(&self) -> &str {
"https://auth.openai.com/oauth/authorize"
}
fn token_url(&self) -> &str {
"https://auth.openai.com/oauth/token"
}
fn redirect_uri(&self) -> &str {
"http://localhost:1455/auth/callback"
}
fn scopes(&self) -> String {
"openid profile email offline_access".to_string()
}
fn token_request_format(&self) -> TokenRequestFormat {
TokenRequestFormat::FormUrlEncoded
}
fn extra_authorize_params(&self) -> Vec<(&str, &str)> {
vec![
("id_token_add_organizations", "true"),
("codex_cli_simplified_flow", "true"),
]
}
fn fixed_redirect_uri(&self) -> Option<String> {
Some("http://localhost:1455/auth/callback".to_string())
}
fn include_state_in_token_exchange(&self) -> bool {
false
}
fn extract_account_id(&self, response: &Value) -> Option<String> {
let id_token = response["id_token"].as_str().unwrap_or_default();
let access_token = response["access_token"].as_str().unwrap_or_default();
extract_account_id_from_jwt(id_token).or_else(|| extract_account_id_from_jwt(access_token))
}
}
fn extract_account_id_from_jwt(token: &str) -> Option<String> {
let parts: Vec<&str> = token.splitn(3, '.').collect();
if parts.len() < 2 {
return None;
}
let decoded = URL_SAFE_NO_PAD.decode(parts[1]).ok()?;
let claims: Value = serde_json::from_slice(&decoded).ok()?;
claims["chatgpt_account_id"]
.as_str()
.map(|s| s.to_string())
.or_else(|| {
claims["https://api.openai.com/auth"]["chatgpt_account_id"]
.as_str()
.map(|s| s.to_string())
})
.or_else(|| {
claims["organizations"][0]["id"]
.as_str()
.map(|s| s.to_string())
})
}
+15 -6
View File
@@ -1,4 +1,4 @@
use super::{ToolCall, catch_error}; use super::{ThinkingBlock, ToolCall, catch_error};
use crate::utils::AbortSignal; use crate::utils::AbortSignal;
use anyhow::{Context, Result, anyhow, bail}; use anyhow::{Context, Result, anyhow, bail};
@@ -13,6 +13,7 @@ pub struct SseHandler {
abort_signal: AbortSignal, abort_signal: AbortSignal,
buffer: String, buffer: String,
tool_calls: Vec<ToolCall>, tool_calls: Vec<ToolCall>,
thinking: Vec<ThinkingBlock>,
last_tool_calls: Vec<ToolCall>, last_tool_calls: Vec<ToolCall>,
max_call_repeats: usize, max_call_repeats: usize,
call_repeat_chain_len: usize, call_repeat_chain_len: usize,
@@ -26,6 +27,7 @@ impl SseHandler {
abort_signal, abort_signal,
buffer: String::new(), buffer: String::new(),
tool_calls: Vec::new(), tool_calls: Vec::new(),
thinking: Vec::new(),
last_tool_calls: Vec::new(), last_tool_calls: Vec::new(),
max_call_repeats: 2, max_call_repeats: 2,
call_repeat_chain_len: 3, call_repeat_chain_len: 3,
@@ -170,6 +172,10 @@ impl SseHandler {
message message
} }
pub fn thinking_block(&mut self, block: ThinkingBlock) {
self.thinking.push(block);
}
pub fn abort(&self) -> AbortSignal { pub fn abort(&self) -> AbortSignal {
self.abort_signal.clone() self.abort_signal.clone()
} }
@@ -179,11 +185,14 @@ impl SseHandler {
&self.last_tool_calls &self.last_tool_calls
} }
pub fn take(self) -> (String, Vec<ToolCall>) { pub fn take(self) -> (String, Vec<ToolCall>, Vec<ThinkingBlock>) {
let Self { let Self {
buffer, tool_calls, .. buffer,
tool_calls,
thinking,
..
} = self; } = self;
(buffer, tool_calls) (buffer, tool_calls, thinking)
} }
} }
@@ -232,8 +241,8 @@ where
.map(|value| value.to_string()); .map(|value| value.to_string());
let is_event_stream = content_type let is_event_stream = content_type
.as_deref() .as_deref()
.map(|ct| ct.starts_with("text/event-stream")) .map(|ct| ct.is_empty() || ct.starts_with("text/event-stream"))
.unwrap_or(false); .unwrap_or(true);
if !is_event_stream { if !is_event_stream {
let header_value = content_type.unwrap_or_default(); let header_value = content_type.unwrap_or_default();
let text = res.text().await?; let text = res.text().await?;
+26 -7
View File
@@ -119,7 +119,11 @@ fn prepare_chat_completions(
format!("{base_url}/google/models/{model_name}:{func}") format!("{base_url}/google/models/{model_name}:{func}")
} }
ModelCategory::Claude => { ModelCategory::Claude => {
format!("{base_url}/anthropic/models/{model_name}:streamRawPredict") let func = match data.stream {
true => "streamRawPredict",
false => "rawPredict",
};
format!("{base_url}/anthropic/models/{model_name}:{func}")
} }
ModelCategory::Mistral => { ModelCategory::Mistral => {
let func = match data.stream { let func = match data.stream {
@@ -318,7 +322,11 @@ fn gemini_extract_chat_completions_text(data: &Value) -> Result<ChatCompletionsO
bail!("Invalid response data: {data}"); bail!("Invalid response data: {data}");
} }
} }
let output = ChatCompletionsOutput { text, tool_calls }; let output = ChatCompletionsOutput {
text,
tool_calls,
..Default::default()
};
Ok(output) Ok(output)
} }
@@ -330,6 +338,7 @@ pub fn gemini_build_chat_completions_body(
mut messages, mut messages,
temperature, temperature,
top_p, top_p,
reasoning_effort,
functions, functions,
stream: _, stream: _,
} = data; } = data;
@@ -367,8 +376,15 @@ pub fn gemini_build_chat_completions_body(
.collect(); .collect();
vec![json!({ "role": role, "parts": parts })] vec![json!({ "role": role, "parts": parts })]
}, },
MessageContent::ToolCalls(MessageContentToolCalls { tool_results, .. }) => { MessageContent::ToolCalls(MessageContentToolCalls { tool_results, text, .. }) => {
let model_parts: Vec<Value> = tool_results.iter().map(|tool_result| { let mut model_parts: Vec<Value> = vec![];
if !text.is_empty() {
model_parts.push(json!({ "text": text }));
}
for tool_result in tool_results.iter() {
if let Some(round_text) = &tool_result.text {
model_parts.push(json!({ "text": round_text }));
}
let mut part = json!({ let mut part = json!({
"functionCall": { "functionCall": {
"name": tool_result.call.name, "name": tool_result.call.name,
@@ -378,8 +394,8 @@ pub fn gemini_build_chat_completions_body(
if let Some(sig) = &tool_result.call.thought_signature { if let Some(sig) = &tool_result.call.thought_signature {
part["thoughtSignature"] = json!(sig); part["thoughtSignature"] = json!(sig);
} }
part model_parts.push(part);
}).collect(); }
let function_parts: Vec<Value> = tool_results.into_iter().map(|tool_result| { let function_parts: Vec<Value> = tool_results.into_iter().map(|tool_result| {
json!({ json!({
"functionResponse": { "functionResponse": {
@@ -422,6 +438,9 @@ pub fn gemini_build_chat_completions_body(
if let Some(v) = top_p { if let Some(v) = top_p {
body["generationConfig"]["topP"] = v.into(); body["generationConfig"]["topP"] = v.into();
} }
if let Some(v) = reasoning_effort {
body["generationConfig"]["thinking_config"] = json!({"thinking_level": v});
}
if let Some(functions) = functions { if let Some(functions) = functions {
// Gemini doesn't support functions with parameters that have empty properties, so we need to patch it. // Gemini doesn't support functions with parameters that have empty properties, so we need to patch it.
@@ -479,7 +498,7 @@ pub async fn prepare_gcloud_access_token(
let expires_at = Utc::now() let expires_at = Utc::now()
+ Duration::try_seconds(expires_in) + Duration::try_seconds(expires_in)
.ok_or_else(|| anyhow!("Failed to parse expires_in of access_token"))?; .ok_or_else(|| anyhow!("Failed to parse expires_in of access_token"))?;
set_access_token(client_name, token, expires_at.timestamp()) set_access_token(client_name, token, expires_at.timestamp(), None)
} }
Ok(()) Ok(())
} }
+159 -11
View File
@@ -2,6 +2,7 @@ use super::*;
use crate::{ use crate::{
client::Model, client::Model,
config::memory,
function::{Functions, run_llm_function}, function::{Functions, run_llm_function},
}; };
@@ -19,7 +20,7 @@ use fancy_regex::Captures;
use inquire::{Text, validator::Validation}; use inquire::{Text, validator::Validation};
use rust_embed::Embed; use rust_embed::Embed;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ffi::OsStr, path::Path}; use std::{env, ffi::OsStr, path::Path};
const DEFAULT_AGENT_NAME: &str = "rag"; const DEFAULT_AGENT_NAME: &str = "rag";
@@ -42,6 +43,8 @@ pub struct Agent {
graph_rags: HashMap<String, Arc<Rag>>, graph_rags: HashMap<String, Arc<Rag>>,
model: Model, model: Model,
vault: GlobalVault, vault: GlobalVault,
is_graph: bool,
enabled_tools: Option<Vec<String>>,
} }
impl Agent { impl Agent {
@@ -214,6 +217,20 @@ impl Agent {
functions.append_skill_functions(); functions.append_skill_functions();
} }
if app.function_calling_support
&& !matches!(agent_config.memory, Some(false))
&& !matches!(app.memory, Some(false))
{
let memory_exists = paths::global_memory_index_file().exists()
|| env::current_dir()
.ok()
.and_then(|cwd| memory::discover_workspace_memory(&cwd))
.is_some();
if memory_exists {
functions.append_memory_functions();
}
}
agent_config.replace_tools_placeholder(&functions); agent_config.replace_tools_placeholder(&functions);
Ok(Self { Ok(Self {
@@ -228,6 +245,8 @@ impl Agent {
graph_rags, graph_rags,
model, model,
vault: app_state.vault.clone(), vault: app_state.vault.clone(),
is_graph: graph_for_rag.is_some(),
enabled_tools: None,
}) })
} }
@@ -324,6 +343,10 @@ impl Agent {
&self.name &self.name
} }
pub fn is_graph(&self) -> bool {
self.is_graph
}
pub fn functions(&self) -> &Functions { pub fn functions(&self) -> &Functions {
&self.functions &self.functions
} }
@@ -344,6 +367,10 @@ impl Agent {
&self.config.mcp_servers &self.config.mcp_servers
} }
pub fn spawnable_agents(&self) -> Option<&[String]> {
self.config.spawnable_agents.as_deref()
}
pub fn skills_enabled(&self) -> Option<bool> { pub fn skills_enabled(&self) -> Option<bool> {
self.config.skills_enabled self.config.skills_enabled
} }
@@ -352,6 +379,10 @@ impl Agent {
self.config.enabled_skills.as_deref() self.config.enabled_skills.as_deref()
} }
pub fn memory(&self) -> Option<bool> {
self.config.memory
}
pub fn set_skills_enabled(&mut self, value: Option<bool>) { pub fn set_skills_enabled(&mut self, value: Option<bool>) {
self.config.skills_enabled = value; self.config.skills_enabled = value;
} }
@@ -464,6 +495,14 @@ impl Agent {
self.config.continuation_prompt.clone() self.config.continuation_prompt.clone()
} }
pub fn inject_skill_instructions(&self) -> bool {
self.config.inject_skill_instructions
}
pub fn skill_instructions_value(&self) -> Option<String> {
self.config.skill_instructions.clone()
}
pub fn can_spawn_agents(&self) -> bool { pub fn can_spawn_agents(&self) -> bool {
self.config.can_spawn_agents self.config.can_spawn_agents
} }
@@ -492,6 +531,14 @@ impl Agent {
self.config.compression_threshold self.config.compression_threshold
} }
pub fn max_tool_result_chars(&self) -> Option<usize> {
self.config.max_tool_result_chars
}
pub fn compression_keep_last(&self) -> Option<usize> {
self.config.compression_keep_last
}
pub fn is_dynamic_instructions(&self) -> bool { pub fn is_dynamic_instructions(&self) -> bool {
self.config.dynamic_instructions self.config.dynamic_instructions
} }
@@ -548,8 +595,12 @@ impl RoleLike for Agent {
self.config.top_p self.config.top_p
} }
fn reasoning_effort(&self) -> Option<String> {
self.config.reasoning_effort.clone()
}
fn enabled_tools(&self) -> Option<Vec<String>> { fn enabled_tools(&self) -> Option<Vec<String>> {
None self.enabled_tools.clone()
} }
fn enabled_mcp_servers(&self) -> Option<Vec<String>> { fn enabled_mcp_servers(&self) -> Option<Vec<String>> {
@@ -569,19 +620,18 @@ impl RoleLike for Agent {
self.config.top_p = value; self.config.top_p = value;
} }
fn set_reasoning_effort(&mut self, value: Option<String>) {
self.config.reasoning_effort = value;
}
fn set_enabled_tools(&mut self, value: Option<Vec<String>>) { fn set_enabled_tools(&mut self, value: Option<Vec<String>>) {
match value { self.enabled_tools = value.map(|tools| {
Some(tools) => { tools
self.config.global_tools = tools
.into_iter() .into_iter()
.map(|v| v.trim().to_string()) .map(|v| v.trim().to_string())
.filter(|v| !v.is_empty()) .filter(|v| !v.is_empty())
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} });
None => {
self.config.global_tools.clear();
}
}
} }
fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>) { fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>) {
@@ -610,11 +660,15 @@ pub struct AgentConfig {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>, pub top_p: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub agent_session: Option<String>, pub agent_session: Option<String>,
#[serde(default)] #[serde(default)]
pub auto_continue: bool, pub auto_continue: bool,
#[serde(default)] #[serde(default)]
pub can_spawn_agents: bool, pub can_spawn_agents: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spawnable_agents: Option<Vec<String>>,
#[serde(default = "default_max_concurrent_agents")] #[serde(default = "default_max_concurrent_agents")]
pub max_concurrent_agents: usize, pub max_concurrent_agents: usize,
#[serde(default = "default_max_agent_depth")] #[serde(default = "default_max_agent_depth")]
@@ -625,8 +679,18 @@ pub struct AgentConfig {
pub inject_todo_instructions: bool, pub inject_todo_instructions: bool,
#[serde(default = "default_true")] #[serde(default = "default_true")]
pub inject_spawn_instructions: bool, pub inject_spawn_instructions: bool,
#[serde(default = "default_true")]
pub inject_skill_instructions: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub skill_instructions: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub memory: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub compression_threshold: Option<usize>, pub compression_threshold: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_tool_result_chars: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compression_keep_last: Option<usize>,
#[serde(default)] #[serde(default)]
pub description: String, pub description: String,
#[serde(default)] #[serde(default)]
@@ -699,11 +763,14 @@ impl AgentConfig {
model_id: graph.model.clone(), model_id: graph.model.clone(),
temperature: graph.temperature, temperature: graph.temperature,
top_p: graph.top_p, top_p: graph.top_p,
reasoning_effort: graph.reasoning_effort.clone(),
description: graph.description.clone(), description: graph.description.clone(),
global_tools: graph.global_tools.clone(), global_tools: graph.global_tools.clone(),
mcp_servers: graph.mcp_servers.clone(), mcp_servers: graph.mcp_servers.clone(),
skills_enabled: graph.skills_enabled, skills_enabled: graph.skills_enabled,
enabled_skills: graph.enabled_skills.clone(), enabled_skills: graph.enabled_skills.clone(),
inject_skill_instructions: graph.inject_skill_instructions.unwrap_or(true),
skill_instructions: graph.skill_instructions.clone(),
conversation_starters: graph.conversation_starters.clone(), conversation_starters: graph.conversation_starters.clone(),
variables: graph.variables.clone(), variables: graph.variables.clone(),
can_spawn_agents: graph.has_agent_node(), can_spawn_agents: graph.has_agent_node(),
@@ -731,6 +798,9 @@ impl AgentConfig {
if let Some(v) = read_env_value::<f64>(&with_prefix("top_p")) { if let Some(v) = read_env_value::<f64>(&with_prefix("top_p")) {
self.top_p = v; self.top_p = v;
} }
if let Some(v) = read_env_value::<String>(&with_prefix("reasoning_effort")) {
self.reasoning_effort = v;
}
if let Ok(v) = env::var(with_prefix("global_tools")) if let Ok(v) = env::var(with_prefix("global_tools"))
&& let Ok(v) = serde_json::from_str(&v) && let Ok(v) = serde_json::from_str(&v)
{ {
@@ -741,6 +811,11 @@ impl AgentConfig {
{ {
self.mcp_servers = v; self.mcp_servers = v;
} }
if let Ok(v) = env::var(with_prefix("spawnable_agents"))
&& let Ok(v) = serde_json::from_str(&v)
{
self.spawnable_agents = Some(v);
}
if let Some(v) = read_env_value::<String>(&with_prefix("agent_session")) { if let Some(v) = read_env_value::<String>(&with_prefix("agent_session")) {
self.agent_session = v; self.agent_session = v;
} }
@@ -886,6 +961,9 @@ async fn init_graph_rags(
reranker_model: rag_node.reranker_model.clone(), reranker_model: rag_node.reranker_model.clone(),
top_k: rag_node.top_k, top_k: rag_node.top_k,
batch_size: rag_node.batch_size, batch_size: rag_node.batch_size,
extractor_model: rag_node.extractor_model.clone(),
extractor_prompt: rag_node.extractor_prompt.clone(),
graph_hops: rag_node.graph_hops,
}; };
let fully_specified = config.embedding_model.is_some() let fully_specified = config.embedding_model.is_some()
&& config.chunk_size.is_some() && config.chunk_size.is_some()
@@ -961,6 +1039,36 @@ pub fn list_agents() -> Vec<String> {
agents agents
} }
pub fn list_agents_with_descriptions() -> Vec<(String, String)> {
list_agents()
.into_iter()
.map(|name| {
let description = load_agent_description(&name);
(name, description)
})
.collect()
}
#[derive(Deserialize)]
struct AgentMetadataStub {
#[serde(default)]
description: String,
}
fn load_agent_description(name: &str) -> String {
if let Ok(config) = AgentConfig::load(&paths::agent_config_file(name)) {
return config.description;
}
if let Ok(contents) = read_to_string(paths::agent_graph_file(name))
&& let Ok(meta) = serde_yaml::from_str::<AgentMetadataStub>(&contents)
{
return meta.description;
}
String::new()
}
pub fn complete_agent_variables(agent_name: &str) -> Vec<(String, Option<String>)> { pub fn complete_agent_variables(agent_name: &str) -> Vec<(String, Option<String>)> {
let config_path = paths::agent_config_file(agent_name); let config_path = paths::agent_config_file(agent_name);
if !config_path.exists() { if !config_path.exists() {
@@ -1150,4 +1258,44 @@ variables:
assert_eq!(config.max_agent_depth, default_max_agent_depth()); assert_eq!(config.max_agent_depth, default_max_agent_depth());
assert_eq!(config.escalation_timeout, default_escalation_timeout()); assert_eq!(config.escalation_timeout, default_escalation_timeout());
} }
#[test]
fn agent_metadata_stub_extracts_description_from_graph_yaml() {
let yaml = r#"
name: librarian
description: External-reference research agent.
version: "1.0"
start: triage
nodes: {}
"#;
let meta: AgentMetadataStub = serde_yaml::from_str(yaml).unwrap();
assert_eq!(meta.description, "External-reference research agent.");
}
#[test]
fn agent_metadata_stub_extracts_multiline_description() {
let yaml = r#"
name: coder
description: |
Implementation agent. Plans, implements, and runs build + tests in a
bounded fix-loop until verified.
version: "1.0"
"#;
let meta: AgentMetadataStub = serde_yaml::from_str(yaml).unwrap();
assert!(meta.description.starts_with("Implementation agent."));
assert!(meta.description.contains("bounded fix-loop"));
}
#[test]
fn agent_metadata_stub_defaults_when_description_missing() {
let yaml = "name: nameless\nversion: \"1.0\"\n";
let meta: AgentMetadataStub = serde_yaml::from_str(yaml).unwrap();
assert_eq!(meta.description, "");
}
} }
+135 -14
View File
@@ -1,4 +1,4 @@
use crate::client::{ClientConfig, list_models}; use crate::client::{ClientConfig, Model, ModelType, list_models};
use crate::render::{MarkdownRender, RenderOptions}; use crate::render::{MarkdownRender, RenderOptions};
use crate::utils::{IS_STDOUT_TERMINAL, NO_COLOR, decode_bin, get_env_name}; use crate::utils::{IS_STDOUT_TERMINAL, NO_COLOR, decode_bin, get_env_name};
@@ -21,6 +21,7 @@ pub struct AppConfig {
pub model_id: String, pub model_id: String,
pub temperature: Option<f64>, pub temperature: Option<f64>,
pub top_p: Option<f64>, pub top_p: Option<f64>,
pub reasoning_effort: Option<String>,
pub dry_run: bool, pub dry_run: bool,
pub stream: bool, pub stream: bool,
@@ -52,6 +53,8 @@ pub struct AppConfig {
pub max_auto_continues: usize, pub max_auto_continues: usize,
pub inject_todo_instructions: bool, pub inject_todo_instructions: bool,
pub continuation_prompt: Option<String>, pub continuation_prompt: Option<String>,
pub inject_skill_instructions: bool,
pub skill_instructions: Option<String>,
pub repl_prelude: Option<String>, pub repl_prelude: Option<String>,
pub cmd_prelude: Option<String>, pub cmd_prelude: Option<String>,
@@ -59,8 +62,17 @@ pub struct AppConfig {
pub save_session: Option<bool>, pub save_session: Option<bool>,
pub compression_threshold: usize, pub compression_threshold: usize,
pub compression_keep_last: usize,
pub summarization_prompt: Option<String>, pub summarization_prompt: Option<String>,
pub summary_context_prompt: Option<String>, pub summary_context_prompt: Option<String>,
pub max_tool_result_chars: Option<usize>,
pub memory: Option<bool>,
pub memory_cap_with_tools: Option<usize>,
pub memory_cap_without_tools: Option<usize>,
pub workspace_instructions: Option<bool>,
pub workspace_instructions_files: Option<Vec<String>>,
pub rag_embedding_model: Option<String>, pub rag_embedding_model: Option<String>,
pub rag_reranker_model: Option<String>, pub rag_reranker_model: Option<String>,
@@ -68,17 +80,22 @@ pub struct AppConfig {
pub rag_chunk_size: Option<usize>, pub rag_chunk_size: Option<usize>,
pub rag_chunk_overlap: Option<usize>, pub rag_chunk_overlap: Option<usize>,
pub rag_template: Option<String>, pub rag_template: Option<String>,
pub rag_extractor_model: Option<String>,
pub rag_extractor_prompt: Option<String>,
pub rag_graph_hops: usize,
#[serde(default)] #[serde(default)]
pub document_loaders: HashMap<String, String>, pub document_loaders: HashMap<String, String>,
pub highlight: bool, pub highlight: bool,
pub raw_markdown: bool,
pub theme: Option<String>, pub theme: Option<String>,
pub left_prompt: Option<String>, pub left_prompt: Option<String>,
pub right_prompt: Option<String>, pub right_prompt: Option<String>,
pub user_agent: Option<String>, pub user_agent: Option<String>,
pub save_shell_history: bool, pub save_shell_history: bool,
pub no_workspace_mcp: bool,
pub sync_models_url: Option<String>, pub sync_models_url: Option<String>,
pub clients: Vec<ClientConfig>, pub clients: Vec<ClientConfig>,
@@ -90,6 +107,7 @@ impl Default for AppConfig {
model_id: Default::default(), model_id: Default::default(),
temperature: None, temperature: None,
top_p: None, top_p: None,
reasoning_effort: None,
dry_run: false, dry_run: false,
stream: true, stream: true,
@@ -118,6 +136,8 @@ impl Default for AppConfig {
max_auto_continues: 10, max_auto_continues: 10,
inject_todo_instructions: true, inject_todo_instructions: true,
continuation_prompt: None, continuation_prompt: None,
inject_skill_instructions: true,
skill_instructions: None,
repl_prelude: None, repl_prelude: None,
cmd_prelude: None, cmd_prelude: None,
@@ -125,8 +145,17 @@ impl Default for AppConfig {
save_session: None, save_session: None,
compression_threshold: 4000, compression_threshold: 4000,
compression_keep_last: 0,
summarization_prompt: None, summarization_prompt: None,
summary_context_prompt: None, summary_context_prompt: None,
max_tool_result_chars: None,
memory: None,
memory_cap_with_tools: None,
memory_cap_without_tools: None,
workspace_instructions: None,
workspace_instructions_files: None,
rag_embedding_model: None, rag_embedding_model: None,
rag_reranker_model: None, rag_reranker_model: None,
@@ -134,16 +163,21 @@ impl Default for AppConfig {
rag_chunk_size: None, rag_chunk_size: None,
rag_chunk_overlap: None, rag_chunk_overlap: None,
rag_template: None, rag_template: None,
rag_extractor_model: None,
rag_extractor_prompt: None,
rag_graph_hops: 1,
document_loaders: Default::default(), document_loaders: Default::default(),
highlight: true, highlight: true,
raw_markdown: false,
theme: None, theme: None,
left_prompt: None, left_prompt: None,
right_prompt: None, right_prompt: None,
user_agent: None, user_agent: None,
save_shell_history: true, save_shell_history: true,
no_workspace_mcp: false,
sync_models_url: None, sync_models_url: None,
clients: vec![], clients: vec![],
@@ -157,6 +191,7 @@ impl AppConfig {
model_id: config.model_id, model_id: config.model_id,
temperature: config.temperature, temperature: config.temperature,
top_p: config.top_p, top_p: config.top_p,
reasoning_effort: None,
dry_run: config.dry_run, dry_run: config.dry_run,
stream: config.stream, stream: config.stream,
@@ -185,6 +220,8 @@ impl AppConfig {
max_auto_continues: config.max_auto_continues, max_auto_continues: config.max_auto_continues,
inject_todo_instructions: config.inject_todo_instructions, inject_todo_instructions: config.inject_todo_instructions,
continuation_prompt: config.continuation_prompt, continuation_prompt: config.continuation_prompt,
inject_skill_instructions: config.inject_skill_instructions,
skill_instructions: config.skill_instructions,
repl_prelude: config.repl_prelude, repl_prelude: config.repl_prelude,
cmd_prelude: config.cmd_prelude, cmd_prelude: config.cmd_prelude,
@@ -192,8 +229,17 @@ impl AppConfig {
save_session: config.save_session, save_session: config.save_session,
compression_threshold: config.compression_threshold, compression_threshold: config.compression_threshold,
compression_keep_last: config.compression_keep_last,
summarization_prompt: config.summarization_prompt, summarization_prompt: config.summarization_prompt,
summary_context_prompt: config.summary_context_prompt, summary_context_prompt: config.summary_context_prompt,
max_tool_result_chars: config.max_tool_result_chars,
memory: config.memory,
memory_cap_with_tools: config.memory_cap_with_tools,
memory_cap_without_tools: config.memory_cap_without_tools,
workspace_instructions: config.workspace_instructions,
workspace_instructions_files: config.workspace_instructions_files,
rag_embedding_model: config.rag_embedding_model, rag_embedding_model: config.rag_embedding_model,
rag_reranker_model: config.rag_reranker_model, rag_reranker_model: config.rag_reranker_model,
@@ -201,16 +247,21 @@ impl AppConfig {
rag_chunk_size: config.rag_chunk_size, rag_chunk_size: config.rag_chunk_size,
rag_chunk_overlap: config.rag_chunk_overlap, rag_chunk_overlap: config.rag_chunk_overlap,
rag_template: config.rag_template, rag_template: config.rag_template,
rag_extractor_model: config.rag_extractor_model,
rag_extractor_prompt: config.rag_extractor_prompt,
rag_graph_hops: config.rag_graph_hops,
document_loaders: config.document_loaders, document_loaders: config.document_loaders,
highlight: config.highlight, highlight: config.highlight,
raw_markdown: config.raw_markdown,
theme: config.theme, theme: config.theme,
left_prompt: config.left_prompt, left_prompt: config.left_prompt,
right_prompt: config.right_prompt, right_prompt: config.right_prompt,
user_agent: config.user_agent, user_agent: config.user_agent,
save_shell_history: config.save_shell_history, save_shell_history: config.save_shell_history,
no_workspace_mcp: false,
sync_models_url: config.sync_models_url, sync_models_url: config.sync_models_url,
clients: config.clients, clients: config.clients,
@@ -223,6 +274,7 @@ impl AppConfig {
app_config.setup_document_loaders(); app_config.setup_document_loaders();
app_config.setup_user_agent(); app_config.setup_user_agent();
app_config.resolve_model()?; app_config.resolve_model()?;
app_config.validate_reasoning_effort()?;
Ok(app_config) Ok(app_config)
} }
@@ -243,6 +295,31 @@ impl AppConfig {
Ok(()) Ok(())
} }
fn validate_reasoning_effort(&self) -> Result<()> {
let Some(ref effort) = self.reasoning_effort else {
return Ok(());
};
let model = Model::retrieve_model(self, &self.model_id, ModelType::Chat)?;
let levels = model.reasoning_levels();
if levels.is_empty() {
bail!(
"reasoning_effort '{}' is configured but the model does not support reasoning effort",
effort
);
}
if !levels.iter().any(|l| l == effort) {
bail!(
"reasoning_effort '{}' is not valid for the model. Supported levels: {}",
effort,
levels.join(", ")
);
}
Ok(())
}
pub fn resolve_model(&mut self) -> Result<()> { pub fn resolve_model(&mut self) -> Result<()> {
if self.model_id.is_empty() { if self.model_id.is_empty() {
let models = list_models(self, crate::client::ModelType::Chat); let models = list_models(self, crate::client::ModelType::Chat);
@@ -256,26 +333,43 @@ impl AppConfig {
pub fn vault_password_file(&self) -> PathBuf { pub fn vault_password_file(&self) -> PathBuf {
match &self.vault_password_file { match &self.vault_password_file {
Some(path) => match path.exists() { Some(path) => {
true => path.clone(), if path.exists() {
false => gman::config::Config::local_provider_password_file(), return path.clone();
}, }
if let Some(translated) = paths::translate_sandboxed_home_dir(path)
&& translated.exists()
{
info!(
"vault_password_file '{}' not found; resolved to sandboxed path '{}'",
path.display(),
translated.display()
);
return translated;
}
gman::config::Config::local_provider_password_file()
}
None => gman::config::Config::local_provider_password_file(), None => gman::config::Config::local_provider_password_file(),
} }
} }
pub fn editor(&self) -> Result<String> { pub fn editor(&self) -> Result<String> {
super::EDITOR.get_or_init(move || { super::EDITOR.get_or_init(move || {
let editor = self.editor.clone() if let Some(editor) = self.editor.clone()
.or_else(|| env::var("VISUAL").ok().or_else(|| env::var("EDITOR").ok())) .or_else(|| env::var("VISUAL").ok().or_else(|| env::var("EDITOR").ok()))
.unwrap_or_else(|| { && which::which(&editor).is_ok()
if cfg!(windows) { {
return Some(editor);
}
let default = if cfg!(windows) {
"notepad".to_string() "notepad".to_string()
} else { } else {
"nano".to_string() "nano".to_string()
} };
}); which::which(&default).ok().map(|_| default)
which::which(&editor).ok().map(|_| editor)
}) })
.clone() .clone()
.ok_or_else(|| anyhow!("Editor not found. Please add the `editor` configuration or set the $EDITOR or $VISUAL environment variable.")) .ok_or_else(|| anyhow!("Editor not found. Please add the `editor` configuration or set the $EDITOR or $VISUAL environment variable."))
@@ -295,7 +389,7 @@ impl AppConfig {
let theme = if self.highlight { let theme = if self.highlight {
let theme_mode = if self.light_theme() { "light" } else { "dark" }; let theme_mode = if self.light_theme() { "light" } else { "dark" };
let theme_filename = format!("{theme_mode}.tmTheme"); let theme_filename = format!("{theme_mode}.tmTheme");
let theme_path = paths::local_path(&theme_filename); let theme_path = paths::local_dir(&theme_filename);
if theme_path.exists() { if theme_path.exists() {
let theme = ThemeSet::get_theme(&theme_path) let theme = ThemeSet::get_theme(&theme_path)
.with_context(|| format!("Invalid theme at '{}'", theme_path.display()))?; .with_context(|| format!("Invalid theme at '{}'", theme_path.display()))?;
@@ -320,14 +414,26 @@ impl AppConfig {
env::var("COLORTERM").as_ref().map(|v| v.as_str()), env::var("COLORTERM").as_ref().map(|v| v.as_str()),
Ok("truecolor") Ok("truecolor")
); );
Ok(RenderOptions::new(theme, wrap, self.wrap_code, truecolor)) Ok(RenderOptions::new(
theme,
wrap,
self.wrap_code,
self.raw_markdown,
truecolor,
))
} }
pub fn print_markdown(&self, text: &str) -> Result<()> { pub fn print_markdown(&self, text: &str) -> Result<()> {
if *IS_STDOUT_TERMINAL { if *IS_STDOUT_TERMINAL {
let render_options = self.render_options()?; let render_options = self.render_options()?;
let mut markdown_render = MarkdownRender::init(render_options)?; let mut markdown_render = MarkdownRender::init(render_options)?;
println!("{}", markdown_render.render(text)); let body = markdown_render.render(text);
let tail = markdown_render.finalize();
if tail.is_empty() {
println!("{body}");
} else {
println!("{body}\n{tail}");
}
} else { } else {
println!("{text}"); println!("{text}");
} }
@@ -379,6 +485,9 @@ impl AppConfig {
if let Some(v) = super::read_env_value::<f64>(&get_env_name("top_p")) { if let Some(v) = super::read_env_value::<f64>(&get_env_name("top_p")) {
self.top_p = v; self.top_p = v;
} }
if let Some(v) = super::read_env_value::<String>(&get_env_name("reasoning_effort")) {
self.reasoning_effort = v;
}
if let Some(Some(v)) = super::read_env_bool(&get_env_name("dry_run")) { if let Some(Some(v)) = super::read_env_bool(&get_env_name("dry_run")) {
self.dry_run = v; self.dry_run = v;
@@ -479,6 +588,15 @@ impl AppConfig {
if let Some(v) = super::read_env_value::<String>(&get_env_name("rag_template")) { if let Some(v) = super::read_env_value::<String>(&get_env_name("rag_template")) {
self.rag_template = v; self.rag_template = v;
} }
if let Some(v) = super::read_env_value::<String>(&get_env_name("rag_extractor_model")) {
self.rag_extractor_model = v;
}
if let Some(v) = super::read_env_value::<String>(&get_env_name("rag_extractor_prompt")) {
self.rag_extractor_prompt = v;
}
if let Some(v) = super::read_env_value::<usize>(&get_env_name("rag_graph_hops")) {
self.rag_graph_hops = v.unwrap_or(1);
}
if let Ok(v) = env::var(get_env_name("document_loaders")) if let Ok(v) = env::var(get_env_name("document_loaders"))
&& let Ok(v) = serde_json::from_str(&v) && let Ok(v) = serde_json::from_str(&v)
@@ -492,6 +610,9 @@ impl AppConfig {
if *NO_COLOR { if *NO_COLOR {
self.highlight = false; self.highlight = false;
} }
if let Some(Some(v)) = super::read_env_bool(&get_env_name("raw_markdown")) {
self.raw_markdown = v;
}
if self.highlight && self.theme.is_none() { if self.highlight && self.theme.is_none() {
if let Some(v) = super::read_env_value::<String>(&get_env_name("theme")) { if let Some(v) = super::read_env_value::<String>(&get_env_name("theme")) {
self.theme = v; self.theme = v;
+5
View File
@@ -253,6 +253,10 @@ impl Input {
patch_messages(&mut messages, model); patch_messages(&mut messages, model);
model.guard_max_input_tokens(&messages)?; model.guard_max_input_tokens(&messages)?;
let (temperature, top_p) = (self.role().temperature(), self.role().top_p()); let (temperature, top_p) = (self.role().temperature(), self.role().top_p());
let reasoning_effort = self
.role()
.reasoning_effort()
.or_else(|| model.default_reasoning_effort().map(|s| s.to_string()));
let functions = if model.supports_function_calling() { let functions = if model.supports_function_calling() {
let fns = self.functions.clone(); let fns = self.functions.clone();
if let Some(vec) = &fns { if let Some(vec) = &fns {
@@ -268,6 +272,7 @@ impl Input {
messages, messages,
temperature, temperature,
top_p, top_p,
reasoning_effort,
functions, functions,
stream, stream,
}) })
+211
View File
@@ -0,0 +1,211 @@
use std::fs;
use std::path::{Path, PathBuf};
use log::warn;
pub const WORKSPACE_INSTRUCTIONS_FILE_NAME: &str = "COYOTE.md";
pub const DEFAULT_WORKSPACE_INSTRUCTIONS_FILES: [&str; 4] = [
WORKSPACE_INSTRUCTIONS_FILE_NAME,
"AGENTS.md",
"CLAUDE.md",
"GEMINI.md",
];
const INSTRUCTIONS_SIZE_WARN_THRESHOLD: usize = 24_000;
#[derive(Debug, Clone)]
pub struct WorkspaceInstructions {
pub path: PathBuf,
pub content: String,
}
pub fn default_workspace_instructions_files() -> Vec<String> {
DEFAULT_WORKSPACE_INSTRUCTIONS_FILES
.iter()
.map(|s| s.to_string())
.collect()
}
pub fn discover_workspace_instructions(
start: &Path,
file_names: &[String],
) -> Option<WorkspaceInstructions> {
for dir in start.ancestors() {
for name in file_names {
let candidate = dir.join(name);
if !candidate.is_file() {
continue;
}
match fs::read_to_string(&candidate) {
Ok(content) if !content.trim().is_empty() => {
return Some(WorkspaceInstructions {
path: candidate,
content,
});
}
Ok(_) => {}
Err(e) => warn!(
"failed to read workspace instructions at {}: {e}",
candidate.display()
),
}
}
}
None
}
pub fn build_instructions_section(instructions: &WorkspaceInstructions) -> String {
let char_count = instructions.content.chars().count();
if char_count > INSTRUCTIONS_SIZE_WARN_THRESHOLD {
warn!(
"workspace instructions at {} are large ({char_count} chars); \
consider moving detail into workspace memory drill files",
instructions.path.display()
);
}
format!(
"<workspace_instructions source=\"{}\">\n{}\n</workspace_instructions>",
instructions.path.display(),
instructions.content.trim_end()
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env, time};
use time::SystemTime;
fn temp_root(label: &str) -> PathBuf {
let unique = SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = env::temp_dir().join(format!("coyote-instructions-{label}-{unique}"));
fs::create_dir_all(&root).unwrap();
root
}
fn defaults() -> Vec<String> {
default_workspace_instructions_files()
}
#[test]
fn discovery_returns_none_when_no_file_exists() {
let root = temp_root("none");
assert!(discover_workspace_instructions(&root, &defaults()).is_none());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_finds_coyote_md() {
let root = temp_root("coyote");
fs::write(root.join("COYOTE.md"), "coyote instructions").unwrap();
let found = discover_workspace_instructions(&root, &defaults()).unwrap();
assert_eq!(found.path, root.join("COYOTE.md"));
assert_eq!(found.content, "coyote instructions");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_falls_back_through_chain_in_order() {
let root = temp_root("fallback");
fs::write(root.join("GEMINI.md"), "gemini instructions").unwrap();
let found = discover_workspace_instructions(&root, &defaults()).unwrap();
assert_eq!(found.path, root.join("GEMINI.md"));
fs::write(root.join("CLAUDE.md"), "claude instructions").unwrap();
let found = discover_workspace_instructions(&root, &defaults()).unwrap();
assert_eq!(found.path, root.join("CLAUDE.md"));
fs::write(root.join("AGENTS.md"), "agents instructions").unwrap();
let found = discover_workspace_instructions(&root, &defaults()).unwrap();
assert_eq!(found.path, root.join("AGENTS.md"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_prefers_coyote_md_over_fallbacks() {
let root = temp_root("precedence");
fs::write(root.join("COYOTE.md"), "coyote").unwrap();
fs::write(root.join("AGENTS.md"), "agents").unwrap();
fs::write(root.join("CLAUDE.md"), "claude").unwrap();
let found = discover_workspace_instructions(&root, &defaults()).unwrap();
assert_eq!(found.path, root.join("COYOTE.md"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_walks_up_from_nested_dir() {
let root = temp_root("walk_up");
fs::write(root.join("AGENTS.md"), "root instructions").unwrap();
let nested = root.join("src").join("deep");
fs::create_dir_all(&nested).unwrap();
let found = discover_workspace_instructions(&nested, &defaults()).unwrap();
assert_eq!(found.path, root.join("AGENTS.md"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_prefers_closer_file_over_higher_priority_name_above() {
let root = temp_root("depth_first");
fs::write(root.join("COYOTE.md"), "root coyote").unwrap();
let nested = root.join("packages").join("app");
fs::create_dir_all(&nested).unwrap();
fs::write(nested.join("CLAUDE.md"), "nested claude").unwrap();
let found = discover_workspace_instructions(&nested, &defaults()).unwrap();
assert_eq!(found.path, nested.join("CLAUDE.md"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_skips_empty_files() {
let root = temp_root("empty");
fs::write(root.join("COYOTE.md"), " \n").unwrap();
fs::write(root.join("AGENTS.md"), "real content").unwrap();
let found = discover_workspace_instructions(&root, &defaults()).unwrap();
assert_eq!(found.path, root.join("AGENTS.md"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discovery_honors_custom_file_chain() {
let root = temp_root("custom");
fs::write(root.join("CLAUDE.md"), "claude").unwrap();
let only_agents = vec!["AGENTS.md".to_string()];
assert!(discover_workspace_instructions(&root, &only_agents).is_none());
let empty: Vec<String> = vec![];
assert!(discover_workspace_instructions(&root, &empty).is_none());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn build_section_wraps_content_with_source_path() {
let instructions = WorkspaceInstructions {
path: PathBuf::from("/ws/COYOTE.md"),
content: "Do the thing.\n".into(),
};
let section = build_instructions_section(&instructions);
assert!(section.starts_with("<workspace_instructions source=\"/ws/COYOTE.md\">"));
assert!(section.contains("Do the thing."));
assert!(section.ends_with("</workspace_instructions>"));
}
}
+23 -2
View File
@@ -1,4 +1,7 @@
use crate::mcp::{ConnectedServer, JsonField, McpServer, McpTransportType, spawn_mcp_server}; use crate::mcp::{
ConnectedServer, JsonField, McpServer, McpTransportType, is_auth_required_error, oauth,
spawn_mcp_server,
};
use anyhow::Result; use anyhow::Result;
use parking_lot::Mutex; use parking_lot::Mutex;
@@ -99,7 +102,23 @@ impl McpFactory {
return Ok(existing); return Ok(existing);
} }
let handle = spawn_mcp_server(spec, log_path).await?; let bearer_token = if spec.is_remote() {
oauth::load_valid_mcp_token(name)
} else {
None
};
let handle = spawn_mcp_server(spec, log_path, bearer_token)
.await
.map_err(|e| {
if is_auth_required_error(&e) {
e.context(format!(
"MCP server '{name}' requires OAuth authentication. \
Run `coyote --auth-mcp {name}` or `.mcp auth {name}` in the REPL to authenticate."
))
} else {
e
}
})?;
self.insert_active(key, &handle); self.insert_active(key, &handle);
Ok(handle) Ok(handle)
} }
@@ -125,6 +144,7 @@ mod tests {
cwd: None, cwd: None,
url: None, url: None,
headers: None, headers: None,
oauth: None,
} }
} }
@@ -141,6 +161,7 @@ mod tests {
cwd: None, cwd: None,
url: Some(url.to_string()), url: Some(url.to_string()),
headers, headers,
oauth: None,
} }
} }
+722
View File
@@ -0,0 +1,722 @@
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use log::warn;
use serde::{Deserialize, Serialize};
use crate::config::{
GIT_DIR_NAME, GITIGNORE_FILE_NAME, MEMORY_DIR_NAME, MEMORY_INDEX_FILE_NAME,
WORKSPACE_COYOTE_DIR_NAME, paths,
};
pub const DEFAULT_MEMORY_CAP_WITH_TOOLS: usize = 6_000;
pub const DEFAULT_MEMORY_CAP_WITHOUT_TOOLS: usize = 12_000;
#[derive(Debug, Clone)]
pub struct WorkspaceMemory {
pub workspace_root: PathBuf,
pub dir: PathBuf,
}
pub fn discover_workspace_memory(start: &Path) -> Option<WorkspaceMemory> {
for dir in start.ancestors() {
let structured = dir.join(WORKSPACE_COYOTE_DIR_NAME).join(MEMORY_DIR_NAME);
if structured.join(MEMORY_INDEX_FILE_NAME).exists() {
return Some(WorkspaceMemory {
workspace_root: dir.to_path_buf(),
dir: structured,
});
}
}
None
}
pub fn find_git_root(start: &Path) -> Option<PathBuf> {
for dir in start.ancestors() {
if dir.join(GIT_DIR_NAME).exists() {
return Some(dir.to_path_buf());
}
}
None
}
pub fn bootstrap_workspace_memory(git_root: &Path) -> Result<PathBuf> {
let mem_dir = paths::workspace_memory_dir_for(git_root);
fs::create_dir_all(&mem_dir)
.with_context(|| format!("create memory dir {}", mem_dir.display()))?;
let index_path = mem_dir.join(MEMORY_INDEX_FILE_NAME);
if !index_path.exists() {
fs::write(&index_path, "# Workspace Memory Index\n\n")
.with_context(|| format!("write {}", index_path.display()))?;
}
let gitignore_appended = append_gitignore_entry(git_root)?;
let suffix = if gitignore_appended {
" (appended .coyote/memory/ to .gitignore)"
} else {
""
};
warn!(
"auto-bootstrapped workspace memory at {}{}",
mem_dir.display(),
suffix
);
Ok(mem_dir)
}
pub fn append_gitignore_entry(git_root: &Path) -> Result<bool> {
let gitignore = git_root.join(GITIGNORE_FILE_NAME);
let entry = format!("{WORKSPACE_COYOTE_DIR_NAME}/{MEMORY_DIR_NAME}/");
let entry_no_slash = format!("{WORKSPACE_COYOTE_DIR_NAME}/{MEMORY_DIR_NAME}");
let existing = fs::read_to_string(&gitignore).unwrap_or_default();
let already_present = existing.lines().any(|line| {
let trimmed = line.trim();
trimmed == entry || trimmed == entry_no_slash
});
if already_present {
return Ok(false);
}
let new_content = if existing.is_empty() {
format!("{entry}\n")
} else if existing.ends_with('\n') {
format!("{existing}{entry}\n")
} else {
format!("{existing}\n{entry}\n")
};
fs::write(&gitignore, new_content).with_context(|| format!("write {}", gitignore.display()))?;
Ok(true)
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct MemoryFrontmatter {
#[serde(default)]
pub name: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default, rename = "type")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub superseded_by: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires: Option<String>,
}
#[derive(Debug, Clone)]
pub struct MemoryFile {
pub path: PathBuf,
pub frontmatter: MemoryFrontmatter,
pub body: String,
}
impl MemoryFile {
pub fn load(path: &Path) -> Result<Self> {
let raw = fs::read_to_string(path)
.with_context(|| format!("read memory file {}", path.display()))?;
let (frontmatter, body) = parse_frontmatter(&raw)
.with_context(|| format!("parse frontmatter in {}", path.display()))?;
Ok(Self {
path: path.to_path_buf(),
frontmatter,
body,
})
}
pub fn save(&self) -> Result<()> {
if let Some(parent) = self.path.parent() {
fs::create_dir_all(parent)?;
}
let frontmatter_yaml = serde_yaml::to_string(&self.frontmatter)?;
let content = format!("---\n{}---\n\n{}", frontmatter_yaml, self.body);
fs::write(&self.path, content)?;
Ok(())
}
pub fn char_len(&self) -> usize {
self.body.chars().count()
}
}
fn parse_frontmatter(raw: &str) -> Result<(MemoryFrontmatter, String)> {
let trimmed = raw.trim_start();
if !trimmed.starts_with("---") {
return Ok((MemoryFrontmatter::default(), raw.to_string()));
}
let after = &trimmed[3..];
let Some(end) = after.find("\n---") else {
return Ok((MemoryFrontmatter::default(), raw.to_string()));
};
let yaml = &after[..end];
let body = after[end + 4..].trim_start_matches('\n').to_string();
let frontmatter: MemoryFrontmatter =
serde_yaml::from_str(yaml.trim()).context("parse YAML frontmatter")?;
Ok((frontmatter, body))
}
#[derive(Debug, Clone)]
pub struct MemoryStore {
pub global_dir: PathBuf,
pub workspace: Option<WorkspaceMemory>,
}
impl MemoryStore {
pub fn new(cwd: &Path) -> Self {
Self {
global_dir: paths::global_memory_dir(),
workspace: discover_workspace_memory(cwd),
}
}
pub fn load_global_index(&self) -> Result<Option<String>> {
let path = self.global_dir.join(MEMORY_INDEX_FILE_NAME);
if path.exists() {
Ok(Some(fs::read_to_string(path)?))
} else {
Ok(None)
}
}
pub fn load_workspace_index(&self) -> Result<Option<String>> {
match &self.workspace {
None => Ok(None),
Some(ws) => {
let index = ws.dir.join(MEMORY_INDEX_FILE_NAME);
if index.exists() {
Ok(Some(fs::read_to_string(index)?))
} else {
Ok(None)
}
}
}
}
pub fn list_files(&self) -> Result<Vec<MemoryFile>> {
let mut out = Vec::new();
if self.global_dir.exists() {
collect_md_files(&self.global_dir, &mut out)?;
}
if let Some(ws) = &self.workspace {
collect_md_files(&ws.dir, &mut out)?;
}
Ok(out)
}
}
pub fn build_memory_section(
store: &MemoryStore,
with_tools: bool,
cap: usize,
) -> Result<Option<String>> {
let global_index = store.load_global_index()?;
let workspace_index = store.load_workspace_index()?;
if global_index.is_none() && workspace_index.is_none() {
return Ok(None);
}
let mut buf = String::from("<memory>\n");
let mut consumed = 0usize;
if let Some(s) = &global_index {
buf.push_str("<global_index>\n");
buf.push_str(s);
buf.push_str("\n</global_index>\n");
consumed += s.chars().count();
}
if let Some(s) = &workspace_index {
buf.push_str("<workspace_index>\n");
buf.push_str(s);
buf.push_str("\n</workspace_index>\n");
consumed += s.chars().count();
}
if consumed > cap {
warn!(
"memory indexes ({} chars) exceed cap ({} chars); injecting fully - \
consider raising memory_cap_* in config or shrinking MEMORY.md",
consumed, cap
);
}
if !with_tools {
let mut budget = cap.saturating_sub(consumed);
let mut files = store.list_files()?;
files.sort_by(|a, b| a.frontmatter.name.cmp(&b.frontmatter.name));
let mut omitted = 0usize;
for f in files {
let needed = f.body.chars().count() + 50;
if needed > budget {
omitted += 1;
continue;
}
buf.push_str(&format!("<file name=\"{}\">\n", f.frontmatter.name));
buf.push_str(&f.body);
buf.push_str("\n</file>\n");
budget = budget.saturating_sub(needed);
}
if omitted > 0 {
buf.push_str(&format!(
"<!-- {} memory file(s) omitted; enable function calling for full access -->\n",
omitted
));
}
}
buf.push_str("</memory>");
Ok(Some(buf))
}
fn collect_md_files(dir: &Path, out: &mut Vec<MemoryFile>) -> Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("md") {
continue;
}
if path.file_name().and_then(|n| n.to_str()) == Some(MEMORY_INDEX_FILE_NAME) {
continue;
}
match MemoryFile::load(&path) {
Ok(f) => out.push(f),
Err(e) => warn!("skip malformed memory file {}: {}", path.display(), e),
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env, time};
use time::SystemTime;
fn temp_root(label: &str) -> PathBuf {
let unique = SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = env::temp_dir().join(format!("coyote-memory-{label}-{unique}"));
fs::create_dir_all(&root).unwrap();
root
}
#[test]
fn loads_global_and_workspace_indexes_from_test_dirs() {
let root = temp_root("phase1");
let workspace = root.join("workspace");
let workspace_memory_dir = workspace
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(MEMORY_DIR_NAME);
fs::create_dir_all(&workspace_memory_dir).unwrap();
fs::write(
workspace_memory_dir.join(MEMORY_INDEX_FILE_NAME),
"workspace-content",
)
.unwrap();
let global = root.join("global");
fs::create_dir_all(&global).unwrap();
fs::write(global.join(MEMORY_INDEX_FILE_NAME), "global-content").unwrap();
let store = MemoryStore {
global_dir: global,
workspace: discover_workspace_memory(&workspace),
};
assert_eq!(
store.load_global_index().unwrap().as_deref(),
Some("global-content")
);
assert_eq!(
store.load_workspace_index().unwrap().as_deref(),
Some("workspace-content")
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn workspace_discovery_ignores_root_instructions_file() {
let root = temp_root("no_lite");
let workspace = root.join("ws");
fs::create_dir_all(&workspace).unwrap();
fs::write(workspace.join("COYOTE.md"), "instructions, not memory").unwrap();
assert!(discover_workspace_memory(&workspace).is_none());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn build_memory_section_returns_none_when_no_memory_exists() {
let root = temp_root("none");
let workspace = root.join("ws");
fs::create_dir_all(&workspace).unwrap();
let store = MemoryStore {
global_dir: root.join("global"),
workspace: discover_workspace_memory(&workspace),
};
assert!(build_memory_section(&store, true, 6_000).unwrap().is_none());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn build_memory_section_injects_only_indexes_with_tools_on() {
let root = temp_root("indexes_only");
let workspace = root.join("ws");
let structured = workspace
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(MEMORY_DIR_NAME);
fs::create_dir_all(&structured).unwrap();
fs::write(
structured.join(MEMORY_INDEX_FILE_NAME),
"workspace-index-content",
)
.unwrap();
fs::write(
structured.join("foo.md"),
"---\nname: foo\n---\nfoo body that should not appear\n",
)
.unwrap();
let store = MemoryStore {
global_dir: root.join("global"),
workspace: discover_workspace_memory(&workspace),
};
let section = build_memory_section(&store, true, 6_000)
.unwrap()
.expect("memory section should exist");
assert!(section.contains("workspace-index-content"));
assert!(!section.contains("foo body that should not appear"));
assert!(section.starts_with("<memory>"));
assert!(section.ends_with("</memory>"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn build_memory_section_injects_drill_bodies_alphabetically_without_tools() {
let root = temp_root("drill_bodies");
let workspace = root.join("ws");
let structured = workspace
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(MEMORY_DIR_NAME);
fs::create_dir_all(&structured).unwrap();
fs::write(structured.join(MEMORY_INDEX_FILE_NAME), "idx").unwrap();
fs::write(
structured.join("zebra.md"),
"---\nname: zebra\n---\nzebra body\n",
)
.unwrap();
fs::write(
structured.join("alpha.md"),
"---\nname: alpha\n---\nalpha body\n",
)
.unwrap();
let store = MemoryStore {
global_dir: root.join("global"),
workspace: discover_workspace_memory(&workspace),
};
let section = build_memory_section(&store, false, 6_000)
.unwrap()
.expect("memory section should exist");
let alpha_pos = section.find("alpha body").expect("alpha body missing");
let zebra_pos = section.find("zebra body").expect("zebra body missing");
assert!(alpha_pos < zebra_pos, "drill bodies must be alphabetical");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn build_memory_section_omits_drill_bodies_when_cap_exceeded() {
let root = temp_root("cap");
let workspace = root.join("ws");
let structured = workspace
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(MEMORY_DIR_NAME);
fs::create_dir_all(&structured).unwrap();
fs::write(structured.join(MEMORY_INDEX_FILE_NAME), "idx").unwrap();
let big_body = "x".repeat(200);
fs::write(
structured.join("big.md"),
format!("---\nname: big\n---\n{}\n", big_body),
)
.unwrap();
let store = MemoryStore {
global_dir: root.join("global"),
workspace: discover_workspace_memory(&workspace),
};
let section = build_memory_section(&store, false, 100)
.unwrap()
.expect("memory section should exist");
assert!(!section.contains(&big_body));
assert!(section.contains("memory file(s) omitted"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn parse_frontmatter_extracts_yaml() {
let raw = "---\nname: foo\ndescription: a thing\ntype: user\n---\nBody text\n";
let (fm, body) = parse_frontmatter(raw).unwrap();
assert_eq!(fm.name, "foo");
assert_eq!(fm.description.as_deref(), Some("a thing"));
assert_eq!(fm.kind.as_deref(), Some("user"));
assert_eq!(body, "Body text\n");
}
#[test]
fn parse_frontmatter_handles_missing_block() {
let raw = "# Just markdown, no frontmatter\nbody";
let (fm, body) = parse_frontmatter(raw).unwrap();
assert_eq!(fm.name, "");
assert!(fm.kind.is_none());
assert_eq!(body, raw);
}
#[test]
fn parse_frontmatter_handles_unterminated_block() {
let raw = "---\nname: oops\nno closing delimiter\n# rest of doc";
let (fm, body) = parse_frontmatter(raw).unwrap();
assert_eq!(fm.name, "");
assert_eq!(body, raw);
}
#[test]
fn memory_file_save_and_load_roundtrip() {
let root = temp_root("roundtrip");
let path = root.join("test.md");
let file = MemoryFile {
path: path.clone(),
frontmatter: MemoryFrontmatter {
name: "test".into(),
description: Some("a test".into()),
kind: Some("user".into()),
..Default::default()
},
body: "Hello world\nmore text".into(),
};
file.save().unwrap();
let loaded = MemoryFile::load(&path).unwrap();
assert_eq!(loaded.frontmatter.name, "test");
assert_eq!(loaded.frontmatter.description.as_deref(), Some("a test"));
assert_eq!(loaded.frontmatter.kind.as_deref(), Some("user"));
assert_eq!(loaded.body, "Hello world\nmore text");
let raw = fs::read_to_string(&path).unwrap();
assert!(raw.contains("type: user"), "kind must serialize as 'type:'");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn discover_walks_up_from_nested_dir() {
let root = temp_root("walk_up");
let workspace = root.join("ws");
let mem_dir = workspace
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(MEMORY_DIR_NAME);
fs::create_dir_all(&mem_dir).unwrap();
fs::write(mem_dir.join(MEMORY_INDEX_FILE_NAME), "idx").unwrap();
let nested = workspace.join("src").join("deep").join("path");
fs::create_dir_all(&nested).unwrap();
let found = discover_workspace_memory(&nested).expect("workspace memory should be found");
assert_eq!(found.dir, mem_dir);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn find_git_root_returns_dir_containing_git_dir() {
let root = temp_root("git_root");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
assert_eq!(find_git_root(&repo), Some(repo.clone()));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn find_git_root_walks_up_from_nested_dir() {
let root = temp_root("git_root_walk");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
let nested = repo.join("a").join("b").join("c");
fs::create_dir_all(&nested).unwrap();
assert_eq!(find_git_root(&nested), Some(repo));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn find_git_root_treats_git_file_as_repo_marker() {
let root = temp_root("git_root_worktree");
let worktree = root.join("worktree");
fs::create_dir_all(&worktree).unwrap();
fs::write(
worktree.join(GIT_DIR_NAME),
"gitdir: /elsewhere/.git/worktrees/wt\n",
)
.unwrap();
assert_eq!(find_git_root(&worktree), Some(worktree));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn find_git_root_returns_none_when_no_git() {
let root = temp_root("git_root_missing");
let bare = root.join("bare");
fs::create_dir_all(&bare).unwrap();
assert_eq!(find_git_root(&bare), None);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn bootstrap_creates_structured_layout_and_index() {
let root = temp_root("bootstrap_layout");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
let mem_dir = bootstrap_workspace_memory(&repo).unwrap();
assert_eq!(mem_dir, paths::workspace_memory_dir_for(&repo));
assert!(mem_dir.is_dir());
let index = mem_dir.join(MEMORY_INDEX_FILE_NAME);
assert!(index.exists());
let body = fs::read_to_string(&index).unwrap();
assert!(body.starts_with("# Workspace Memory Index"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn bootstrap_creates_gitignore_when_absent() {
let root = temp_root("bootstrap_gi_new");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
bootstrap_workspace_memory(&repo).unwrap();
let gi = repo.join(GITIGNORE_FILE_NAME);
assert!(gi.exists());
let body = fs::read_to_string(&gi).unwrap();
assert!(body.contains(".coyote/memory/"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn bootstrap_appends_to_existing_gitignore_without_trailing_newline() {
let root = temp_root("bootstrap_gi_append");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
fs::write(repo.join(GITIGNORE_FILE_NAME), "target/").unwrap();
bootstrap_workspace_memory(&repo).unwrap();
let body = fs::read_to_string(repo.join(GITIGNORE_FILE_NAME)).unwrap();
assert!(body.contains("target/"));
assert!(body.contains(".coyote/memory/"));
assert!(body.ends_with('\n'));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn bootstrap_is_idempotent_on_gitignore_entry() {
let root = temp_root("bootstrap_gi_idempotent");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
let original = "target/\n.coyote/memory/\n";
fs::write(repo.join(GITIGNORE_FILE_NAME), original).unwrap();
bootstrap_workspace_memory(&repo).unwrap();
let body = fs::read_to_string(repo.join(GITIGNORE_FILE_NAME)).unwrap();
assert_eq!(body, original, "gitignore must be untouched");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn bootstrap_treats_entry_without_trailing_slash_as_present() {
let root = temp_root("bootstrap_gi_no_slash");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
let original = ".coyote/memory\n";
fs::write(repo.join(GITIGNORE_FILE_NAME), original).unwrap();
bootstrap_workspace_memory(&repo).unwrap();
let body = fs::read_to_string(repo.join(GITIGNORE_FILE_NAME)).unwrap();
assert_eq!(body, original);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn bootstrap_does_not_clobber_existing_index() {
let root = temp_root("bootstrap_existing_index");
let repo = root.join("repo");
fs::create_dir_all(repo.join(GIT_DIR_NAME)).unwrap();
let mem_dir = paths::workspace_memory_dir_for(&repo);
fs::create_dir_all(&mem_dir).unwrap();
let preserved = "# Custom Index\n\n- [[foo]]: keep me\n";
fs::write(mem_dir.join(MEMORY_INDEX_FILE_NAME), preserved).unwrap();
bootstrap_workspace_memory(&repo).unwrap();
let body = fs::read_to_string(mem_dir.join(MEMORY_INDEX_FILE_NAME)).unwrap();
assert_eq!(body, preserved);
let _ = fs::remove_dir_all(&root);
}
}
+79 -11
View File
@@ -3,10 +3,12 @@ mod app_config;
mod app_state; mod app_state;
mod input; mod input;
mod install_remote; mod install_remote;
pub(crate) mod instructions;
mod macros; mod macros;
mod mcp_factory; mod mcp_factory;
pub(crate) mod memory;
pub(crate) mod paths; pub(crate) mod paths;
mod prompts; pub(crate) mod prompts;
mod rag_cache; mod rag_cache;
mod request_context; mod request_context;
mod role; mod role;
@@ -20,6 +22,7 @@ mod update;
pub use self::agent::{ pub use self::agent::{
Agent, AgentVariable, AgentVariables, complete_agent_variables, list_agents, Agent, AgentVariable, AgentVariables, complete_agent_variables, list_agents,
list_agents_with_descriptions,
}; };
#[allow(unused_imports)] #[allow(unused_imports)]
pub use self::app_config::AppConfig; pub use self::app_config::AppConfig;
@@ -28,11 +31,11 @@ pub use self::app_state::AppState;
pub use self::input::Input; pub use self::input::Input;
pub use self::install_remote::{install_remote, install_remote_from_repl_args}; pub use self::install_remote::{install_remote, install_remote_from_repl_args};
#[allow(unused_imports)] #[allow(unused_imports)]
pub use self::request_context::{RenderMode, RequestContext}; pub use self::request_context::{RenderMode, RequestContext, should_inject_skill_instructions};
pub use self::role::{ pub use self::role::{
CODE_ROLE, CREATE_TITLE_ROLE, EXPLAIN_SHELL_ROLE, Role, RoleLike, SHELL_ROLE, CODE_ROLE, CREATE_TITLE_ROLE, EXPLAIN_SHELL_ROLE, Role, RoleLike, SHELL_ROLE,
}; };
use self::session::Session; pub use self::session::Session;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use self::skill::Skill; pub use self::skill::Skill;
#[allow(unused_imports)] #[allow(unused_imports)]
@@ -42,7 +45,7 @@ pub use self::skill_registry::SkillRegistry;
pub use self::update::run_self_update; pub use self::update::run_self_update;
use crate::client::{ use crate::client::{
ClientConfig, MessageContentToolCalls, Model, ModelType, OPENAI_COMPATIBLE_PROVIDERS, ClientConfig, MessageContentToolCalls, Model, ModelType, OPENAI_COMPATIBLE_PROVIDERS,
ProviderModels, create_client_config, list_client_types, ProviderModels, create_client_config, list_client_types, oauth,
}; };
use crate::function::{FunctionDeclaration, Functions}; use crate::function::{FunctionDeclaration, Functions};
use crate::rag::Rag; use crate::rag::Rag;
@@ -61,7 +64,7 @@ use indoc::formatdoc;
use inquire::{Confirm, Select}; use inquire::{Confirm, Select};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use std::collections::HashMap; use std::collections::{HashMap, HashSet};
use std::sync::LazyLock; use std::sync::LazyLock;
use std::{ use std::{
env, env,
@@ -134,11 +137,23 @@ const RAGS_DIR_NAME: &str = "rags";
const FUNCTIONS_DIR_NAME: &str = "functions"; const FUNCTIONS_DIR_NAME: &str = "functions";
const FUNCTIONS_BIN_DIR_NAME: &str = "bin"; const FUNCTIONS_BIN_DIR_NAME: &str = "bin";
const AGENTS_DIR_NAME: &str = "agents"; const AGENTS_DIR_NAME: &str = "agents";
const REPL_HISTORY_DIR_NAME: &str = "repl-history";
const GLOBAL_TOOLS_DIR_NAME: &str = "tools"; const GLOBAL_TOOLS_DIR_NAME: &str = "tools";
const GLOBAL_TOOLS_UTILS_DIR_NAME: &str = "utils"; const GLOBAL_TOOLS_UTILS_DIR_NAME: &str = "utils";
const BASH_PROMPT_UTILS_FILE_NAME: &str = "prompt-utils.sh"; const BASH_PROMPT_UTILS_FILE_NAME: &str = "prompt-utils.sh";
const MCP_FILE_NAME: &str = "mcp.json"; const MCP_FILE_NAME: &str = "mcp.json";
const DEFAULT_VISIBLE_TOOLS: [&str; 18] = [ const HIDDEN_MCP_FILE_NAME: &str = ".mcp.json";
const MEMORY_DIR_NAME: &str = "memory";
const MEMORY_INDEX_FILE_NAME: &str = "MEMORY.md";
const WORKSPACE_COYOTE_DIR_NAME: &str = ".coyote";
const SBX_KIT_DIR_NAME: &str = "sbx-kit";
const SBX_KIT_HASH_FILE: &str = "kit.sha256";
const SBX_MIXIN_FILE_NAME: &str = "sbx-mixin.yaml";
const SBX_VAULT_MIXINS_DIR_NAME: &str = "sbx-vault-mixins";
const SBX_MIXIN_KITS_DIR_NAME: &str = "sbx-mixin-kits";
const GIT_DIR_NAME: &str = ".git";
const GITIGNORE_FILE_NAME: &str = ".gitignore";
const DEFAULT_VISIBLE_TOOLS: [&str; 19] = [
"execute_command.sh", "execute_command.sh",
"execute_py_code.py", "execute_py_code.py",
"execute_sql_code.sh", "execute_sql_code.sh",
@@ -152,6 +167,7 @@ const DEFAULT_VISIBLE_TOOLS: [&str; 18] = [
"fs_read.sh", "fs_read.sh",
"fs_rm.sh", "fs_rm.sh",
"fs_write.sh", "fs_write.sh",
"ast_grep.sh",
"get_current_time.sh", "get_current_time.sh",
"get_current_weather.sh", "get_current_weather.sh",
"search_wikipedia.sh", "search_wikipedia.sh",
@@ -169,7 +185,7 @@ const SUMMARIZATION_PROMPT: &str =
const SUMMARY_CONTEXT_PROMPT: &str = "This is a summary of the chat history as a recap: "; const SUMMARY_CONTEXT_PROMPT: &str = "This is a summary of the chat history as a recap: ";
const LEFT_PROMPT: &str = "{color.red}{model}){color.green}{?session {?agent {agent}>}{session}{?role /}}{!session {?agent {agent}>}}{role}{?rag @{rag}}{color.cyan}{?session )}{!session >}{color.reset} "; const LEFT_PROMPT: &str = "{color.red}{model}){color.green}{?session {?agent {agent}>}{session}{?role /}}{!session {?agent {agent}>}}{role}{?rag @{rag}}{color.cyan}{?session )}{!session >}{color.reset} ";
const RIGHT_PROMPT: &str = "{color.purple}{?session {?consume_tokens {consume_tokens}({consume_percent}%)}{!consume_tokens {consume_tokens}}}{color.reset}"; const RIGHT_PROMPT: &str = "{color.cyan}{?reasoning_effort [{reasoning_effort}] }{color.purple}{?session {?consume_tokens {consume_tokens}({consume_percent}%)}{!consume_tokens {consume_tokens}}}{color.reset}";
static EDITOR: OnceLock<Option<String>> = OnceLock::new(); static EDITOR: OnceLock<Option<String>> = OnceLock::new();
@@ -214,6 +230,8 @@ pub struct Config {
pub max_auto_continues: usize, pub max_auto_continues: usize,
pub inject_todo_instructions: bool, pub inject_todo_instructions: bool,
pub continuation_prompt: Option<String>, pub continuation_prompt: Option<String>,
pub inject_skill_instructions: bool,
pub skill_instructions: Option<String>,
pub repl_prelude: Option<String>, pub repl_prelude: Option<String>,
pub cmd_prelude: Option<String>, pub cmd_prelude: Option<String>,
@@ -221,8 +239,17 @@ pub struct Config {
pub save_session: Option<bool>, pub save_session: Option<bool>,
pub compression_threshold: usize, pub compression_threshold: usize,
pub compression_keep_last: usize,
pub summarization_prompt: Option<String>, pub summarization_prompt: Option<String>,
pub summary_context_prompt: Option<String>, pub summary_context_prompt: Option<String>,
pub max_tool_result_chars: Option<usize>,
pub memory: Option<bool>,
pub memory_cap_with_tools: Option<usize>,
pub memory_cap_without_tools: Option<usize>,
pub workspace_instructions: Option<bool>,
pub workspace_instructions_files: Option<Vec<String>>,
pub rag_embedding_model: Option<String>, pub rag_embedding_model: Option<String>,
pub rag_reranker_model: Option<String>, pub rag_reranker_model: Option<String>,
@@ -230,11 +257,15 @@ pub struct Config {
pub rag_chunk_size: Option<usize>, pub rag_chunk_size: Option<usize>,
pub rag_chunk_overlap: Option<usize>, pub rag_chunk_overlap: Option<usize>,
pub rag_template: Option<String>, pub rag_template: Option<String>,
pub rag_extractor_model: Option<String>,
pub rag_extractor_prompt: Option<String>,
pub rag_graph_hops: usize,
#[serde(default)] #[serde(default)]
pub document_loaders: HashMap<String, String>, pub document_loaders: HashMap<String, String>,
pub highlight: bool, pub highlight: bool,
pub raw_markdown: bool,
pub theme: Option<String>, pub theme: Option<String>,
pub left_prompt: Option<String>, pub left_prompt: Option<String>,
pub right_prompt: Option<String>, pub right_prompt: Option<String>,
@@ -280,6 +311,8 @@ impl Default for Config {
max_auto_continues: 10, max_auto_continues: 10,
inject_todo_instructions: true, inject_todo_instructions: true,
continuation_prompt: None, continuation_prompt: None,
inject_skill_instructions: true,
skill_instructions: None,
repl_prelude: None, repl_prelude: None,
cmd_prelude: None, cmd_prelude: None,
@@ -287,8 +320,17 @@ impl Default for Config {
save_session: None, save_session: None,
compression_threshold: 4000, compression_threshold: 4000,
compression_keep_last: 0,
summarization_prompt: None, summarization_prompt: None,
summary_context_prompt: None, summary_context_prompt: None,
max_tool_result_chars: None,
memory: None,
memory_cap_with_tools: None,
memory_cap_without_tools: None,
workspace_instructions: None,
workspace_instructions_files: None,
rag_embedding_model: None, rag_embedding_model: None,
rag_reranker_model: None, rag_reranker_model: None,
@@ -296,10 +338,14 @@ impl Default for Config {
rag_chunk_size: None, rag_chunk_size: None,
rag_chunk_overlap: None, rag_chunk_overlap: None,
rag_template: None, rag_template: None,
rag_extractor_model: None,
rag_extractor_prompt: None,
rag_graph_hops: 1,
document_loaders: Default::default(), document_loaders: Default::default(),
highlight: true, highlight: true,
raw_markdown: false,
theme: None, theme: None,
left_prompt: None, left_prompt: None,
right_prompt: None, right_prompt: None,
@@ -346,6 +392,12 @@ impl AssetCategory {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum MemoryScope {
Global,
Workspace,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum InstallFilter { pub enum InstallFilter {
Agents, Agents,
@@ -413,9 +465,10 @@ fn confirm_asset_overwrite(category: AssetCategory, label: &str, target: &Path)
} }
let body = match category { let body = match category {
AssetCategory::McpConfig => format!( AssetCategory::McpConfig => format!(
"This replaces your MCP server configuration at {} with this \ "This merges the bundled MCP server template into your configuration \
build's bundled template. Your configured MCP servers (and any \ at {}. New servers from the bundled template will be added; any \
custom secret references they contain) will be lost.", MCP servers you have already configured (including custom secret \
references) are left untouched.",
target.display() target.display()
), ),
_ => format!( _ => format!(
@@ -435,7 +488,7 @@ fn confirm_asset_overwrite(category: AssetCategory, label: &str, target: &Path)
pub fn default_sessions_dir() -> PathBuf { pub fn default_sessions_dir() -> PathBuf {
match env::var(get_env_name("sessions_dir")) { match env::var(get_env_name("sessions_dir")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => paths::local_path(SESSIONS_DIR_NAME), Err(_) => paths::local_dir(SESSIONS_DIR_NAME),
} }
} }
@@ -550,6 +603,18 @@ impl Config {
}) })
.with_context(|| "Failed to load config from str")?; .with_context(|| "Failed to load config from str")?;
let mut seen = HashSet::new();
for cc in &config.clients {
let (name, _, _) = oauth::client_config_info(cc);
if !seen.insert(name.to_string()) {
bail!(
"Duplicate client name '{name}' in config.yaml. \
Client names must be unique across all `clients[]` entries \
to avoid OAuth token collisions."
);
}
}
Ok(config) Ok(config)
} }
@@ -642,6 +707,9 @@ bitflags::bitflags! {
const SESSION = 1 << 2; const SESSION = 1 << 2;
const RAG = 1 << 3; const RAG = 1 << 3;
const AGENT = 1 << 4; const AGENT = 1 << 4;
const FUNCTION_CALLING = 1 << 5;
const AUTO_CONTINUE = 1 << 6;
const SKILLS_ENABLED = 1 << 7;
} }
} }
+496 -22
View File
@@ -2,10 +2,14 @@ use super::role::Role;
use super::{ use super::{
AGENT_GRAPH_FILE_NAME, AGENTS_DIR_NAME, BASH_PROMPT_UTILS_FILE_NAME, CONFIG_FILE_NAME, AGENT_GRAPH_FILE_NAME, AGENTS_DIR_NAME, BASH_PROMPT_UTILS_FILE_NAME, CONFIG_FILE_NAME,
ENV_FILE_NAME, FUNCTIONS_BIN_DIR_NAME, FUNCTIONS_DIR_NAME, GLOBAL_TOOLS_DIR_NAME, ENV_FILE_NAME, FUNCTIONS_BIN_DIR_NAME, FUNCTIONS_DIR_NAME, GLOBAL_TOOLS_DIR_NAME,
GLOBAL_TOOLS_UTILS_DIR_NAME, MACROS_DIR_NAME, MCP_FILE_NAME, ModelsOverride, RAGS_DIR_NAME, GLOBAL_TOOLS_UTILS_DIR_NAME, HIDDEN_MCP_FILE_NAME, MACROS_DIR_NAME, MCP_FILE_NAME,
ROLES_DIR_NAME, SKILLS_DIR_NAME, MEMORY_DIR_NAME, MEMORY_INDEX_FILE_NAME, ModelsOverride, RAGS_DIR_NAME, ROLES_DIR_NAME,
SBX_KIT_DIR_NAME, SBX_KIT_HASH_FILE, SBX_MIXIN_FILE_NAME, SBX_MIXIN_KITS_DIR_NAME,
SBX_VAULT_MIXINS_DIR_NAME, SKILLS_DIR_NAME, WORKSPACE_COYOTE_DIR_NAME,
}; };
use crate::client::ProviderModels; use crate::client::ProviderModels;
use crate::config::REPL_HISTORY_DIR_NAME;
use crate::config::session::Session;
use crate::utils::{get_env_name, list_file_names, normalize_env_name}; use crate::utils::{get_env_name, list_file_names, normalize_env_name};
use anyhow::{Context, Result, anyhow, bail}; use anyhow::{Context, Result, anyhow, bail};
@@ -13,7 +17,7 @@ use log::LevelFilter;
use std::collections::HashSet; use std::collections::HashSet;
use std::env; use std::env;
use std::fs::{read_dir, read_to_string}; use std::fs::{read_dir, read_to_string};
use std::path::PathBuf; use std::path::{Path, PathBuf};
pub fn config_dir() -> PathBuf { pub fn config_dir() -> PathBuf {
if let Ok(v) = env::var(get_env_name("config_dir")) { if let Ok(v) = env::var(get_env_name("config_dir")) {
@@ -26,38 +30,147 @@ pub fn config_dir() -> PathBuf {
} }
} }
pub fn local_path(name: &str) -> PathBuf { pub fn local_dir(name: &str) -> PathBuf {
config_dir().join(name) config_dir().join(name)
} }
pub fn cache_path() -> PathBuf { pub fn cache_dir() -> PathBuf {
if let Ok(v) = env::var(get_env_name("cache_dir")) {
PathBuf::from(v)
} else if let Ok(v) = env::var("XDG_CACHE_HOME") {
PathBuf::from(v).join(env!("CARGO_CRATE_NAME"))
} else {
let base_dir = dirs::cache_dir().unwrap_or_else(env::temp_dir); let base_dir = dirs::cache_dir().unwrap_or_else(env::temp_dir);
base_dir.join(env!("CARGO_CRATE_NAME")) base_dir.join(env!("CARGO_CRATE_NAME"))
}
} }
pub fn oauth_tokens_path() -> PathBuf { pub fn sandbox_kit_override() -> Option<PathBuf> {
cache_path().join("oauth") env::var_os(get_env_name("sandbox_kit")).map(PathBuf::from)
}
pub fn translate_sandboxed_home_dir(path: &Path) -> Option<PathBuf> {
env::var_os("IS_SANDBOX")?;
let s = path.to_str()?;
if let Some(translated) = translate_unix_home_style(s, "/home/") {
return Some(translated);
}
if let Some(translated) = translate_unix_home_style(s, "/Users/") {
return Some(translated);
}
translate_windows_users_dir(s)
}
fn translate_unix_home_style(s: &str, prefix: &str) -> Option<PathBuf> {
let rest = s.strip_prefix(prefix)?;
let (user, tail) = match rest.split_once('/') {
Some((u, t)) => (u, t),
None => (rest, ""),
};
if user.is_empty() || user == "agent" {
return None;
}
Some(if tail.is_empty() {
PathBuf::from("/home/agent")
} else {
PathBuf::from(format!("/home/agent/{tail}"))
})
}
fn translate_windows_users_dir(s: &str) -> Option<PathBuf> {
let bytes = s.as_bytes();
if bytes.len() < 4 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' || bytes[2] != b'\\' {
return None;
}
let after_drive = &s[3..];
let rest = after_drive.strip_prefix("Users\\")?;
let (user, tail) = match rest.split_once('\\') {
Some((u, t)) => (u, t.replace('\\', "/")),
None => (rest, String::new()),
};
if user.is_empty() || user == "agent" {
return None;
}
Some(if tail.is_empty() {
PathBuf::from("/home/agent")
} else {
PathBuf::from(format!("/home/agent/{tail}"))
})
}
pub fn sbx_mixin_file() -> PathBuf {
config_dir().join(SBX_MIXIN_FILE_NAME)
}
pub fn global_tools_sbx_mixin_file() -> PathBuf {
functions_dir().join(SBX_MIXIN_FILE_NAME)
}
pub fn find_workspace_sbx_mixin(start: &Path) -> Option<PathBuf> {
for dir in start.ancestors() {
let candidate = dir
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(SBX_MIXIN_FILE_NAME);
if candidate.exists() {
return Some(candidate);
}
}
None
}
pub fn oauth_tokens_dir() -> PathBuf {
cache_dir().join("oauth")
} }
pub fn token_file(client_name: &str) -> PathBuf { pub fn token_file(client_name: &str) -> PathBuf {
oauth_tokens_path().join(format!("{client_name}_oauth_tokens.json")) oauth_tokens_dir().join(format!("{client_name}_oauth_tokens.json"))
} }
pub fn log_path() -> PathBuf { pub fn log_file() -> PathBuf {
cache_path().join(format!("{}.log", env!("CARGO_CRATE_NAME"))) cache_dir().join(format!("{}.log", env!("CARGO_CRATE_NAME")))
}
pub fn sbx_kit_dir() -> PathBuf {
cache_dir().join(SBX_KIT_DIR_NAME)
}
pub fn sbx_kit_hash_file() -> PathBuf {
sbx_kit_dir().join(SBX_KIT_HASH_FILE)
}
pub fn sbx_vault_mixins_dir() -> PathBuf {
cache_dir().join(SBX_VAULT_MIXINS_DIR_NAME)
}
pub fn sbx_vault_mixins_hash_file() -> PathBuf {
sbx_vault_mixins_dir().join(SBX_KIT_HASH_FILE)
}
pub fn sbx_mixin_kits_dir() -> PathBuf {
cache_dir().join(SBX_MIXIN_KITS_DIR_NAME)
} }
pub fn config_file() -> PathBuf { pub fn config_file() -> PathBuf {
match env::var(get_env_name("config_file")) { match env::var(get_env_name("config_file")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(CONFIG_FILE_NAME), Err(_) => local_dir(CONFIG_FILE_NAME),
} }
} }
pub fn roles_dir() -> PathBuf { pub fn roles_dir() -> PathBuf {
match env::var(get_env_name("roles_dir")) { match env::var(get_env_name("roles_dir")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(ROLES_DIR_NAME), Err(_) => local_dir(ROLES_DIR_NAME),
} }
} }
@@ -68,7 +181,7 @@ pub fn role_file(name: &str) -> PathBuf {
pub fn skills_dir() -> PathBuf { pub fn skills_dir() -> PathBuf {
match env::var(get_env_name("skills_dir")) { match env::var(get_env_name("skills_dir")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(SKILLS_DIR_NAME), Err(_) => local_dir(SKILLS_DIR_NAME),
} }
} }
@@ -80,6 +193,40 @@ pub fn skill_file(name: &str) -> PathBuf {
skill_dir(name).join("SKILL.md") skill_dir(name).join("SKILL.md")
} }
pub fn workspace_config_dir() -> PathBuf {
let workspace_dir_name = match env::var(get_env_name("workspace_config_dir")) {
Ok(value) => value,
Err(_) => WORKSPACE_COYOTE_DIR_NAME.to_string(),
};
env::current_dir()
.unwrap_or_default()
.join(workspace_dir_name)
}
pub fn workspace_skills_dir() -> PathBuf {
workspace_config_dir().join(SKILLS_DIR_NAME)
}
pub fn workspace_skill_file(name: &str) -> PathBuf {
workspace_skills_dir().join(name).join("SKILL.md")
}
pub fn workspace_mcp_config_file() -> Option<PathBuf> {
workspace_mcp_config_file_in(&env::current_dir().unwrap_or_default())
}
fn workspace_mcp_config_file_in(workspace_root: &Path) -> Option<PathBuf> {
let dir = workspace_config_dir();
[
dir.join(MCP_FILE_NAME),
dir.join(HIDDEN_MCP_FILE_NAME),
workspace_root.join(HIDDEN_MCP_FILE_NAME),
]
.into_iter()
.find(|candidate| candidate.is_file())
}
pub fn validate_skill_name(name: &str) -> Result<()> { pub fn validate_skill_name(name: &str) -> Result<()> {
if name.is_empty() { if name.is_empty() {
bail!("Skill name cannot be empty"); bail!("Skill name cannot be empty");
@@ -96,7 +243,7 @@ pub fn validate_skill_name(name: &str) -> Result<()> {
pub fn macros_dir() -> PathBuf { pub fn macros_dir() -> PathBuf {
match env::var(get_env_name("macros_dir")) { match env::var(get_env_name("macros_dir")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(MACROS_DIR_NAME), Err(_) => local_dir(MACROS_DIR_NAME),
} }
} }
@@ -107,21 +254,21 @@ pub fn macro_file(name: &str) -> PathBuf {
pub fn env_file() -> PathBuf { pub fn env_file() -> PathBuf {
match env::var(get_env_name("env_file")) { match env::var(get_env_name("env_file")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(ENV_FILE_NAME), Err(_) => local_dir(ENV_FILE_NAME),
} }
} }
pub fn rags_dir() -> PathBuf { pub fn rags_dir() -> PathBuf {
match env::var(get_env_name("rags_dir")) { match env::var(get_env_name("rags_dir")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(RAGS_DIR_NAME), Err(_) => local_dir(RAGS_DIR_NAME),
} }
} }
pub fn functions_dir() -> PathBuf { pub fn functions_dir() -> PathBuf {
match env::var(get_env_name("functions_dir")) { match env::var(get_env_name("functions_dir")) {
Ok(value) => PathBuf::from(value), Ok(value) => PathBuf::from(value),
Err(_) => local_path(FUNCTIONS_DIR_NAME), Err(_) => local_dir(FUNCTIONS_DIR_NAME),
} }
} }
@@ -146,7 +293,7 @@ pub fn bash_prompt_utils_file() -> PathBuf {
} }
pub fn agents_data_dir() -> PathBuf { pub fn agents_data_dir() -> PathBuf {
local_path(AGENTS_DIR_NAME) local_dir(AGENTS_DIR_NAME)
} }
pub fn agent_data_dir(name: &str) -> PathBuf { pub fn agent_data_dir(name: &str) -> PathBuf {
@@ -192,7 +339,39 @@ pub fn agent_functions_file(name: &str) -> Result<PathBuf> {
} }
pub fn models_override_file() -> PathBuf { pub fn models_override_file() -> PathBuf {
local_path("models-override.yaml") local_dir("models-override.yaml")
}
pub fn global_memory_dir() -> PathBuf {
config_dir().join(MEMORY_DIR_NAME)
}
pub fn global_memory_index_file() -> PathBuf {
global_memory_dir().join(MEMORY_INDEX_FILE_NAME)
}
pub fn workspace_memory_dir_for(workspace_root: &Path) -> PathBuf {
workspace_root
.join(WORKSPACE_COYOTE_DIR_NAME)
.join(MEMORY_DIR_NAME)
}
pub fn workspace_memory_index_file_for(workspace_root: &Path) -> PathBuf {
workspace_memory_dir_for(workspace_root).join(MEMORY_INDEX_FILE_NAME)
}
pub fn repl_history_dir() -> PathBuf {
cache_dir().join(REPL_HISTORY_DIR_NAME)
}
pub fn repl_history_file(session: &Option<Session>) -> PathBuf {
let history_key = if let Some(session) = &session {
format!("session_{}", session.name().replace('/', "_"))
} else {
"default".to_string()
};
repl_history_dir().join(history_key)
} }
pub fn log_config() -> Result<(LevelFilter, Option<PathBuf>)> { pub fn log_config() -> Result<(LevelFilter, Option<PathBuf>)> {
@@ -205,7 +384,7 @@ pub fn log_config() -> Result<(LevelFilter, Option<PathBuf>)> {
}); });
let resolved_log_path = match env::var(get_env_name("log_path")) { let resolved_log_path = match env::var(get_env_name("log_path")) {
Ok(v) => Some(PathBuf::from(v)), Ok(v) => Some(PathBuf::from(v)),
Err(_) => Some(log_path()), Err(_) => Some(log_file()),
}; };
Ok((log_level, resolved_log_path)) Ok((log_level, resolved_log_path))
} }
@@ -264,25 +443,31 @@ pub fn has_macro(name: &str) -> bool {
pub fn list_skills() -> Vec<String> { pub fn list_skills() -> Vec<String> {
let mut names = Vec::new(); let mut names = Vec::new();
if let Ok(rd) = read_dir(skills_dir()) { let mut seen = HashSet::new();
for dir in [workspace_skills_dir(), skills_dir()] {
if let Ok(rd) = read_dir(dir) {
for entry in rd.flatten() { for entry in rd.flatten() {
if let Ok(file_type) = entry.file_type() if let Ok(file_type) = entry.file_type()
&& file_type.is_dir() && file_type.is_dir()
&& let Some(name) = entry.file_name().to_str() && let Some(name) = entry.file_name().to_str()
&& !seen.contains(name)
&& entry.path().join("SKILL.md").is_file() && entry.path().join("SKILL.md").is_file()
&& validate_skill_name(name).is_ok() && validate_skill_name(name).is_ok()
{ {
seen.insert(name.to_string());
names.push(name.to_string()); names.push(name.to_string());
} }
} }
} }
}
names.sort_unstable(); names.sort_unstable();
names names
} }
pub fn has_skill(name: &str) -> bool { pub fn has_skill(name: &str) -> bool {
skill_file(name).is_file() workspace_skill_file(name).is_file() || skill_file(name).is_file()
} }
pub fn local_models_override() -> Result<Vec<ProviderModels>> { pub fn local_models_override() -> Result<Vec<ProviderModels>> {
@@ -350,6 +535,295 @@ mod tests {
} }
} }
mod sandbox_home_translation {
use super::*;
use serial_test::serial;
fn with_sandbox<F: FnOnce()>(f: F) {
let prev = env::var_os("IS_SANDBOX");
unsafe {
env::set_var("IS_SANDBOX", "1");
}
f();
unsafe {
match prev {
Some(v) => env::set_var("IS_SANDBOX", v),
None => env::remove_var("IS_SANDBOX"),
}
}
}
fn without_sandbox<F: FnOnce()>(f: F) {
let prev = env::var_os("IS_SANDBOX");
unsafe {
env::remove_var("IS_SANDBOX");
}
f();
unsafe {
if let Some(v) = prev {
env::set_var("IS_SANDBOX", v);
}
}
}
#[test]
#[serial]
fn returns_none_when_not_in_sandbox() {
without_sandbox(|| {
let p = Path::new("/home/atusa/.coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
#[test]
#[serial]
fn translates_host_home_to_agent_home() {
with_sandbox(|| {
let p = Path::new("/home/atusa/.coyote_password");
assert_eq!(
translate_sandboxed_home_dir(p),
Some(PathBuf::from("/home/agent/.coyote_password"))
);
});
}
#[test]
#[serial]
fn translates_nested_host_home_dir() {
with_sandbox(|| {
let p = Path::new("/home/atusa/.config/coyote/.password");
assert_eq!(
translate_sandboxed_home_dir(p),
Some(PathBuf::from("/home/agent/.config/coyote/.password"))
);
});
}
#[test]
#[serial]
fn returns_none_when_path_already_targets_agent_home() {
with_sandbox(|| {
let p = Path::new("/home/agent/.coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
#[test]
#[serial]
fn returns_none_when_path_is_outside_home() {
with_sandbox(|| {
let p = Path::new("/etc/coyote/.coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
#[test]
#[serial]
fn returns_none_for_relative_path() {
with_sandbox(|| {
let p = Path::new(".coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
#[test]
#[serial]
fn returns_none_for_first_segment_not_home() {
with_sandbox(|| {
let p = Path::new("/opt/atusa/.coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
#[test]
#[serial]
fn translates_macos_users_dir() {
with_sandbox(|| {
let p = Path::new("/Users/atusa/.coyote_password");
assert_eq!(
translate_sandboxed_home_dir(p),
Some(PathBuf::from("/home/agent/.coyote_password"))
);
});
}
#[test]
#[serial]
fn translates_macos_nested_dir() {
with_sandbox(|| {
let p = Path::new("/Users/atusa/.config/coyote/.password");
assert_eq!(
translate_sandboxed_home_dir(p),
Some(PathBuf::from("/home/agent/.config/coyote/.password"))
);
});
}
#[test]
#[serial]
fn returns_none_when_macos_dir_already_targets_agent() {
with_sandbox(|| {
let p = Path::new("/Users/agent/.coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
#[test]
#[serial]
fn translates_windows_drive_letter_path() {
with_sandbox(|| {
let p = Path::new("C:\\Users\\atusa\\.coyote_password");
assert_eq!(
translate_sandboxed_home_dir(p),
Some(PathBuf::from("/home/agent/.coyote_password"))
);
});
}
#[test]
#[serial]
fn translates_windows_nested_path() {
with_sandbox(|| {
let p = Path::new("D:\\Users\\atusa\\.config\\coyote\\.password");
assert_eq!(
translate_sandboxed_home_dir(p),
Some(PathBuf::from("/home/agent/.config/coyote/.password"))
);
});
}
#[test]
#[serial]
fn returns_none_when_windows_path_already_targets_agent() {
with_sandbox(|| {
let p = Path::new("C:\\Users\\agent\\.coyote_password");
assert_eq!(translate_sandboxed_home_dir(p), None);
});
}
}
mod workspace_mcp_resolution {
use super::*;
use serial_test::serial;
fn with_workspace_dir<F: FnOnce(&Path, &Path)>(f: F) {
let unique = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = env::temp_dir().join(format!("coyote-workspace-mcp-test-{unique}"));
let ws_dir = root.join(WORKSPACE_COYOTE_DIR_NAME);
fs::create_dir_all(&ws_dir).unwrap();
let env_name = get_env_name("workspace_config_dir");
let prev = env::var_os(&env_name);
unsafe {
env::set_var(&env_name, &ws_dir);
}
f(&root, &ws_dir);
unsafe {
match prev {
Some(v) => env::set_var(&env_name, v),
None => env::remove_var(&env_name),
}
}
let _ = fs::remove_dir_all(&root);
}
#[test]
#[serial]
fn returns_none_when_no_config_exists() {
with_workspace_dir(|root, _| {
assert_eq!(workspace_mcp_config_file_in(root), None);
});
}
#[test]
#[serial]
fn finds_mcp_json() {
with_workspace_dir(|root, ws_dir| {
fs::write(ws_dir.join("mcp.json"), "{}").unwrap();
assert_eq!(
workspace_mcp_config_file_in(root),
Some(ws_dir.join("mcp.json"))
);
});
}
#[test]
#[serial]
fn falls_back_to_claude_style_hidden_mcp_json() {
with_workspace_dir(|root, ws_dir| {
fs::write(ws_dir.join(".mcp.json"), "{}").unwrap();
assert_eq!(
workspace_mcp_config_file_in(root),
Some(ws_dir.join(".mcp.json"))
);
});
}
#[test]
#[serial]
fn prefers_mcp_json_when_both_exist() {
with_workspace_dir(|root, ws_dir| {
fs::write(ws_dir.join("mcp.json"), "{}").unwrap();
fs::write(ws_dir.join(".mcp.json"), "{}").unwrap();
assert_eq!(
workspace_mcp_config_file_in(root),
Some(ws_dir.join("mcp.json"))
);
});
}
#[test]
#[serial]
fn falls_back_to_project_root_hidden_mcp_json() {
with_workspace_dir(|root, _| {
fs::write(root.join(".mcp.json"), "{}").unwrap();
assert_eq!(
workspace_mcp_config_file_in(root),
Some(root.join(".mcp.json"))
);
});
}
#[test]
#[serial]
fn prefers_workspace_dir_config_over_project_root() {
with_workspace_dir(|root, ws_dir| {
fs::write(ws_dir.join(".mcp.json"), "{}").unwrap();
fs::write(root.join(".mcp.json"), "{}").unwrap();
assert_eq!(
workspace_mcp_config_file_in(root),
Some(ws_dir.join(".mcp.json"))
);
});
}
}
#[test]
fn sandbox_kit_override_reflects_env_var_state() {
let env_name = get_env_name("sandbox_kit");
let prev = env::var_os(&env_name);
unsafe {
env::remove_var(&env_name);
}
assert_eq!(sandbox_kit_override(), None);
let probe = PathBuf::from("/tmp/coyote-sandbox-kit-probe");
unsafe {
env::set_var(&env_name, &probe);
}
assert_eq!(sandbox_kit_override(), Some(probe));
unsafe {
match prev {
Some(v) => env::set_var(&env_name, v),
None => env::remove_var(&env_name),
}
}
}
#[test] #[test]
fn list_skills_skips_invalid_directory_names() { fn list_skills_skips_invalid_directory_names() {
let unique = time::SystemTime::now() let unique = time::SystemTime::now()
+88 -2
View File
@@ -1,5 +1,60 @@
use indoc::indoc; use indoc::indoc;
pub(crate) const DEFAULT_SKILL_INSTRUCTIONS: &str = indoc! {"
## Skills
Specialized skills may be available in this context. Call `skill__list` early in a task to
discover any that match the work, then `skill__load` the relevant ones. Their instructions and
granted tools will become active for subsequent turns. Call `skill__unload` when their work is
complete to keep the context lean."
};
pub(crate) const DEFAULT_MEMORY_INSTRUCTIONS: &str = indoc! {"
## Memory
A persistent memory file system survives across sessions. The MEMORY.md content shown above is
your always-on context (universal facts, hard rules, binding feedback). Drill files hold deeper,
on-demand context that you fetch with `memory__read`.
Tools:
- `memory__read(name)`: Read a specific drill file's full content.
- `memory__write(name, content, scope)`: Create or replace a drill file (scope: 'global' | 'workspace').
The MEMORY.md index is appended automatically; do not also update the index by hand.
Optional `superseded_by` / `expires` (YYYY-MM-DD) mark a memory as stale for later cleanup.
- `memory__rename(name, new_name, scope)`: Rename a drill file. Its index entry and every
[[wikilink]] to it are rewritten automatically.
- `memory__delete(name, scope)`: Delete a drill file and its index entry. Reports any
[[wikilinks]] left dangling in other files.
- `memory__edit_index(scope, content)`: Replace the entire MEMORY.md at the given scope.
Use this to add always-on facts, reorganize, prune stale entries, or fix descriptions.
- `memory__list()`: See all known drill files and their metadata.
- `memory__lint()`: Health-check memory for orphans, broken links, oversized files,
stale (superseded/expired) files, and index descriptions that drifted from the files.
RULES:
- Every interaction has two outputs: your answer AND any memory updates the conversation warrants.
Don't let learnings evaporate into chat history.
- All MEMORY.md edits MUST go through `memory__edit_index`. NEVER use `fs_write`, `fs_patch`,
or any other generic file tool on MEMORY.md Coyote manages its location and a stray
MEMORY.md outside the managed path is invisible to memory.
- All drill files MUST go through `memory__write`. The index updates itself. Renames and
deletions MUST go through `memory__rename` / `memory__delete` so links stay intact.
- When a fact becomes outdated, update it in place, delete it, or mark the old file with
`superseded_by`/`expires` so `memory__lint` flags it later. Never leave contradictory
memories side by side.
- Use [[wikilink]] notation in memory files to reference other memories by their `name:` slug.
- NEVER write secrets, credentials, or API keys to memory memory is plaintext on disk.
Use coyote's Vault for secrets.
- Keep individual drill files focused (under ~2K chars). Split large topics across linked files."
};
pub(crate) const DEFAULT_MEMORY_INSTRUCTIONS_READONLY: &str = indoc! {"
## Memory (read-only)
The memory content shown above persists across sessions. In this session it is READ-ONLY the user
maintains memory files manually outside the conversation.
Reference the memory content as authoritative context about the user and their workspace.
Do not propose writing to memory or call any `memory__*` tools they are unavailable."
};
pub(in crate::config) const DEFAULT_TODO_INSTRUCTIONS: &str = indoc! {" pub(in crate::config) const DEFAULT_TODO_INSTRUCTIONS: &str = indoc! {"
## Task Tracking ## Task Tracking
You have built-in task tracking tools. Use them to track your progress: You have built-in task tracking tools. Use them to track your progress:
@@ -29,7 +84,8 @@ pub(in crate::config) const DEFAULT_SPAWN_INSTRUCTIONS: &str = indoc! {"
| `agent__spawn` | Spawn a subagent in the background. Returns an `id` immediately. | | `agent__spawn` | Spawn a subagent in the background. Returns an `id` immediately. |
| `agent__check` | Non-blocking check: is the agent done yet? Returns PENDING or result. | | `agent__check` | Non-blocking check: is the agent done yet? Returns PENDING or result. |
| `agent__collect` | Blocking wait: wait for an agent to finish, return its output. | | `agent__collect` | Blocking wait: wait for an agent to finish, return its output. |
| `agent__list` | List all spawned agents and their status. | | `agent__list_available` | List all agent types you can spawn (name + description). Use this to discover specialists before calling `agent__spawn`. |
| `agent__list_running` | List all subagents YOU have spawned, with their status. |
| `agent__cancel` | Cancel a running agent by ID. | | `agent__cancel` | Cancel a running agent by ID. |
| `agent__task_create` | Create a task in the dependency-aware task queue. | | `agent__task_create` | Create a task in the dependency-aware task queue. |
| `agent__task_list` | List all tasks and their status/dependencies. | | `agent__task_list` | List all tasks and their status/dependencies. |
@@ -54,6 +110,36 @@ pub(in crate::config) const DEFAULT_SPAWN_INSTRUCTIONS: &str = indoc! {"
agent__collect --id agent_explore_e5f6g7h8 agent__collect --id agent_explore_e5f6g7h8
``` ```
### CRITICAL: Never end your turn with pending agents
Spawned agents do NOT report back on their own. They run in the background until you
actively reclaim them with `agent__collect` (to get their output) or `agent__cancel`
(to discard them). If you spawn agents and then emit a final message without reclaiming
them, the system will detect the unreclaimed agents and reject the turn-end, injecting
a reminder forcing you to handle them. After several such reminders, the system will
auto-cancel them and warn you that work was lost.
The correct flow when you have nothing else to do:
```
# WRONG - do NOT do this:
agent__spawn --agent explore --prompt \"...\"
agent__spawn --agent explore --prompt \"...\"
# ... emit text like \"I will synthesize once they report back.\" and stop
# ^ The agents will be abandoned. Their output will be lost.
# RIGHT - always do this:
agent__spawn --agent explore --prompt \"...\"
agent__spawn --agent explore --prompt \"...\"
agent__collect --id <first_id> # blocks until done
agent__collect --id <second_id> # blocks until done
# ... NOW you can synthesize and end your turn
```
`agent__collect` is a **blocking wait**: it pauses your execution until the agent
completes, then returns the output as a tool result. Use it freely it is the
correct primitive for \"I'm done with my own work and just need the agents' results\".
### Parallel Spawning (DEFAULT for multi-agent work) ### Parallel Spawning (DEFAULT for multi-agent work)
When a task needs multiple agents, **spawn them all at once**, then collect: When a task needs multiple agents, **spawn them all at once**, then collect:
@@ -121,7 +207,7 @@ pub(in crate::config) const DEFAULT_USER_INTERACTION_INSTRUCTIONS: &str = indoc!
## User Interaction ## User Interaction
You have built-in tools to interact with the user directly: You have built-in tools to interact with the user directly:
- `user__ask --question \"...\" --options [\"A\", \"B\", \"C\"]`: Present a selection prompt. Returns the chosen option. - `user__select --question \"...\" --options [\"A\", \"B\", \"C\"]`: Present a single-select list of named options. Use this — not `user__confirm` — whenever there are 2+ named options. Returns the chosen option.
- `user__confirm --question \"...\"`: Ask a yes/no question. Returns \"yes\" or \"no\". - `user__confirm --question \"...\"`: Ask a yes/no question. Returns \"yes\" or \"no\".
- `user__input --question \"...\"`: Request free-form text input from the user. - `user__input --question \"...\"`: Request free-form text input from the user.
- `user__checkbox --question \"...\" --options [\"A\", \"B\", \"C\"]`: Multi-select prompt. Returns an array of selected options. - `user__checkbox --question \"...\" --options [\"A\", \"B\", \"C\"]`: Multi-select prompt. Returns an array of selected options.

Some files were not shown because too many files have changed in this diff Show More