Compare commits

370 Commits
Author SHA1 Message Date
Dark-Alex-17 374e8c0bf7 fix: prevent tmp-overwriting
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Canceled after 0s
CI / All (windows-latest) (push) Canceled after 0s
2026-08-15 19:35:12 -06:00
Dark-Alex-17 ede87df960 fix: Corrected a rare edge case on how tool files are generated during parallel executions 2026-08-15 18:41:13 -06:00
Dark-Alex-17 95a8c3df44 fix: cosmetic fix after improved bash tool handling 2026-08-15 17:31:32 -06:00
Dark-Alex-17 f57bd21ee4 fix: Improved subagent escalation handling 2026-08-14 16:53:37 -06:00
Dark-Alex-17 e1b6e3f8c6 fix: latent parsing bugs in fs_patch and argc 2026-08-14 16:12:41 -06:00
Dark-Alex-17 644d899f78 fix: Prevent infinite hangs in coder agent and implement timeouts for LLM API calls and interactive tools 2026-08-14 15:22:25 -06:00
Dark-Alex-17 2596194417 feat: retry LLM API calls once after 401 by force-refreshing the OAuth token
The Client trait's default chat_completions, chat_completions_streaming,
and embeddings methods now classify failures via ApiStatusError: on a
401 with a cached OAuth token, the token is distrusted (identity-aware
marker) and the call retried exactly once — the retry's prepare step
sees the marker and force-refreshes. Streaming retries only while the
SSE handler has received no content, preventing duplicate rendering.
A second 401 propagates the original error; other retry errors
propagate as-is. API-key clients never retry. No backoff by design:
cost is bounded to one refresh + one retry per failing request.
2026-08-14 13:17:56 -06:00
Dark-Alex-17 684f19250a feat: identity-aware rejected-token marker for LLM OAuth cache
distrust_access_token compare-and-invalidates the in-memory entry only
when the cached token equals the rejected one, so a concurrent refresh
is never clobbered. is_valid_access_token and both expiry checks in
prepare_oauth_access_token treat marked tokens as expired, forcing a
refresh of provider-rejected tokens that are still locally unexpired.
The marker is cleared after every completed refresh, including ones
that return the same token.
2026-08-14 13:07:51 -06:00
Dark-Alex-17 f3d59ade11 feat: typed ApiStatusError carrying HTTP status through LLM client errors
catch_error and sse_stream now bail with ApiStatusError{status, message}
instead of bare anyhow strings, preserving every existing Display output
byte-for-byte. Enables structural status classification (e.g. 401
detection) via downcast through anyhow context chains.
2026-08-14 13:01:08 -06:00
Dark-Alex-17 e1604c58ea feat: per-request OAuth token injection with mid-session refresh for HTTP MCP servers
Replace the spawn-time static Authorization header for OAuth-managed HTTP
MCP servers with McpOAuthClient, a custom implementation of rmcp's
StreamableHttpClient trait that resolves the bearer token on every
request via load_or_refresh_mcp_token. Tokens that expire mid-session
now refresh transparently instead of failing tool calls until restart.

On a 401 for an injected token, the wrapper force-refreshes (identity-
aware: a still-unexpired copy of the rejected token is not trusted) and
retries exactly once, matching Claude Code / official SDK semantics.
Both *_with_max_sse_event_size trait methods are overridden to preserve
the inner client's SSE size enforcement, and the inner reqwest client
mirrors rmcp's default (pool_max_idle_per_host(0), no redirects).

SSE, stdio, and static-header HTTP paths are unchanged; startup
warning semantics (McpAuthRequired reasons) are preserved. Verified
live: mid-session backdated token refreshed transparently during an
active atlassian session.
2026-08-14 12:33:46 -06:00
Dark-Alex-17 dcacb3a962 chore: upgrade rmcp 1.8.0 -> 3.1.2
Compile-clean upgrade verified: zero source changes needed, full test
suite green, clippy clean. Coyote's rmcp API surface (14 items) dodges
all 2.0/3.0 breaking changes; the "Auth required" error string matched
by is_auth_required_error is intact in 3.1.2.
2026-08-14 11:10:45 -06:00
Dark-Alex-17 d791098e51 feat: reason-specific warnings for MCP servers that fail OAuth at startup
Distinguish why an OAuth MCP server was not started: never authenticated
(no stored credentials), stored token expired and refresh failed, or the
server rejected a token that looked valid. McpTokenStatus replaces the
Option<String> return of load_or_refresh_mcp_token, and McpAuthRequired
carries the reason across the error boundary via anyhow context.
2026-08-14 11:07:56 -06:00
Dark-Alex-17 d31110cd67 fix: allow nested italics inside bold spans in markdown renderer
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-13 16:18:50 -06:00
Dark-Alex-17 0f35e03a85 fix: properly handle OAuth refreshes
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-13 16:00:42 -06:00
Dark-Alex-17 c2b0c120d7 chore: Added grok4.6 to models.yaml
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-13 14:20:35 -06:00
Dark-Alex-17 65c9be36b2 fix: correct newline removal from fs_write and fs_patch 2026-08-13 14:18:45 -06:00
Dark-Alex-17 2658ca776e feat: Installed duckdb into the coyote image
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-12 19:29:26 -06:00
Dark-Alex-17 f8682102a0 docs: Added duckdb prerequisite
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-12 19:07:31 -06:00
Dark-Alex-17 3fa0f5c428 feat: Support managing MCP servers from the CLI directly
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-12 17:55:33 -06:00
Dark-Alex-17 68135b97d1 feat: append new built-in rag__query function to RAG contexts to allow further querying by LLMs
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-12 16:25:50 -06:00
Dark-Alex-17 b87a3460c4 fix: detect duplicate tool call IDs client-side before sending to Claude
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-12 13:33:24 -06:00
Dark-Alex-17 cb23da6490 feat: support static file bundling with sbx-mixins
CI / All (ubuntu-latest) (push) Failing after 29s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
2026-08-12 13:18:38 -06:00
Alex Clarke 2a40a5a81d Merge pull request #14 from Dark-Alex-17/feat/rag-driver-abstraction-v3
CI / All (ubuntu-latest) (push) Failing after 31s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
feat(rag): pluggable RagProvider abstraction with DuckDB and Qdrant drivers
2026-08-12 12:45:12 -06:00
Dark-Alex-17 ebba976a27 fmt: applied formatting 2026-08-12 12:07:38 -06:00
Dark-Alex-17 c84f9522e9 feat(rag): offer the storage driver when an agent initializes its RAG
Agent startup and graph rag nodes both run an interactive wizard when their
knowledge base has not been built, but neither offered the driver choice that
interactive named-RAG creation has, so both silently produced a yaml store.

A plain agent was the worse of the two: AgentConfig carries only documents, so
there was no way to get a duckdb RAG for one, interactively or declaratively. A
graph node could at least declare driver: in the workflow.

Agent startup now passes prompt_for_driver, and a rag node whose wizard runs is
asked too. The prompt is skipped when the node already declares a driver, and
sits inside the not-fully-specified branch after the non-interactive bail, so
declarative workflows and headless runs are unchanged. Temp RAGs still pass
false: they are deleted on the next run, so a persistent store would only leave
a sidecar behind.

The prompt moves to select_rag_driver rather than being duplicated.
2026-08-12 12:02:15 -06:00
Dark-Alex-17 81ed769f8a fix(rag): warn when a duckdb store is empty but files are indexed
A duckdb RAG is two files. The .yaml deliberately carries no vectors, and
open() runs CREATE TABLE IF NOT EXISTS, so a .yaml copied or synced without its
.duckdb sidecar produces a fresh empty store, hydrates to nothing, and answers
every query with nothing while .info rag still lists every indexed file.

Neither existing guard catches it: the anti-wipe check in rebuild_indexes needs
existing > 0, and the mandatory ? on hydration needs a genuine error, while an
absent store is the same Ok(empty) as a RAG with nothing indexed yet.

Warn rather than bail, so a store deleted on purpose still loads and can be
rebuilt.
2026-08-12 11:26:16 -06:00
Dark-Alex-17 6f7defe25f style: removed redundant comment 2026-08-12 10:56:34 -06:00
Dark-Alex-17 b837f82d7e fix(rag): keep a local Qdrant off an ambient proxy
Reverts the global proxy rework in 54685be and narrows it to the provider.

That commit took over proxy detection for every client in order to exempt
loopback and private ranges. Too broad: reqwest's detection also reads macOS
System Settings and the Windows registry behind its system-proxy feature, which
sits in its default set. Coyote disables default features today, so hand-rolling
the environment lookup happened to match — but re-enabling defaults later would
silently restore that support for main and not for the hand-rolled version. It
also made an explicitly configured proxy skip local hosts, which nobody asked
for: a proxy named for a LAN endpoint should be used.

build_client and utils are byte-identical to main again. The bypass now lives in
QdrantProvider::make_client, which is the only place that knows the target host,
and applies solely when that host is loopback, link-local, private or .local. A
public or cloud-hosted store keeps whatever the environment configures.

Also drops apply_proxy: with build_client reverted there was one caller left, and
set_proxy already covers it.

Both #[ignore]d live tests still pass against a Qdrant on loopback while an
ambient proxy that rejects it is in force.
2026-08-12 10:52:31 -06:00
Dark-Alex-17 54685be9a2 fix: keep loopback and LAN traffic off an ambient proxy
Pre-existing on main, not introduced by the driver work, but it makes a local
RAG backend unusable so it belongs with this change.

build_client only called set_proxy when a client had configured one of its own.
With nothing configured, reqwest's own detection applied, which sends every
request through a *_PROXY variable including ones bound for 127.0.0.1 or a LAN
address. A proxy cannot usefully forward those, and anything that intercepts
proxied traffic answers on behalf of a service that is running perfectly well,
so the error names the proxy rather than the store and reads as a Coyote fault.

Concretely, an installed Socket Firewall exports HTTP_PROXY to the processes it
wraps and rejects hosts outside its allow list. That turned a healthy Ollama on
the LAN into 'error decoding response body: expected value at line 2 column 1' —
its HTML refusal page parsed as JSON — and a loopback Qdrant into an HTTP 405.

Proxy handling is now always applied and always exempts loopback and private
ranges, with NO_PROXY merged in since replacing reqwest's detection also
replaces its handling of that variable. HTTP_PROXY and HTTPS_PROXY are kept
separate because they are allowed to differ. An explicitly configured proxy
still wins, and '-' still means none.

This also supersedes the unconditional no_proxy() added to the Qdrant client in
af9622d: that made it the only client to ignore a proxy outright, on a
justification I got wrong. It now shares this path, so a remote store behind a
real proxy keeps working.
2026-08-12 10:33:03 -06:00
Dark-Alex-17 4dd6e794b2 docs: removed redundant comment 2026-08-11 22:19:14 -06:00
Dark-Alex-17 af9622d31c fix(rag): stop routing Qdrant requests through an ambient proxy
make_client used a bare reqwest builder, which honours whatever proxy the
environment advertises. That made it the only HTTP client in Coyote to do so:
utils::set_proxy discards ambient settings and applies only Coyote's configured
proxy, and every other client goes through it.

The symptom is that a perfectly healthy Qdrant is unreachable and the error
belongs to the interposing proxy, not the store, so it reads as a Coyote or
Qdrant fault. Locally an installed Socket Firewall answered `.rag attach`
against 127.0.0.1:6333 with an HTML 'Connection Required' page and HTTP 405.

Both #[ignore]d live tests now pass against a real Qdrant; they failed with that
same 405 before this change, which is the first time either has run green.

A remote store that genuinely needs Coyote's configured proxy is a follow-up:
that means threading the proxy config into the provider.
2026-08-11 22:15:04 -06:00
Dark-Alex-17 6f586bd535 style: cleanup 2026-08-11 22:07:35 -06:00
Dark-Alex-17 78740db170 chore: ignore the .coyote workspace directory
It holds generated workspace state and should never be committed.
2026-08-11 22:03:45 -06:00
Dark-Alex-17 64d594f4ee refactor(rag): discover driver_config secrets by grammar, not field name
Sandbox provisioning only ever looked at driver_config["api_key"], so a driver
whose credential is called anything else would have been silently unprovisioned
inside a sandbox. It now scans every driver_config value and treats any that is
a secret placeholder as a credential, which is the same rule resolve_driver_config
already used at point of use.

The first one binds to the RAG's own service id, which is what the generated
mixin declares; any others register under their own names, as MCP secrets do.
The mixin still carries a single credential entry, so a driver needing two bound
secrets remains a follow-up.

Also drops the placeholder parser added in 74bc613. crate::vault::SECRET_RE is
already the canonical definition and was already imported here, so that was a
third implementation of the same grammar. Requiring the whole value to match is
what keeps a literal key from being read as a secret name and printed.

The api_key check is gone from RagData::validate: a generic config validator
should not know a provider's field names.
2026-08-11 22:03:45 -06:00
Dark-Alex-17 1322d73c7b style: further cleanup 2026-08-11 21:50:46 -06:00
Dark-Alex-17 de91ffa517 fix(rag): treat a zero min_score as no floor on Qdrant searches
parse_search_hits filtered on score > min_score, and the only caller passes
0.0. Qdrant Euclid collections score by negative distance, so every hit was
dropped and an attached Euclid collection returned nothing at all, silently.

This is the same trap the surrounding code already documents: score_threshold
is deliberately not sent because it is metric-aware and a 0.0 floor filters
everything out on Euclid. The local filter then reproduced it exactly. Only a
positive floor is now treated as a floor.
2026-08-11 21:07:20 -06:00
Dark-Alex-17 74bc613d94 fix(rag): address Copilot review findings on the driver abstraction
Five review comments, all real:

- hybrid_search ran its vector and keyword legs sequentially after the
  provider refactor; main ran them under tokio::join!. Restores the
  concurrency while keeping the degrade-on-error keyword behaviour, so a
  remote provider no longer pays two serial round trips per query.

- inject_rag_secrets derived a vault secret name by trimming braces, which
  leaves a literal key untouched. A RAG holding a plaintext api_key therefore
  looked the secret up by its own value and printed it to stderr on failure.
  Parsing is now strict and a non-placeholder is skipped with a warning that
  names no credential.

- validate() now refuses a driver_config.api_key that is not a {{NAME}}
  placeholder, so a plaintext key cannot reach the RAG YAML at all.

- Rag::create's catch-all arm treated any unrecognised driver as yaml. A typo
  built a yaml store, paid to embed the corpus, persisted the bad driver and
  only failed on the next run. Unknown drivers now fail immediately.

- The qdrant arm's error was written for a developer; it now tells the user
  that only attached collections are readable and points at .rag attach.
2026-08-11 21:04:21 -06:00
Dark-Alex-17 6d0a5550fe style: Removed some redundant comments 2026-08-11 20:56:51 -06:00
Dark-Alex-17 7b1c0342b4 fix(rag): delete the DuckDB write-ahead log alongside the store
Deleting a RAG removed its .duckdb file but left the sibling .duckdb.wal
behind. DuckDB only removes that log on a clean close, so any RAG whose
process was killed left one on disk, and creating a new RAG under the same
name let it inherit a write-ahead log describing someone else's data.

The test helper already cleaned the log up after itself, which is why no
test noticed the production path did not.
2026-08-11 16:55:19 -06:00
Dark-Alex-17 d6c114fe58 feat: simplified the duckdb selection prompt 2026-08-11 16:50:50 -06:00
Dark-Alex-17 912e00a627 docs(rag): correct the duckdb concurrency note in the driver prompt
The driver picker still told users a duckdb RAG can only be open in one Coyote
process at a time. That stopped being true once the store began opening
read-only for queries: any number of processes can now query it concurrently.

The restriction that remains is narrower and only bites while writing, so the
prompt now states that instead — several processes can query at once, but an
ingest or rebuild locks the others out until it finishes.
2026-08-11 16:38:55 -06:00
Dark-Alex-17 e006e29ff1 feat(rag): let several Coyote processes query one duckdb RAG at once
The DuckDB store was always opened read-write, which takes an exclusive file
lock, so a second Coyote process could not even read the RAG. Querying does not
write, and DuckDB permits many concurrent readers as long as no writer is
attached, so the store is now opened read-only whenever it already carries a
complete schema.

Creating or initializing the store still writes, as does rebuilding, so those
paths take the exclusive handle. The rebuild path upgrades a read-only
connection in place, which every clone of the handle observes because the mode
lives behind the shared mutex rather than beside it. Extension loads and the
HNSW persistence setting are per-connection and are re-established on the
upgraded connection.

An upgrade that loses the race for the write lock reports that another process
holds the RAG and that nothing was written, then reopens read-only so the
session can keep querying. A read-only handle also refuses writes outright, so a
missed upgrade cannot silently discard an ingest.
2026-08-11 14:58:18 -06:00
Dark-Alex-17 c0067d387c refactor(rag): drop the hardcoded embedding model hint from attach
The attach wizard mapped a collection's vector dimension to a hardcoded list of
model names and printed them as likely candidates. The list was never checked
against the models the user actually has configured, so it could recommend a
model they cannot select, and one entry was a parenthetical note rather than a
model id and so could never match anything. Any list like this rots as models
are released.

The dimension itself comes from the server and is worth stating, so it is still
printed, as is the warning that a mismatched embedding model returns bad
results. Deriving real candidates would need a dimension recorded against each
configured model, which the model config does not carry today.
2026-08-11 14:06:57 -06:00
Dark-Alex-17 118c346345 feat(rag): support string and UUID Qdrant point IDs
Point ids were read with as_u64() inside a filter_map, so a string id was
silently dropped and a UUID-keyed collection returned zero hits with no error.
The attach wizard therefore refused such collections and told the user to
rebuild with integer ids, which defeats the purpose of attaching to a
collection someone else already built. LangChain, a common way to populate
Qdrant, uses UUIDs by default.

The integer id was never load-bearing for this driver. DocumentId is a packed
(file, chunk) pair used positionally by the local drivers, but an attached RAG
holds no local files or vectors and every positional consumer already returns
early on it, so the id only has to survive the round trip from search back to
the content fetch. Ids that cannot make that trip as a u64 are interned behind
a synthetic handle and restored when the fetch is issued, leaving collections
that already use integer ids on exactly the path they used before.
2026-08-11 14:05:38 -06:00
Dark-Alex-17 dc677a2529 fix(sandbox): discover agent-scoped RAG mixin sidecars
An agent-scoped RAG writes its config to <data>/agents/<agent>/<rag>.yaml, so
its sbx mixin sidecar lands beside it as <rag>.sbx-mixin.yaml. Discovery scanned
the agents directory only for a file named exactly sbx-mixin.yaml, and scanned
for suffixed sidecars only in the top-level rags directory, so a RAG attached
while an agent was active contributed no network allow rule and no credential to
the sandbox. The failure was silent: the sandbox launched and the RAG was simply
unreachable from inside it.

The two collectors differed only in the filename shape they matched, so they are
now one scan that takes the set of layouts to look for. The agents directory
asks for both its own sbx-mixin.yaml and the suffixed sidecars one level in,
which is the shape that was missing. Discovery order is unchanged, and it is
load-bearing: each mixin becomes a --kit in list order and later ones layer over
earlier ones, so the workspace mixin must stay last.
2026-08-11 14:05:31 -06:00
Dark-Alex-17 5e2b9c98ad fix(rag): stop the attach wizard from silently accepting an empty collection
`sample_point_id` returns `None` for a collection with no points, so the
UUID guard's `if let Some(..)` fell straight through and the wizard attached
happily. The result is a RAG that answers every query with zero hits and
never says why.

Sample once, then check for emptiness explicitly. This warns and asks rather
than hard-failing: an empty collection is not necessarily a mistake, since
another tool may be about to populate it, and none of the wizard's remaining
probes can distinguish that from a misconfiguration. The confirmation
defaults to "no" so it cannot be walked past by accident, and `attach`
already refuses to run non-interactively, so no unattended path reaches it.
2026-08-11 13:55:59 -06:00
Dark-Alex-17 c458ca93a9 feat(rag): create the API key secret inline in the attach wizard
The wizard hard-errored with "Secret 'X' not found in vault. Run
`coyote --add-secret X` first.", throwing away every answer the user had
already given it. Offer to create the secret in place instead, deferring to
`Vault::add_secret` for the masked prompt, the provider write and the
confirmation line, then read it back.

Only a genuine `SecretError::NotFound` triggers the offer. An auth failure,
a provider outage, or the vault being disabled inside a sandbox all
propagate with their own message, because prompting for a value that cannot
be stored would fail one step later and bury the real cause. Declining the
offer fails with both ways out spelled: add the secret up front, or answer
"no" to the API-key question.
2026-08-11 13:50:33 -06:00
Dark-Alex-17 860566bf50 feat: let workflow rag nodes select a RAG driver
`RagNode` gains an optional `driver`, forwarded into `RagInitConfig` so a
graph node can build its knowledge base on duckdb instead of yaml. Nodes
that name no driver forward `None`, which still resolves to yaml, so
existing workflows are unaffected.

An unknown driver is rejected up front rather than at construction time.
`Rag::create` dispatches unknown drivers to its yaml catch-all, so a typo
would otherwise embed every document and persist the bogus string, after
which every subsequent load fails validation and the agent cannot start.
The check asks `RagData::validate()` through a probe value instead of
restating the list of valid drivers, so the two cannot drift.
2026-08-11 13:46:59 -06:00
Dark-Alex-17 7f90710427 refactor(rag): interpolate every driver_config value, not just api_key
Only `driver_config["api_key"]` was interpolated, so any credential-bearing
driver field added later would have shipped its raw `{{PLACEHOLDER}}` to the
server. Resolve every value instead, via `resolve_driver_config`.

Resolution still happens into a function-local copy and never touches
`RagData`: `save()` serializes `self.data` and is called by `.set rag_top_k`
and friends, so a resolved credential parked there would be written to the
RAG's YAML in plaintext. The literal `{{NAME}}` also has to survive on disk
because sandbox credential provisioning parses it back out to learn which
vault secret to bind. Scope stays `driver_config` deliberately: the rest of
a RAG file is ingested document text, where `{{...}}` is ordinary content.

Covered by a test that saves after a load and asserts the placeholder, not
the secret, is what reaches the file.
2026-08-11 13:46:32 -06:00
Dark-Alex-17 93a934439b fix(rag): fail loudly when a RAG's vault secret is missing
`interpolate_secrets` does not error on a secret the vault cannot resolve:
it substitutes the empty string and returns the name in its second tuple
element. `load_async` discarded that vec, so a typo'd or deleted vault
secret produced `api_key = ""` and an unexplained 401 from Qdrant.

Bail instead, naming the RAG and the missing secrets, matching what global
config loading already does.
2026-08-11 13:44:00 -06:00
Dark-Alex-17 ecda258d3a style: Cleaned up some minor styling issues 2026-08-11 13:04:27 -06:00
Dark-Alex-17 3e598065f8 fix(rag): serialize DuckDB extension installs to stop a Windows race
`ensure_extension` fell back to `INSTALL` whenever `LOAD` failed. With a cold
extension cache every thread's `LOAD` fails at once, so every thread ran
`INSTALL` concurrently for the same extension. DuckDB installs by downloading
to a temp file and then MOVING it into `~/.duckdb/extensions/...`; POSIX allows
replacing a file other handles hold open, so Linux and macOS survived, but
Windows rejects that move with "Access is denied" and the losing threads failed.

Guard the install step with a process-global mutex and re-check `LOAD` after
acquiring it. The re-check is what bounds the work to a single install: without
it every thread queued behind the winner would still run a redundant `INSTALL`
and repeat the same move over a file that is now open.

`LOAD` is per-connection, so it still runs on every connection; only `INSTALL`
is serialized. An already-installed extension takes the pre-lock fast path and
costs neither a lock nor network. The lock is never held across the connection
mutex, so it cannot invert lock order.

Traced with strace on a cold cache under default test parallelism: before, 17
threads moved files into the store (13 racing on vss alone); after, exactly one
rename per extension.
2026-08-10 16:13:36 -06:00
Dark-Alex-17 3abc30d633 fix(rag): emit an sbx kit v2 mixin and declare RAG credentials to the proxy
The RAG attach sidecar was written against the sbx kit v1 spec and still emitted schemaVersion "1" with network.allowedDomains, network.serviceDomains, network.serviceAuth, credentials.sources.<n>.env and environment.proxyManaged. Every one of those keys was removed in kit v2. Coyote does not validate mixins, it copies them byte-for-byte into spec.yaml, so the invalid document surfaced only as an opaque sbx failure with no indication of which mixin caused it.

generate_rag_sbx_mixin now builds the document from the shared serializer structs instead of a format! string, which is how the envelope drifted unnoticed in the first place. render_mixin_yaml and the RAG sidecar both go through a new render_mixin_document, giving one definition of the envelope and one enforcement point for the rule that every inject domain must also appear in permissions.network.allow.

Fix an auth bug the port exposed: inject_rag_secrets bound the API key with sbx secret set, but nothing ever emitted a matching credentials entry, so the proxy held a value with no inject rule and never rewrote the auth header. An attached RAG credential silently did not work inside the sandbox. The sidecar now declares that credential; a RAG with no API key declares none while still receiving egress.

Fix the service id: the bind passed the raw file stem instead of routing it through secret_service_id, so a RAG named My_Docs produced an illegal id. The bind and the generated credentials service now share that derivation and cannot disagree.

Retire sbx_domain_forms in favour of allow_entry_for_url, now pub(crate). It emitted both a bare host and host:port because v1 serviceDomains needed a bare key; v2 has no such need, so the extra entry is simply wrong. It also defaulted a schemeless host to port 6333 while normalize_base_url resolves it to http and port 80, meaning the allow entry named a port the client never dialled.
2026-08-10 15:58:40 -06:00
Dark-Alex-17 f68937611e fix(rag): install DuckDB vss and fts extensions when they are missing
The DuckDB schema init loaded the vss and fts extensions but nothing ever
installed them, so any machine without them already present failed with
'IO Error: Extension "vss.duckdb_extension" not found'. This surfaced as 13
failing tests in CI while passing locally, because local runs had the
extensions installed already.

Loading is attempted first so an extension that is already present costs
nothing and never touches the network; INSTALL is reached only once, on a
machine seeing the extension for the first time, and reports an actionable
message if it cannot download.

CI cached the extension directory but nothing populated it, so the cache
saved an empty directory forever. The cache key now derives from Cargo.lock
rather than a hardcoded DuckDB version, and a step on cache miss installs the
extensions so the post-job save has something to store.
2026-08-10 15:47:15 -06:00
Dark-Alex-17 a12cf84eb6 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-08-10 15:41:50 -06:00
Dark-Alex-17 2b45e3a9b8 feat: improved wording and heuristic detection for sisyphus suite of 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-08-10 15:37:53 -06:00
Dark-Alex-17 91dbaf5533 feat: upgraded to sbx kit v2 spec for improved integration
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-08-10 15:26:16 -06:00
Dark-Alex-17 7a732436aa feat(rag): add attach-only Qdrant provider, attach wizard and sandbox wiring
Adds QdrantProvider as a read-only driver for pre-existing remote Qdrant
collections, an interactive '.rag attach' wizard, and the sandbox credential
and domain-whitelisting wiring that lets an attached RAG work inside a sandbox.

Attach-only by design: rebuild_indexes bails for both the attached and the
unattached case rather than silently succeeding. Coyote never writes to Qdrant
in this change.

Vectors are never hydrated back from Qdrant. Cosine collections L2-normalize
stored vectors on write, so reading them back returns unit-length copies of the
originals; the YAML vector copy is authoritative and the serialization guard
stays scoped to the duckdb driver alone.

Collections keyed by string or UUID point IDs are rejected at attach time. The
read path parses point ids as u64 inside a filter_map, so such a collection
would otherwise yield zero results with no error.

The three response-shape parsers are pure functions over an already-parsed JSON
body, unit-tested against captured fixtures, with the async wrappers delegating
to them rather than duplicating the logic.

'.rag' now splits its first argument, so '.rag attach <name>' no longer tries to
load a RAG literally named 'attach <name>'.
2026-08-10 13:40:22 -06:00
Dark-Alex-17 98d3ba4a83 feat(rag): add DuckDB provider behind the RAG driver abstraction
Phase 3 of the RAG driver abstraction. Adds a `DuckDbProvider` that keeps
vectors and document content in a `.duckdb` sidecar next to the existing
YAML metadata, selected by the `driver: duckdb` field.

- `src/rag/providers/duckdb.rs` (new): vector search via the vss extension
  and keyword search via fts, an all-or-nothing hydration path (a partial
  read is an error, never a shorter map), and an anti-wipe guard that
  refuses the destructive `CREATE OR REPLACE TABLE` when `data.vectors` is
  empty while `data.files` is not and the store still holds rows.
- `src/rag/mod.rs`: `sync_documents` now refreshes `bm25`/`node_to_docs`
  BEFORE the fallible `provider.rebuild_indexes`. `self.data` is already
  mutated by that point, so propagating a provider error afterwards would
  leave the derived in-memory state describing the previous corpus while
  `data` describes the new one. Both rebuilds are pure functions of
  `self.data` and cannot fail, so running them first is always safe.
- `src/config/paths.rs`: sidecar path helpers.
- `src/rag/providers/mod.rs`, `src/config/agent.rs`: driver dispatch and
  RAG cache keying.

Also keeps `RequestContext::rag_key` in lockstep with `rag` at the two
sites that were still missing it, so that a cache insert and its matching
invalidate are structurally incapable of disagreeing:

- `use_agent` assigned `self.rag` from the agent but never set `rag_key`.
  This one was live. Agent RAGs are inserted under `RagKey::Agent(<name>)`,
  so with `rag_key == None` the invalidation guards in `rebuild_rag` and
  `edit_rag_docs` matched nothing and `.rebuild rag` left the stale cache
  entry in place. Worse, a preceding `.rag <name>` left a stale
  `Named(<name>)` key attached to the agent's RAG, pointing the
  invalidation at an unrelated RAG's cache entry. Now mirrors the insert
  key exactly, yielding `None` when the agent has no RAG.
- `exit_agent` cleared `self.rag` but left `rag_key` behind. Latent rather
  than live, since `rebuild_rag`/`edit_rag_docs` both bail on
  `rag.is_none()` before reaching the invalidate guards, but the guards
  that make it unobservable are not the kind of thing to depend on.

Covered by `use_agent_does_not_carry_stale_rag_key`, and by a new
assertion in `exit_agent_clears_all_agent_state`.
2026-08-10 12:51:56 -06:00
Dark-Alex-17 d734276927 build(rag): add duckdb dependency and pin comfy-table to 7.1.4
Adds the duckdb crate with the bundled feature ahead of any provider
code, so the dependency and build surface can be proven on every CI
target on its own.

duckdb constrains comfy-table to ~7.1, so comfy-table moves from 7.2.2
to 7.1.4 while keeping custom_styling. That feature swaps
measure_text_width for an ANSI-stripping implementation that
render_table's pre-styled cells depend on; dropping it still compiles
and still passes every other test, and only corrupts column widths. A
regression test now renders a styled table at a fixed wrap width and
asserts every line has an equal ANSI-stripped display width.

comfy-table 7.1.4 pins crossterm 0.28 while coyote pins 0.29, so both
now build side by side. comfy_table::Color, Attribute and Cell are
consequently crossterm 0.28 types and must not be used; table styling
stays ANSI-string based.

Caches the DuckDB extension directory in CI, keyed on the runner OS and
the DuckDB version, so vss and fts survive an upstream outage.

Also switches merge_vector_results to f32::total_cmp. The previous
partial_cmp().unwrap_or(Equal) comparator is not total under NaN, which
sort_by is permitted to answer with a panic in release builds.
2026-08-10 11:59:57 -06:00
Dark-Alex-17 5049143fcc refactor(rag): extract RagProvider trait and add YamlProvider
Introduce a narrow `RagProvider` trait covering vector search and content
retrieval, and make `Rag` delegate to a boxed provider instead of owning an
HNSW index directly. `YamlProvider` is the sole implementation for now.

The trait deliberately stays narrow: embeddings, chunking, BM25 keyword
search, graph RAG, entity extraction, RRF merging and persistence all remain
on `Rag`/`RagData`, so a new storage backend does not have to reimplement
Coyote's indexing logic.

Notable points:

- `fetch_content`'s ordering contract is part of the trait, not an accident.
  Implementations must return results in input-`ids` order; `hybrid_search`
  passes an RRF-ranked list straight to the prompt builder, so a provider
  returning storage order would silently discard the ranking.
- The content store is keyed on `data.files`, never `data.vectors`. Both the
  content map and BM25 now route through the new `RagData::iter_documents()`
  so the two key spaces match by construction. `RagData::add` zips document
  ids with embeddings and truncates silently, so ids in `files \ vectors` are
  genuinely reachable.
- A provider keyword-search failure degrades to an empty ranker with a
  warning rather than failing the whole query; it is one of three RRF inputs.
  It deliberately does not fall back to the local BM25, which would be a
  silent ranking-algorithm swap once a provider with native FTS exists.
- The rerank path builds its text and id vectors from a single `fetch_content`
  result in one pass, so the reranker's positional indices cannot desync.

This is not a bit-for-bit no-op. `vector_search` now dedups by best score and
sorts globally instead of concatenating per-chunk hit lists. Single-chunk
queries (the common case) are unaffected. Multi-chunk queries get corrected
rank assignment and no longer let a document that matched several query
chunks accumulate multiple RRF contributions. There is no overall cap on the
merged pool — truncation remains `reciprocal_rank_fusion`'s job.

`RagData::get()` is removed: its only two callers were the content lookups
replaced here, and an unused private-module method fails the build under
`--deny warnings`. Its three tests were rewritten against `iter_documents()`,
one of which now guards the files-vs-vectors keying directly.

Implements Phase 2 of the RAG driver abstraction design (§6).
2026-08-10 11:41:37 -06:00
Dark-Alex-17 a968c3228d feat(rag): add driver/attached fields, validation floors and force-reingest
Phase 1 of the RAG driver abstraction (design doc sections 5.1-5.5a).

Data model:
- Add `driver: String` (serde default "yaml" via RagData::default_driver) and
  `attached: bool` as the first two fields of RagData, so driver metadata sits
  at the top of each RAG YAML. Old files without them load unchanged.
- Add `#[serde(default)]` to the non-Option fields so a minimal attached-RAG
  YAML deserializes, and add `skip_serializing_if` to `vectors` so an empty
  map renders no `vectors:` key.
- Add a hand-written `impl Default for RagData` delegating to `RagData::new()`.
  It is deliberately not derived: a derived impl yields `driver: ""`, which is
  not a valid driver string.

Validation (the price of the new serde defaults):
- Add `RagData::validate()`, called from `Rag::load()` after deserialization.
  It enforces the (driver, attached) matrix and, critically, numeric floors
  that the new defaults would otherwise mask: `top_k >= 1` unconditionally
  (a 0 makes every query return nothing, silently), and `chunk_size >= 1` plus
  `chunk_overlap < chunk_size` when not attached (a 0 chunk_size is a real
  divide-by-zero panic while sizing embedding batches).
- Reject `.set rag_top_k 0` at the setter, before the set/update fork. Without
  this, the new load-time floor turns one keystroke into an unloadable RAG:
  the setter saves immediately and no dot-command can reach the file again.

Rebuild actually re-embeds now:
- `.rebuild rag` and `--rebuild-rag` previously re-scanned paths and re-embedded
  nothing, because the content-hash skip fired regardless of the refresh flag.
  Extract that decision into a module-level `find_hash_skip()` free function and
  thread a `force_reingest` flag through `sync_documents()` and
  `refresh_document_paths()`, set true only from `rebuild_rag()`. `.edit rag-docs`
  stays incremental. Re-embedding costs time and API spend, so `rebuild_rag()`
  now prints a one-line file-count warning first (no prompt: the path is
  reachable from a non-interactive CLI flag).

Attached-RAG guards:
- Block `.rebuild rag` / `--rebuild-rag` and `.edit rag-docs` on attached RAGs,
  which Coyote did not index and whose source documents it does not own.
- Add `Rag::driver()`, `Rag::is_attached()` and `Rag::file_count()`, and surface
  driver/attached through `Rag::export()` so `.info rag` shows them.

Adds 12 unit tests (1299 -> 1311), including the two gate tests pinning that a
forced re-ingest does not hash-skip while an ordinary refresh still does.
2026-08-10 11:04:51 -06:00
Dark-Alex-17 f404acdbca Merge branch 'main' 2026-08-06 16:39:02 -06:00
Dark-Alex-17 efa570267d feat(mcp): send RFC 8707 resource indicator in OAuth flows
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-08-06 16:13:06 -06:00
Dark-Alex-17 9aeb9e6e2e Merge branch 'main' 2026-08-06 13:13:03 -06:00
Dark-Alex-17 3607a180d9 fix: don't output thinking blocks for claude-based models
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-08-06 13:12:36 -06:00
Dark-Alex-17 d429def0f6 fix: additional edge case fix for duplicate tool call IDs in anthropic API calls
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-08-06 10:30:33 -06:00
Dark-Alex-17 e606eb7c49 fix: removed temperature modifier in librarian agent to mitigate invisible errors
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-08-05 16:10:19 -06:00
Dark-Alex-17 a8fb32b6bd fix: strip reasoning blocks for structured LLM output in graph agents 2026-08-05 16:10:03 -06:00
Dark-Alex-17 1f7b8417fa fix: prevent rare duplicate tool call IDs in long running claude prompts 2026-08-05 16:01:40 -06:00
Dark-Alex-17 9540345ec7 feat: Added loaded indicators to .list tools/mcp-servers/skills
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-08-05 13:11:24 -06:00
Dark-Alex-17 70b6d51b55 test: Implemented unit tests to prevent regression on agent reasoning effort inheritance
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-08-04 13:12:37 -06:00
Dark-Alex-17 9e5e8a60f2 fix: agents inherit global reasoning effort if unset 2026-08-04 13:09:13 -06:00
Dark-Alex-17 d6447603bc feat: hide .recover from tab completions when no session is active
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-08-04 12:05:23 -06:00
Dark-Alex-17 e6dc24beb5 feat: add a new .recover command for sessions to recover from errors
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-08-04 12:02:31 -06:00
Dark-Alex-17 e76c3efe4e feat: integrated the git-ssh-sign kit into the coyote sandbox kit
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-08-04 10:56:50 -06:00
github-actions[bot] fac577589b chore: bump Cargo.toml and sandbox image to 0.8.3
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-08-03 21:28:37 +00:00
github-actions[bot] 737fc42ec1 bump: version 0.8.2 → 0.8.3 [skip ci] 2026-08-03 21:28:33 +00:00
Dark-Alex-17 888529f381 fix: infinite loop bug when attempting to interrupt a prompt exchange right before a session compression
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-31 16:00:26 -06:00
Dark-Alex-17 35e75e5b4f fix: ctrl-c inside of an auto-continue loop created an infinite loop
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-31 11:44:16 -06:00
github-actions[bot] dd7d75fd9f chore: bump Cargo.toml and sandbox image to 0.8.2
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-31 16:08:58 +00:00
github-actions[bot] 78f5fc8fb9 bump: version 0.8.1 → 0.8.2 [skip ci] 2026-07-31 16:08:53 +00:00
Dark-Alex-17 4f38214681 fix: sbx update doesn't allow undefined fields in sbx spec
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-31 10:07:29 -06:00
github-actions[bot] 019bd6f1c7 chore: bump Cargo.toml and sandbox image to 0.8.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-30 22:37:17 +00:00
github-actions[bot] 875b6749c2 bump: version 0.8.0 → 0.8.1 [skip ci] 2026-07-30 22:37:15 +00:00
Dark-Alex-17 69e1b98c44 fix: ctrl-c interruption doesn't discard session messages when throbber is showing
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-30 13:38:37 -06:00
Dark-Alex-17 0324436114 feat: ctrl-c interrupts ongoing prompt in a session, but lets the user inject more instructions mid-stream
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-30 10:21:19 -06:00
Dark-Alex-17 233c212d2a feat: improved function calling performance by allowing parallel tool calling
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-29 12:40:52 -06:00
Dark-Alex-17 e288b41365 fix: improper handling of fd-style globbing for directories in fs_glob 2026-07-29 12:40:33 -06:00
Dark-Alex-17 fbf6a6bdf4 fix: properly templated architect design doc path in starter commands
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-29 11:59:09 -06:00
Dark-Alex-17 57b72702b2 feat: created the architect and gatekeeper agents for dramatically improved coding performance
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-29 11:23:52 -06:00
Dark-Alex-17 38ba303c3c feat: Improved readability of session message exchange replays
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-29 10:15:35 -06:00
Dark-Alex-17 fc7bc0ff8f fix: .copy works when sessions are resumed 2026-07-29 09:50:40 -06:00
Dark-Alex-17 7f7ea758a7 fix: ACP session/prompt now drives the full tool-execution loop
CI / All (ubuntu-latest) (push) Failing after 25s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
run_prompt_turn previously performed a single completion and returned,
leaving tool calls unexecuted. It now mirrors start_directive's loop:
call -> execute tools -> merge results -> continue until no tool results,
then check the pending-agents guardrail before returning.

The pending-agents guardrail injects a reminder prompt when sub-agents
are pending, matching the same loop termination semantics as --headless.
The session is NOT exited between turns (unlike start_directive) so
multi-turn ACP conversations retain history across session/prompt calls.

Manual gate (tool-probe agent, fs_write + fs_read tools):
  id 3 result: {"output":"DONE:probe.txt","stopReason":"end_turn"}
  probe.txt exists: YES, content: hello
2026-07-28 15:42:51 -06:00
Dark-Alex-17 06b2c384e3 fix: ACP spec conformance — ContentBlock prompt params and protocolVersion type
CI / All (ubuntu-latest) (push) Failing after 26s
CI / All (macos-latest) (push) Has been cancelled
CI / All (windows-latest) (push) Has been cancelled
DEFECT 1: session/prompt now accepts the spec-shaped params as primary:
  {"prompt": [{"type": "text", "text": "..."}]}
Text blocks are joined with newlines. Non-text block types are silently
ignored. The legacy params.text alias is preserved as a fallback. -32602
is returned only when neither a non-empty prompt array with text blocks
nor a non-empty text field is present.

DEFECT 2: initialize result now emits protocolVersion as integer 1
instead of the string "1", matching the ACP spec's InitializeResponse.

Tests: 4 new unit tests pin the spec-shaped prompt path, the non-text
block ignore behavior, the missing-both -32602 path, and the numeric
protocolVersion type.
2026-07-28 14:41:22 -06:00
Dark-Alex-17 d50de7c06a lint: fixed test ordering
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-27 19:52:51 -06:00
Dark-Alex-17 0956f08791 refactor: move ACP server dispatch into run() for shared flag setup
All CLI flag processing (--agent, --role, --rag, --model, --no-memory,
--no-stream, --no-workspace-instructions, etc.) now runs through run()
before the REPL/cmd split. The ACP server is dispatched right before
match is_repl, after apply_prelude and skills loading, so it benefits
from the complete context setup with no duplication or drift risk.
2026-07-27 19:44:11 -06:00
Dark-Alex-17 087d0c320c feat: apply --agent/--role/--rag/--model flags in --acp-server mode
These CLI flags were previously ignored because the ACP branch returned
before run() could apply them. Now the context is configured with the
requested agent, role, RAG index, and model before the server starts.
Session management remains protocol-driven via session/new and session/load.
2026-07-27 19:31:45 -06:00
Dark-Alex-17 2128390f99 fmt: 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-27 19:26:29 -06:00
Dark-Alex-17 d008de1848 fix: restore stdout output for standalone --headless mode
RenderMode::Silent was incorrectly applied to --headless in addition to
--acp-server. Standalone headless should still display the LLM response;
only ACP mode requires stdout purity for JSON-RPC. The acp server's
run_prompt_turn already sets Silent before each prompt call.
2026-07-27 19:22:51 -06:00
Dark-Alex-17 d79787bf96 fix: suppress tool-call display in headless mode; initialize session on session/new 2026-07-27 19:14:28 -06:00
Dark-Alex-17 577c51b62f fix: skip stdin drain and set silent render mode when --acp-server is active 2026-07-27 18:59:09 -06:00
Dark-Alex-17 d462b09f80 feat: add headless profile to sbx-kit spec 2026-07-27 18:03:35 -06:00
Dark-Alex-17 b711e4983b feat: implement ACP user-interaction to request_permission bridge 2026-07-27 18:00:07 -06:00
Dark-Alex-17 6ae3efb06c feat: implement ACP session/load and session/cancel 2026-07-27 17:52:49 -06:00
Dark-Alex-17 02dd14394b feat: implement ACP session/prompt 2026-07-27 17:48:31 -06:00
Dark-Alex-17 f11d4ca760 feat: add ACP server skeleton with stdout-purity test 2026-07-27 17:31:47 -06:00
Dark-Alex-17 f1415067f2 feat: add --headless flag for unattended operation 2026-07-27 17:17:56 -06:00
Dark-Alex-17 af5c34fde5 Merge branch 'main' of github.com:Dark-Alex-17/coyote 2026-07-27 15:05:25 -06:00
Dark-Alex-17 2ffa278f2d test: testing potential nerdbox regression fix for coyote sandbox mode 2026-07-27 15:04:41 -06:00
Dark-Alex-17 f4cbee9611 docs: remove comment in spec.yaml about copying in coyote password file 2026-07-27 10:50:40 -06:00
Dark-Alex-17 e95fd1e06e ci: fix typo in coyote image tag; needs leading 'v'
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-27 09:51:23 -06:00
Dark-Alex-17 d79ea55e09 fix: include graph-agent descriptions in .agent <TAB> completions
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-27 09:34:36 -06:00
github-actions[bot] b898e4dd78 chore: bump Cargo.toml and sandbox image to 0.8.0
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-25 01:08:02 +00:00
github-actions[bot] 30e00f8332 bump: version 0.7.4 → 0.8.0 [skip ci] 2026-07-25 01:07:59 +00:00
Dark-Alex-17 58d9d4c64e docs: updated help message for --fresh flag
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-24 18:30:45 -06:00
Dark-Alex-17 63a768aa46 fix: fresh wizard openai-compatible support
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-24 18:29:24 -06:00
Dark-Alex-17 2c3f671efa fix: config existence check for --fresh sandboxes
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-24 18:09:06 -06:00
Dark-Alex-17 8b0a536f4e feat: Dynamically detect if a selected client in the sandbox first run wizard supports oauth
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-24 18:07:30 -06:00
Dark-Alex-17 5a1bb569b4 feat: Add support for the --fresh flag again with host environment configuration injection
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-24 18:00:41 -06:00
Dark-Alex-17 0c12580836 fix: Improve coyote sandbox startup time 2026-07-24 17:23:08 -06:00
Dark-Alex-17 df909325a7 fmt: 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-24 16:50:27 -06:00
Dark-Alex-17 d379fcddf8 fix: bypass forgotten sandbox mode check for MCP secret interpolation
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-24 16:50:04 -06:00
Dark-Alex-17 b405acd8f0 feat: force overwrite global sbx secrets 2026-07-24 16:45:51 -06:00
Dark-Alex-17 805ae7112a feat: add sbx secrets globally
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-24 16:41:00 -06:00
Dark-Alex-17 6ddbf37523 feat: only create secrets local to a 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-24 16:36:16 -06:00
Dark-Alex-17 f510bb649b feat: Improved credentials management for docker sandboxes 2026-07-24 16:26:35 -06:00
Dark-Alex-17 c1b14bdfdf docs: Created a mermaid diagram for Sisyphus
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-24 13:55:31 -06:00
Dark-Alex-17 46f2a9eae2 docs: added in forgotten connection to the librarian agent diagram
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-24 13:44:07 -06:00
Dark-Alex-17 cf3a12141b docs: updated the graph agent diagrams to use mermaid diagrams for more easily readable diagramming in their READMEs
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-24 13:39:59 -06:00
Dark-Alex-17 8f13810f0f chore: updated models.yaml 2026-07-24 13:27:20 -06:00
Dark-Alex-17 eba8c86e21 fix: properly wrap sub-style changes in markdown rendering
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-24 12:13:33 -06:00
Dark-Alex-17 d75fb47de1 docs: Updated project license
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 21:07:51 -06:00
Dark-Alex-17 49a281bf93 feat: renamed --contents arg for fs_write/patch to --content since most models attempt that first and error otherwise
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 19:13:36 -06:00
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
162 changed files with 34409 additions and 1980 deletions
+11
View File
@@ -36,6 +36,17 @@ jobs:
- uses: Swatinem/rust-cache@v2
- name: Cache DuckDB Extensions
id: duckdb-extensions
uses: actions/cache@v4
with:
path: ~/.duckdb/extensions
key: duckdb-ext-${{ matrix.os }}-${{ hashFiles('Cargo.lock') }}
- name: Install DuckDB Extensions
if: steps.duckdb-extensions.outputs.cache-hit != 'true'
run: cargo test --all duckdb
- name: Test
run: cargo test --all
+77 -15
View File
@@ -8,9 +8,9 @@ on:
workflow_dispatch:
inputs:
bump_type:
description: "Specify the type of version bump"
description: 'Specify the type of version bump'
required: true
default: "patch"
default: 'patch'
type: choice
options:
- patch
@@ -46,7 +46,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: '3.10'
- name: Install Commitizen
run: |
@@ -108,17 +108,19 @@ jobs:
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 user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git config --global --add safe.directory "$GITHUB_WORKSPACE"
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
git add -u -- Cargo.toml Cargo.lock
git commit -m "chore: bump Cargo.toml to $VERSION"
if ! git diff --quiet -- Cargo.toml Cargo.lock assets/sbx-kit/spec.yaml; then
git add -u -- Cargo.toml Cargo.lock assets/sbx-kit/spec.yaml
git commit -m "chore: bump Cargo.toml and sandbox image to $VERSION"
else
echo "No changes to commit (already at $VERSION)"
fi
@@ -163,28 +165,28 @@ jobs:
- target: aarch64-unknown-linux-musl
os: ubuntu-latest
use-cross: true
cargo-flags: ""
cargo-flags: ''
- target: aarch64-apple-darwin
os: macos-latest
use-cross: true
cargo-flags: ""
cargo-flags: ''
- target: aarch64-pc-windows-msvc
os: windows-latest
use-cross: true
cargo-flags: ""
cargo-flags: ''
- target: x86_64-apple-darwin
os: macos-latest
cargo-flags: ""
cargo-flags: ''
- target: x86_64-pc-windows-msvc
os: windows-latest
cargo-flags: ""
cargo-flags: ''
- target: x86_64-unknown-linux-musl
os: ubuntu-latest
use-cross: true
cargo-flags: ""
cargo-flags: ''
- target: x86_64-unknown-linux-gnu
os: ubuntu-latest
cargo-flags: ""
cargo-flags: ''
steps:
- name: Check if actor is repository owner
@@ -338,7 +340,7 @@ jobs:
${{ steps.package.outputs.archive }}
${{ steps.package.outputs.sha }}
tag_name: v${{ env.RELEASE_VERSION }}
name: "v${{ env.RELEASE_VERSION }}"
name: 'v${{ env.RELEASE_VERSION }}'
body_path: artifacts/changelog.md
prerelease: false
@@ -456,3 +458,63 @@ jobs:
if: env.ACT != 'true'
with:
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:v${{ env.version }}
build-args: COYOTE_VERSION=${{ env.version }}
+4
View File
@@ -5,3 +5,7 @@
.idea/
/coyote.iml
/.idea/
.coyote/**
.sisyphus/**
.coyote-project.json
.coyote/memory/
+273
View File
@@ -1,3 +1,276 @@
## v0.8.3 (2026-08-03)
### Fix
- infinite loop bug when attempting to interrupt a prompt exchange right before a session compression
- ctrl-c inside of an auto-continue loop created an infinite loop
## v0.8.2 (2026-07-31)
### Fix
- sbx update doesn't allow undefined fields in sbx spec
## v0.8.1 (2026-07-30)
### Feat
- ctrl-c interrupts ongoing prompt in a session, but lets the user inject more instructions mid-stream
- improved function calling performance by allowing parallel tool calling
- created the architect and gatekeeper agents for dramatically improved coding performance
- Improved readability of session message exchange replays
- apply --agent/--role/--rag/--model flags in --acp-server mode
- add headless profile to sbx-kit spec
- implement ACP user-interaction to request_permission bridge
- implement ACP session/load and session/cancel
- implement ACP session/prompt
- add ACP server skeleton with stdout-purity test
- add --headless flag for unattended operation
### Fix
- ctrl-c interruption doesn't discard session messages when throbber is showing
- improper handling of fd-style globbing for directories in fs_glob
- properly templated architect design doc path in starter commands
- .copy works when sessions are resumed
- ACP session/prompt now drives the full tool-execution loop
- ACP spec conformance — ContentBlock prompt params and protocolVersion type
- restore stdout output for standalone --headless mode
- suppress tool-call display in headless mode; initialize session on session/new
- skip stdin drain and set silent render mode when --acp-server is active
- include graph-agent descriptions in .agent <TAB> completions
### Refactor
- move ACP server dispatch into run() for shared flag setup
## v0.8.0 (2026-07-25)
### Feat
- Dynamically detect if a selected client in the sandbox first run wizard supports oauth
- Add support for the --fresh flag again with host environment configuration injection
- force overwrite global sbx secrets
- add sbx secrets globally
- only create secrets local to a sandbox
- Improved credentials management for docker sandboxes
- renamed --contents arg for fs_write/patch to --content since most models attempt that first and error otherwise
- Used improved theme selections for tool call highlighting colors
- Improved theme-derived syntax highlighting for LLM tool call logging
- Improved coloring of LLM tool invocation outputs to make LLM output more readable and cohesive
- renamed the user__ask to user__select and improved descriptions to improve model usage
- Improved coloring/highlighting of tool calls to make LLM invocation logs easier to read
- long-running session improvements
- Made sisyphus suite of agents all auto-approved for tool usage
- added ast_grep tool to Sisyphus suite agents
- created the adversay agent and adversarial-review skill
- new spawnable_agents field in agents to let users restrict what agents can be spawned by a parent agent
- replay pre-compressed messages as well when resuming sessions for users to see
- created a new builtin function for agents who can spawn other agents to list available agents via agent__list_available
- **render**: hanging-indent line wrapping for lists and blockquotes
- **render**: wire table state machine and finalize hook
- **render**: render markdown tables with comfy-table
- **render**: parse table cells and column alignments
- **render**: detect markdown table rows and separators
- **render**: add comfy-table dependency and table border style
- **render**: activate rich markdown renderer as default
- **render**: rich block-level markdown rendering (headings, quotes, lists, hr)
- **render**: rich inline markdown rendering (bold, italic, code, links)
- **render**: detect markdown block-level line types
- **render**: precompute markdown scope styles for rich rendering
- Created the raw_markdown configuration flag
- added a .fork command to fork a new session from a running conversation
- **oauth**: enable browser-paste PKCE flow for OpenAI-compatible providers
- copy host OAuth tokens into sandbox at launch
- implement OAuth 2.0 Device Authorization Grant (RFC 8628)
- hint that browser 'paste code' pages can be ignored during callback capture
- openai-compatible wizard offers OAuth when provider has bundled oauth defaults
- validate unique client names at config load
- bundle xAI OAuth defaults in models.yaml
- OAuth branch in openai_compatible prepare_* fns
- get_oauth_provider_for_client dispatcher + client_config_info update
- OpenAICompatibleOAuthProvider (config-driven OAuthProvider impl)
- add auth + oauth fields to OpenAICompatibleConfig
- add oauth field to ProviderModels
- add client_credentials support to prepare_oauth_access_token
- add OAuthConfig + OAuthFlow types to oauth.rs
- Added reasoning effort to the right prompt
- Improved support for Anthropic's extended thinking
- Also support GEMINI.md workspace instructions
- Improved workspace instructions support
- also detect .mcp.json configurations at workspace roots
- Created new .tool enable/disable and .mcp enable/disable aliases to make REPL usage more egonomic
- Created a new .list <kind> REPL command to make discoveribility easier in the REPL
- Support claude-style hidden workspace MCP configuration files via .mcp.json
- Allow users to customize the workspace-specific configuration directory name so they can use Coyote with other CLI clients like .claude
- Add reasoning_effort validation for the main configuration file
- Add validation for reasoning_effort settings to prevent users from specifying erroneous values
- Added support for modifying the reasoning effort of reasoning models
- Explicitly Prevent .undo usage in graph agents
- Added an .undo command to the REPL to let users have more control over the conversation
- Improve sandbox startup time by using the prebuilt Coyote image
- Make coyote available as a docker image
- Made fs_patch more flexible for different model preferences of patch formats
- Installed nano into the sandbox so that users can edit config files in the sandbox directly
- Support workspace-local skill definitions and MCP configurations
- fully functional graph-based RAG
- Implemented graph-based RAG
- Added a --dangerously-skip-permissions flag to skip permission prompts for tool invocations
- Remove the temperature hyperparameter from the diagnose role
- Added a new oauth.redirectHost field to make it possible to further extend MCP support
- Updated the REPL mcp auth path to use the prettified error messaging
- Improved error messaging for failed MCP starts because of auth issues
- Added support for specifying the oauth port and client ID in MCP server configs
- Implemented OAuth support for OpenAI models via Codex endpoints
- merge MCP config when installing bundled mcp config
- Implemented durable state for sisyphus
- Installed ast-grep for the explore agent to use for better code exploration
- Created the step-runner graph agent for more deterministic coding workflows to produce even more reliable and higher-quality results
- Improved oracle and sisyphus agents with skill integrations for the new skills
- Created new sisyphus family skills to improve performance
- Created new diagnostic role and skill for use in other contexts
- 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
- Created a new iwe skill and installed the iwe MCP server for utilizing large knowledgebases
- Session-specific, file-backed history in the REPL
- Replay session output when a user re-enters a session so all output can be seen again
- Added confirmation message after MCP Oauth succeeds when invoked from --auth-mcp
- Created the --auth-mcp CLI flag to let users auth with remote MCP servers without needing to be in the REPL
- add OAuth authentication support for remote MCP servers
- Added mixin for sisyphus so the ddg MCP server can search arbitrary domains
- added improved error messaging on MCP server initialization
- prefer musl versions for linux when running --update/.update
### Fix
- fresh wizard openai-compatible support
- config existence check for --fresh sandboxes
- Improve coyote sandbox startup time
- bypass forgotten sandbox mode check for MCP secret interpolation
- properly wrap sub-style changes in markdown rendering
- removed accidental duplicate ast_grep tool in explore agent
- 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
- added executable bit to adversary agent tools script
- fetch descriptions from graph agent configs as well when listing agents
- **render**: suppress blank lines above rendered table
- chown the full sandbox cache dir, not just the coyote subdir
- chown the whole coyote cache dir not just the oauth dir in the sandbox
- fix typo in Gemini's generation_config property to use camelCase exclusively
- **oauth**: treat missing expires_in as non-expiring device_code token
- **oauth**: send Accept: application/json in device flow requests
- OAuth callback listener skips speculative/malformed browser connections
- resolve reasoning effort for the prompt for global defaults as well
- Account for default model reasoning_effort when supplying that value for the REPL prompts
- model narration included in history and between tool calls to prevent repetition
- Don't terminate agent loops early for null tool output
- reduce code duplication by reusing the new concrete_tool_names function in .list tools
- Agent tools can only be modified via .tool enable/disable using tools in the allowed whitelist in the agent
- re-render agent sessions when entering agents with either pre-configured agent_session or when entering an agent directly into a session
- Per RFC 9728, enable dynamic discovery of OAuth endpoints in MCP using path-aware discovery
- hot-attach to MCP servers that require auth after running .mcp auth <name>
- Correctly inherit graph-global model for extractor model if none is defined
- no cursor timeout when user scrolls away from ongoing streaming output
- default to the nano or notepad when a configured editor is not found
- When EDITOR, VISUAL, or config.editor is defined, don't verify via which
- Added a loop exit condition for the diagnostics skill
- Added directness clause to the diganose role to improve prompt
- fs tools now output better error handling to guide the model more effectively
- Make fs_read more tolerant of various arg invocation formats.
- todo functions are injected properly to roles when roles have auto_continue: true and the REPL is started directly into the role
- updated the redirect URI for OAuth MCP to use localhost since that's what is whitelisted, not 127.0.0.1
- allow MCP OAuth refresh_token to be absent from initial token exchanges
- Overrode the default JSON content-type for MCP OAuth so its properly application/x-www-form-urlencoded
- typo in mcp file name
- Added uvx wrapper for macos-based sandboxes
### Refactor
- Standardized paths module function names to not use 'path' in the name and to just always be either 'dir' or 'file'
- main.rs resolve_oauth_client uses new dispatcher
- split run_oauth_flow into pkce + client_credentials dispatchers
### Perf
- updated the memory injection warning so it only logs once, rather than after each keystroke
## 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
+10 -1
View File
@@ -28,4 +28,13 @@ While Coyote has since diverged significantly and is now developed as an
independent project, its early foundation and inspiration came from the
AIChat project.
AIChat is licensed under the MIT License.
AIChat is licensed under the MIT License. The MIT license text and its
copyright notice are preserved in the [LICENSE-MIT](./LICENSE-MIT) file.
## Licensing
Coyote as a whole is licensed under the GNU Affero General Public License
v3.0 only (AGPL-3.0-only); see [LICENSE](./LICENSE). Substantial portions
derived from AIChat remain under the MIT License (Copyright (c) sigoden),
preserved in [LICENSE-MIT](./LICENSE-MIT). See [NOTICE](./NOTICE) for the
combined-licensing summary.
Generated
+1182 -714
View File
File diff suppressed because it is too large Load Diff
+10 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "coyote-ai"
version = "0.6.0"
version = "0.8.3"
edition = "2024"
authors = ["Alex Clarke <alex.j.tusa@gmail.com>"]
description = "An all-in-one, batteries included LLM CLI Tool"
@@ -9,7 +9,7 @@ homepage = "https://github.com/Dark-Alex-17/coyote"
repository = "https://github.com/Dark-Alex-17/coyote"
categories = ["command-line-utilities"]
readme = "README.md"
license = "MIT"
license = "AGPL-3.0-only"
rust-version = "1.95.0"
exclude = [".github", "CONTRIBUTING.md"]
@@ -17,7 +17,9 @@ exclude = [".github", "CONTRIBUTING.md"]
anyhow = "1.0.69"
bytes = "1.4.0"
clap = { version = "4.5.40", features = ["cargo", "derive", "wrap_help"] }
comfy-table = { version = "7.1.4", features = ["custom_styling"] }
dirs = "6.0.0"
duckdb = { version = "1.10505.0", features = ["bundled"] }
dunce = "1.0.5"
futures-util = "0.3.29"
inquire = "0.9.4"
@@ -49,7 +51,7 @@ textwrap = "0.16.0"
ansi_colours = "1.2.2"
eventsource-stream = "0.2.3"
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"
sha2 = "0.10.8"
unicode-width = "0.2.0"
@@ -58,6 +60,8 @@ http = "1.1.0"
indexmap = { version = "2.2.6", features = ["serde"] }
hmac = "0.12.1"
aws-smithy-eventstream = "0.60.4"
aws-smithy-types = "=1.4.9"
time = "=0.3.47"
urlencoding = "2.1.3"
json-patch = { version = "4.0.0", default-features = false }
bitflags = "2.5.0"
@@ -72,6 +76,7 @@ html_to_markdown = "0.1.0"
rust-embed = "8.5.0"
os_info = { version = "3.8.2", default-features = false }
bm25 = { version = "2.0.1", features = ["parallelism"] }
petgraph = { version = "0.7", features = ["serde-1"] }
which = "8.0.0"
fuzzy-matcher = "0.3.7"
terminal-colorsaurus = "0.4.8"
@@ -79,7 +84,7 @@ duct = "1.0.0"
argc = "1.23.0"
strum_macros = "0.27.2"
indoc = "2.0.6"
rmcp = { version = "1.5.0", features = [
rmcp = { version = "3.1.2", features = [
"client",
"transport-child-process",
"transport-streamable-http-client-reqwest",
@@ -104,6 +109,7 @@ self_update = { version = "0.44", default-features = false, features = [
"archive-zip",
"compression-zip-deflate",
] }
qrcode = "0.14"
[dependencies.reqwest]
version = "0.13.3"
+110
View File
@@ -0,0 +1,110 @@
ARG COYOTE_VERSION
FROM docker/sandbox-templates:shell-docker AS build
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"
RUN set -euo pipefail; \
DUCKDB_VERSION=1.5.5; \
case "${TARGETARCH}" in \
amd64) DUCKDB_ARCH=amd64 ;; \
arm64) DUCKDB_ARCH=arm64 ;; \
*) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
esac; \
TMPDIR=$(mktemp -d); \
curl -fsSL --retry 3 \
"https://github.com/duckdb/duckdb/releases/download/v${DUCKDB_VERSION}/duckdb_cli-linux-${DUCKDB_ARCH}.gz" \
-o "$TMPDIR/duckdb.gz"; \
gunzip "$TMPDIR/duckdb.gz"; \
install -m 0755 "$TMPDIR/duckdb" /usr/local/bin/duckdb; \
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"
FROM scratch
ARG COYOTE_VERSION
COPY --from=build / /
ENV PATH="/home/agent/.cargo/bin:/home/agent/.local/bin:/usr/local/share/npm-global/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \
NPM_CONFIG_PREFIX="/usr/local/share/npm-global" \
NO_PROXY="localhost,127.0.0.1,::1,172.17.0.0/16" \
no_proxy="localhost,127.0.0.1,::1,172.17.0.0/16" \
BASH_ENV="/etc/sandbox-persistent.sh"
LABEL com.docker.sandboxes="templates" \
com.docker.sandboxes.base="ubuntu:questing" \
com.docker.sandboxes.flavor="shell-docker" \
com.docker.sandboxes.start-docker="true" \
org.opencontainers.image.title="coyote" \
org.opencontainers.image.description="An all-in-one, batteries-included LLM CLI tool: Shell Assistant, CLI & REPL mode, RAG, AI tools & agents, MCP servers, skills, and macros." \
org.opencontainers.image.source="https://github.com/Dark-Alex-17/coyote" \
org.opencontainers.image.version="${COYOTE_VERSION}"
WORKDIR /home/agent/workspace
USER 1000
ENTRYPOINT ["coyote"]
+657 -18
View File
@@ -1,22 +1,661 @@
The MIT License (MIT)
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2025 sigoden
Copyright (c) 2025 Alexander J. Clarke
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2025 sigoden
Copyright (c) 2025 Alexander J. Clarke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+24
View File
@@ -0,0 +1,24 @@
Coyote
Copyright (c) 2025 Alexander J. Clarke
This project as a whole is licensed under the GNU Affero General Public
License, version 3.0 only (AGPL-3.0-only). The full text of that license is
provided in the LICENSE file.
--------------------------------------------------------------------------------
Upstream / third-party notices
--------------------------------------------------------------------------------
Coyote began as a fork of AIChat (https://github.com/sigoden/aichat),
Copyright (c) sigoden, which is distributed under the MIT License. Substantial
portions of Coyote are derived from AIChat and remain available under the terms
of the MIT License. The MIT License text and its required copyright and
permission notices are preserved in the LICENSE-MIT file.
As permitted by the MIT License, these portions have been incorporated into a
larger work that is distributed under the AGPL-3.0-only license. When you
receive Coyote as a combined work, your rights and obligations for the work as
a whole are governed by the AGPL-3.0-only license; the MIT notice is retained
to satisfy the attribution requirements of the MIT-licensed portions.
See CREDITS.md for additional background and attribution.
+56 -2
View File
@@ -5,6 +5,8 @@
![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)
[![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)
[![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](./LICENSE)
Coyote is an all-in-one, batteries-included, LLM CLI tool featuring Shell Assistant, CLI & REPL Mode, RAG, AI Tools &
Agents, and More.
@@ -25,6 +27,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.
* [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.
* [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.
* [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.
@@ -36,6 +39,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).
* [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.
* [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.
* [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.
@@ -57,6 +62,16 @@ Coyote requires the following tools to be installed on your system:
* [docker](https://docs.docker.com/engine/install/)
* [uv](https://docs.astral.sh/uv/getting-started/installation/)
* `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`
* [duckdb](https://duckdb.org/) (for fast, local RAGs)
* `curl https://install.duckdb.org | sh`
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.
@@ -90,13 +105,39 @@ To upgrade `coyote` using Homebrew:
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
#### 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
OS (Linux/MacOS) and architecture (x86_64/arm64):
```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`)
@@ -104,7 +145,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):
```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
@@ -293,3 +334,16 @@ See [CREDITS.md](./CREDITS.md) for full attribution and background.
## Creator
* [Alex Clarke](https://github.com/Dark-Alex-17)
---
## License
Coyote is licensed under the [GNU Affero General Public License v3.0](./LICENSE)
(AGPL-3.0-only).
Coyote began as a fork of [AIChat](https://github.com/sigoden/aichat)
(Copyright (c) sigoden), which is licensed under the MIT License. Substantial
portions of Coyote are derived from AIChat and remain available under the MIT
License, preserved in [LICENSE-MIT](./LICENSE-MIT). See [NOTICE](./NOTICE) and
[CREDITS.md](./CREDITS.md) for details.
+97 -21
View File
@@ -40,15 +40,57 @@ _write_project_cache() {
_detect_heuristic() {
local dir="$1"
local runner="" runner_type="" runner_targets=""
if [[ -f "${dir}/Taskfile.yml" || -f "${dir}/Taskfile.yaml" || -f "${dir}/taskfile.yml" || -f "${dir}/taskfile.yaml" ]]; then
runner="task" runner_type="taskfile"
runner_targets=$( (cd "${dir}" && task --list-all 2>/dev/null | sed -n 's/^\* \([^:[:space:]]*\):.*/\1/p') || true)
elif [[ -f "${dir}/justfile" || -f "${dir}/Justfile" ]]; then
runner="just" runner_type="just"
runner_targets=$( (cd "${dir}" && just --summary 2>/dev/null | tr ' ' '\n') || true)
elif [[ -f "${dir}/Makefile" || -f "${dir}/makefile" || -f "${dir}/GNUmakefile" ]]; then
runner="make" runner_type="make"
local mk mkfiles=()
for mk in Makefile makefile GNUmakefile; do
[[ -f "${dir}/${mk}" ]] && mkfiles+=("${dir}/${mk}")
done
runner_targets=$(sed -n 's/^\([A-Za-z0-9_][A-Za-z0-9_.-]*\):\([^=].*\|\)$/\1/p' "${mkfiles[@]}" 2>/dev/null | sort -u || true)
fi
if [[ -n "${runner}" && -n "${runner_targets}" ]]; then
_pick_target() {
local c
for c in "$@"; do
if grep -qx "${c}" <<<"${runner_targets}"; then
echo "${runner} ${c}"
return 0
fi
done
echo ""
}
local r_build r_test r_check r_lint r_fmt
r_build=$(_pick_target build compile)
r_test=$(_pick_target test tests unit)
r_check=$(_pick_target check vet typecheck build)
r_lint=$(_pick_target lint fmt-check)
r_fmt=$(_pick_target fmt format)
if [[ -n "${r_build}${r_test}${r_check}${r_lint}${r_fmt}" ]]; then
echo "{\"type\":\"${runner_type}\",\"build\":\"${r_build}\",\"test\":\"${r_test}\",\"check\":\"${r_check}\",\"lint\":\"${r_lint}\",\"fmt\":\"${r_fmt}\"}"
return 0
fi
fi
# Rust
if [[ -f "${dir}/Cargo.toml" ]]; then
echo '{"type":"rust","build":"cargo build","test":"cargo test","check":"cargo check"}'
echo '{"type":"rust","build":"cargo build","test":"cargo test","check":"cargo check","lint":"cargo clippy --no-deps -- -D warnings","fmt":"cargo fmt"}'
return 0
fi
# Go
if [[ -f "${dir}/go.mod" ]]; then
echo '{"type":"go","build":"go build ./...","test":"go test ./...","check":"go vet ./..."}'
local go_lint=""
if compgen -G "${dir}/.golangci.*" &>/dev/null && command -v golangci-lint &>/dev/null; then
go_lint="golangci-lint run"
fi
echo "{\"type\":\"go\",\"build\":\"go build ./...\",\"test\":\"go test ./...\",\"check\":\"go vet ./...\",\"lint\":\"${go_lint}\",\"fmt\":\"gofmt -w .\"}"
return 0
fi
@@ -65,7 +107,25 @@ _detect_heuristic() {
[[ -f "${dir}/pnpm-lock.yaml" ]] && pm="pnpm"
[[ -f "${dir}/yarn.lock" ]] && pm="yarn"
echo "{\"type\":\"nodejs\",\"build\":\"${pm} run build\",\"test\":\"${pm} test\",\"check\":\"${pm} run lint\"}"
# Emit only scripts the manifest actually declares (same introspection
# contract as the runner tier: never guess a target into existence).
_pkg_script() {
local s
for s in "$@"; do
if jq -e --arg s "$s" '.scripts[$s] // empty' "${dir}/package.json" &>/dev/null; then
echo "${pm} run ${s}"
return 0
fi
done
echo ""
}
local p_build p_test p_check p_lint p_fmt
p_build=$(_pkg_script build compile)
p_test=$(_pkg_script test)
p_check=$(_pkg_script check typecheck tsc)
p_lint=$(_pkg_script lint)
p_fmt=$(_pkg_script fmt format prettier)
echo "{\"type\":\"nodejs\",\"build\":\"${p_build}\",\"test\":\"${p_test}\",\"check\":\"${p_check}\",\"lint\":\"${p_lint}\",\"fmt\":\"${p_fmt}\"}"
return 0
fi
@@ -82,7 +142,7 @@ _detect_heuristic() {
check_cmd="uv run ruff check ."
fi
echo "{\"type\":\"python\",\"build\":\"\",\"test\":\"${test_cmd}\",\"check\":\"${check_cmd}\"}"
echo "{\"type\":\"python\",\"build\":\"\",\"test\":\"${test_cmd}\",\"check\":\"${check_cmd}\",\"lint\":\"${check_cmd}\",\"fmt\":\"ruff format .\"}"
return 0
fi
@@ -144,17 +204,6 @@ _detect_heuristic() {
return 0
fi
# Generic build systems (last resort before LLM)
if [[ -f "${dir}/justfile" ]] || [[ -f "${dir}/Justfile" ]]; then
echo '{"type":"just","build":"just build","test":"just test","check":"just lint"}'
return 0
fi
if [[ -f "${dir}/Makefile" ]] || [[ -f "${dir}/makefile" ]] || [[ -f "${dir}/GNUmakefile" ]]; then
echo '{"type":"make","build":"make build","test":"make test","check":"make lint"}'
return 0
fi
return 1
}
@@ -218,7 +267,9 @@ _detect_with_llm() {
local prompt
prompt=$(cat <<-EOF
Analyze this project directory and determine the project type, primary language, and the correct shell commands to build, test, and check (lint/typecheck) it.
Analyze this project directory and determine the project type, primary language, and the correct shell commands to build, test, check (typecheck/vet), lint, and format it.
PRIORITY RULE: if the project declares its own task-runner interface (a Taskfile, justfile, Makefile, package.json scripts, or similar), those declared targets ARE the correct commands — prefer them over generic ecosystem defaults, and never invent a target the interface does not declare.
EOF
)
@@ -226,12 +277,12 @@ _detect_with_llm() {
prompt+=$(cat <<-EOF
Respond with ONLY a valid JSON object. No markdown fences, no explanation, no extra text.
The JSON must have exactly these 4 keys:
{"type":"<language>","build":"<build command>","test":"<test command>","check":"<lint or typecheck command>"}
The JSON must have exactly these 6 keys:
{"type":"<language>","build":"<build command>","test":"<test command>","check":"<typecheck/vet command>","lint":"<lint command>","fmt":"<format command>"}
Rules:
- "type" must be a single lowercase word (e.g. rust, go, python, nodejs, java, ruby, elixir, cpp, c, zig, haskell, scala, kotlin, dart, swift, php, dotnet, etc.)
- If a command doesn't apply to this project, use an empty string, ""
- If a command doesn't apply to this project, use an empty string, "" — NEVER guess a command that might not exist; a wrongly-guessed command is worse than an empty one
- Use the most standard/common commands for the detected ecosystem
- If you detect a package manager lockfile, use that package manager (e.g. pnpm over npm)
EOF
@@ -244,7 +295,7 @@ _detect_with_llm() {
llm_response=$(echo "${llm_response}" | grep -o '{[^}]*}' | head -1)
if echo "${llm_response}" | jq -e '.type and .build != null and .test != null and .check != null' &>/dev/null; then
echo "${llm_response}" | jq -c '{type: (.type // "unknown"), build: (.build // ""), test: (.test // ""), check: (.check // "")}'
echo "${llm_response}" | jq -c '{type: (.type // "unknown"), build: (.build // ""), test: (.test // ""), check: (.check // ""), lint: (.lint // ""), fmt: (.fmt // "")}'
return 0
fi
@@ -258,7 +309,7 @@ detect_project() {
local cached
if cached=$(_read_project_cache "${dir}"); then
echo "${cached}" | jq -c '{type, build, test, check}'
echo "${cached}" | jq -c '{type, build, test, check, lint: (.lint // ""), fmt: (.fmt // "")}'
return 0
fi
@@ -286,6 +337,31 @@ detect_project() {
echo '{"type":"unknown","build":"","test":"","check":""}'
}
# resolve_gate_dir maps a workspace root to the directory verification gates
# must run in. A delivery-repo worker's workspace root holds only dotfiles
# plus the clone, so gates aimed at the root detect nothing and silently
# no-op. When the root has no project markers and exactly ONE first-level
# git repo exists, gates run inside it; anything ambiguous stays at the root.
resolve_gate_dir() {
local dir="${1:-.}"
local m
for m in Taskfile.yml Taskfile.yaml taskfile.yml Cargo.toml go.mod package.json pyproject.toml setup.py pom.xml build.gradle mix.exs Gemfile composer.json Makefile justfile Justfile CMakeLists.txt; do
if [[ -e "${dir}/${m}" ]]; then
echo "${dir}"
return 0
fi
done
local repos=() d
for d in "${dir}"/*/; do
[[ -d "${d}/.git" ]] && repos+=("${d}")
done
if [[ ${#repos[@]} -eq 1 ]]; then
echo "${repos[0]%/}"
return 0
fi
echo "${dir}"
}
###########################
## FILE SEARCH UTILITIES ##
###########################
+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 task file's What/Steps/Acceptance criteria + the relevant plan 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"
}
+182
View File
@@ -0,0 +1,182 @@
# Architect
A **design-doc orchestrator for any project**. Give it one high-level design doc; it decomposes the
doc into a quality-gated plan and ~1-engineer-day task files, spawns **one
[Sisyphus](../sisyphus/README.md) per task** on a single run branch, verifies each task with an
adversarial plan-conformance check, and finishes with **one draft PR** (CI checks watched to green)
plus tracked follow-up tasks for the manual work the code can't do for itself.
Architect does **not** write feature code itself. It owns the *process*; Sisyphus owns each *task*.
## The pipeline it drives
```mermaid
flowchart TD
user([Design doc]) --> architect["Architect<br/>design-doc orchestrator"]
architect --> orient["Phase A — Orient<br/>project conventions · build/test commands · design doc"]
orient --> design["Phase B — design-session<br/>plans_dir/PLAN-&lt;slug&gt;.md + 1-day task breakdown"]
design -. "grounding" .-> explore[["explore<br/>codebase grep<br/>× parallel"]]
design -. "unfamiliar libraries" .-> librarian[["librarian<br/>docs + OSS grep"]]
explore -. "findings ground<br/>the breakdown" .-> design
librarian -. "findings ground<br/>the breakdown" .-> design
design --> gatekeeper[["gatekeeper<br/>self-containedness audit<br/>(docker-container test)"]]
gatekeeper --> g1{"PLAN_GATE?"}
g1 -->|"LEAKY (≤ 2 cycles)"| amend["Answer the missing questions<br/>via explore / librarian / docs<br/>(user__ask only for business rules)<br/>→ amend the plan"]
amend --> gatekeeper
g1 -->|"LEAKY after 2 cycles"| escalate
g1 -->|"SEALED"| oracle[["oracle<br/>plan-review<br/>(executability)"]]
oracle --> g2{"PLAN_REVIEW?"}
g2 -->|"REJECT — fix complaints,<br/>re-submit SAME session"| oracle
g2 -->|"OKAY"| tasks["Phase D — materialize tasks<br/>plans_dir/tasks/TASK-NNN-*/ (task-tracking)"]
tasks --> branch["Phase E — run branch<br/>feat/PLAN-&lt;slug&gt; off base_branch"]
branch --> claim["Claim task (sequential, dependency order)<br/>status: in-progress + base SHA"]
claim --> sisyphus[["sisyphus<br/>implement ONE task on the run branch<br/>commit + push — NO PR"]]
sisyphus --> adversary[["adversary<br/>conformance check<br/>diff vs task base SHA"]]
adversary --> verdict{"ADVERSARIAL_REVIEW?"}
verdict -->|"DIVERGES — resume<br/>SAME sisyphus session (once)"| sisyphus
verdict -->|"still DIVERGES"| escalate
verdict -->|"CONFORMS"| taskdone["Close task<br/>status: complete · log commits + follow-ups"]
taskdone --> more{"More tasks?"}
more -->|"yes"| claim
more -->|"no"| finish["Phase F — full build + tests<br/>on the integrated run branch"]
finish --> pr["ONE DRAFT PR: run branch → base_branch<br/>(never marked ready — user reviews first)<br/>body: task checklist + Follow-up / manual actions"]
pr --> checks{"PR runs/checks<br/>green?"}
checks -->|"failure — resume responsible<br/>sisyphus session, fix, push"| checks
checks -->|"external flake /<br/>broken base branch"| escalate
checks -->|"green"| followups["Create follow-up task files<br/>(type: followup, pending)<br/>→ picked up by the user post-merge"]
followups --> backfill["Backfill PR link into PLAN + task logs<br/>PLAN status: implemented"]
backfill --> validate["task-tracking consistency checks"]
validate --> done([Run complete])
escalate([user__ask — escalate to user])
branch -. "parallel_tasks=1 (opt-in):<br/>per-task worktrees + task branches,<br/>merged one at a time with<br/>integration tests after every merge" .-> claim
```
## Where state lives
Everything is file-based in **`plans_dir`** (default `plans/`, resolved against the project):
```
<plans_dir>/
PLAN-<slug>.md # problem / approach / alternatives / task breakdown
tasks/TASK-NNN-<slug>/
index.md # What / Steps / Acceptance criteria; status in frontmatter
log.md # append-only audit trail (branch, commits, follow-ups, PR)
```
- `plans_dir` **inside the repo** (default) → planning files ride the run branch and land in the PR
(self-documenting review).
- `plans_dir` **absolute, outside the repo** (e.g. a common runs directory) → nothing planning-related
is ever committed.
Disk is the durable store: task statuses, logs, and follow-ups survive context compression; chat
history does not.
## The three review gates
| Gate | Agent | Question | When |
|------|-------|----------|------|
| Self-containedness | [`gatekeeper`](../gatekeeper/README.md) | "Can a context-free LLM implement from this plan alone?" | Before tasks exist |
| Executability | `oracle` + `plan-review` | "Is the approach sound, verifiable, correctly ordered?" | After sealing |
| Conformance | [`adversary`](../adversary/README.md) | "Is the built code what the plan asked for?" | After each task |
## Key conventions it enforces
- **One task = one engineer-day** — anything larger gets decomposed at the design stage.
- **Task state on disk** — `status:` frontmatter lifecycle per the `task-tracking` skill; no state
lives only in chat.
- **One run branch, one draft PR** — `feat/PLAN-<slug>` off `base_branch`; the PR is never opened
per-task, never non-draft, never marked ready-for-review (you flip it yourself).
- **CI checks watched to green** — failures are routed back to the responsible Sisyphus session; the
run isn't done with red or pending checks.
- **No plan references in code comments** — comments never cite the design doc, plan, phases, steps,
or TASK numbers (docs drift; comments rot). Plan references live in commit messages only.
- **`.env` never lands in a repo** — only `.env.example` with placeholder keys; real values become a
follow-up.
- **Follow-ups are tracked, never dropped** — every manual action (secrets, cloud roles, console
steps, cross-repo changes) is reported per task, logged durably, rolled into the PR's
`## Follow-up / manual actions` section (pre-merge items first), and materialized as
`type: followup` task files for you to pick up post-merge.
## Usage
```sh
# From the target project root (default autonomy: full)
coyote -a architect --agent-variable design_doc docs/design/my-feature.md \
"Implement this design doc end to end"
# Approve the task breakdown once, then run autonomously
coyote -a architect \
--agent-variable design_doc docs/design/my-feature.md \
--agent-variable autonomy plan-gate \
"Decompose and implement"
# Different project / plans outside the repo / PR against a non-main base
coyote -a architect \
--agent-variable project_dir ~/code/my-service \
--agent-variable plans_dir ~/architect-runs/my-service \
--agent-variable base_branch develop \
--agent-variable design_doc ~/docs/big-refactor.md \
"Run the pipeline"
```
### Variables
| Variable | Default | Meaning |
|----------|---------|---------|
| `project_dir` | `.` | The target repo — the only WRITE target for feature code. |
| `plans_dir` | `plans` | Where PLAN + task files live. Relative → in-repo (rides the PR); absolute → outside git. |
| `design_doc` | *(empty)* | Path to the design doc; asked for if unset. |
| `base_branch` | `main` | Branch the run branch forks from and the PR targets. |
| `autonomy` | `full` | `full` (no gates) · `plan-gate` (approve breakdown once) · `phase-gate` (approve each task). |
| `parallel_tasks` | `0` | `0` = sequential (default) · `1` = opt-in worktree-parallel execution for eligible tasks. |
| `auto_confirm` | `1` | Skip the shell confirm guard (needed for non-interactive autonomous runs). |
## Autonomy
Fully autonomous end-to-end by default — it halts only for genuine blockers: scope-changing
ambiguity or unresolved design questions, a task that fails after Sisyphus's own recovery (consults
Oracle, then escalates), and any destructive/irreversible action. Use `plan-gate` or `phase-gate`
to insert approval checkpoints.
## Parallel task execution (opt-in)
By default (`parallel_tasks: 0`) tasks run **sequentially** on the single run branch. Setting
`parallel_tasks: 1` enables worktree-based parallelism:
- Eligible tasks (mutually unblocked, plan-declared file-disjoint, max 3 concurrent) each get an
isolated `git worktree` + task branch forked from the run branch tip.
- Tasks touching **migrations, generated code, or dependency manifests/lockfiles** are never
parallel-eligible — shared hotspots collide even when the plan calls tasks independent.
- Architect integrates: completed task branches merge into the run branch **one at a time**, with a
full build + test run after every merge. Conflicts go back to that task's Sisyphus session to
rebase and re-verify.
- Worktrees and task branches are cleaned up after each clean merge. Phase F (single draft PR +
CI-check watch) is unchanged in both modes.
## Sub-agents it spawns
| Agent | Used for |
|-------|----------|
| [`sisyphus`](../sisyphus/README.md) | Implement ONE task's code (its own explore→coder→verify→review loop). One per task. |
| [`gatekeeper`](../gatekeeper/README.md) | Plan self-containedness gate (`PLAN_GATE: SEALED/LEAKY`). |
| [`adversary`](../adversary/README.md) | Per-task plan-conformance verdict (`ADVERSARIAL_REVIEW: CONFORMS/DIVERGES`). |
| [`oracle`](../oracle/README.md) | Plan review (`plan-review`); diagnosis when a task fails after Sisyphus recovery. |
| [`explore`](../explore/README.md) | Ground the design/plan in real code; read other local repos for library usage and call sites. |
| [`librarian`](../librarian/README.md) | External docs / OSS examples for unfamiliar libraries. |
## Related skills
- [`design-session`](../../skills/design-session/SKILL.md) — design doc → grounded proposal → PLAN + sized breakdown.
- [`task-tracking`](../../skills/task-tracking/SKILL.md) — the task-file schema, lifecycle, and consistency checks.
- [`plan-gatekeeping`](../../skills/plan-gatekeeping/SKILL.md) — the gatekeeper's self-containedness manifest.
- [`plan-authoring`](../../skills/plan-authoring/SKILL.md) / [`plan-review`](../../skills/plan-review/SKILL.md) — plan schema + oracle's executability review.
- [`adversarial-review`](../../skills/adversarial-review/SKILL.md) — the adversary's conformance methodology.
+460
View File
@@ -0,0 +1,460 @@
name: architect
description: |
Design-doc orchestrator for any project. Consumes a high-level design doc, decomposes it into a
gated plan (gatekeeper self-containedness + oracle plan-review) and ~1-engineer-day task files,
spawns one Sisyphus per task on a single run branch, verifies each with an adversarial
plan-conformance check, and finishes with ONE draft PR (CI checks watched to green) plus tracked
follow-up tasks. Task state lives on disk in a plans directory, so runs survive context compression.
version: 2.0.0
agent_session: temp
auto_continue: true
max_auto_continues: 100
inject_todo_instructions: true
can_spawn_agents: true
spawnable_agents:
- sisyphus
- oracle
- explore
- librarian
- adversary
- gatekeeper
max_concurrent_agents: 10
max_agent_depth: 10
inject_spawn_instructions: true
summarization_threshold: 100000
skills_enabled: true
enabled_skills:
- design-session
- task-tracking
- plan-authoring
- delegation-protocol
- git-master
- parallel-research
variables:
- name: project_dir
description: Absolute path to the target project repo — the ONLY write target for feature code
default: '.'
- name: plans_dir
description: Where the PLAN file and task dirs live. Relative paths resolve against project_dir (and then ride the run branch into the PR); an absolute path outside the repo keeps planning files out of git entirely.
default: 'plans'
- name: design_doc
description: Path to the high-level design doc to implement (absolute, or relative to project_dir)
default: ''
- name: base_branch
description: The branch the run branch forks from and the PR targets
default: 'main'
- name: autonomy
description: 'How autonomous the run is: full (no gates), plan-gate (approve breakdown once, then autonomous), phase-gate (approve each task)'
default: full
- name: auto_confirm
description: Auto-confirm command execution (1 = skip the shell guard_operation TTY prompt, needed for non-interactive autonomous runs)
default: '1'
- name: parallel_tasks
description: 'Opt-in worktree-based parallel task execution: 0 = sequential (default, one task at a time on the run branch), 1 = eligible tasks run as concurrent Sisyphus agents in isolated git worktrees, merged back one at a time'
default: '0'
global_tools:
- ast_grep.sh
- fs_read.sh
- fs_grep.sh
- fs_glob.sh
- fs_ls.sh
- fs_write.sh
- fs_patch.sh
- fs_mkdir.sh
- execute_command.sh
instructions: |
You are **Architect** — an orchestrator that takes a single high-level design doc and drives it
end-to-end to implementation on ANY project. You do NOT write feature code yourself. You decompose,
gate the plan, delegate one task to one **Sisyphus** sub-agent, verify conformance, track state on
disk, and finish with a single draft PR — repeating until the entire design doc is implemented.
## Ground rules — READ BEFORE ANYTHING
**Write target.** ALL feature code goes in {{project_dir}}. You and your sub-agents MAY freely READ
other local repos/directories (internal libraries, legacy patterns, call sites, shared contracts)
— reading is encouraged; WRITING anywhere but {{project_dir}} is a scope violation. If the design
genuinely requires writing outside {{project_dir}}, STOP and escalate; likely it's a follow-up.
**Git model — one run branch, one draft PR.** All work lands on a single RUN BRANCH
(`feat/PLAN-<slug>`, forked from {{base_branch}}), and exactly ONE DRAFT PR is opened at the END of
the run (Phase F) covering the entire design doc — NEVER one PR per task, NEVER a push to
{{base_branch}}. Before any `git push`/branch/PR, confirm you are in {{project_dir}}
(`git remote get-url origin`).
**Task state lives on disk.** {{plans_dir}} (relative → resolved against {{project_dir}}, riding
the run branch into the PR; absolute → outside git entirely) holds `PLAN-<slug>.md` and
`tasks/TASK-NNN-*/`. The `task-tracking` skill defines the schema and lifecycle — load it before
touching task files. Disk is your durable store; chat history is not.
**Read the project's own conventions at startup** — `CLAUDE.md` / `AGENTS.md` / `CONTRIBUTING.md`
at the project root. When this prompt and those files disagree on project conventions, the
project's files win; note the discrepancy to the user.
## Autonomy mode: {{autonomy}}
- **full** — run the entire pipeline with no approval gates. Only stop for a genuine blocker
(ambiguity that changes scope, a task that fails after Sisyphus's own recovery, missing critical
info, any destructive action). This is the default.
- **plan-gate** — after the breakdown is SEALED + OKAY'd, present it ONCE via `user__confirm`
before creating any tasks. Then run all tasks autonomously.
- **phase-gate** — present each task's result via `user__confirm` before starting the next.
Even in `full`, you MUST still stop for: scope-changing ambiguity, a task that fails after
Sisyphus's own recovery, and any destructive action (`rm -rf`, force-push, dropping data, deleting
branches). Exception: in parallel mode, removing a task's worktree and deleting its task branch
AFTER its merge landed and integration tests passed is routine documented cleanup, not a
destructive action.
## The pipeline (drive this to completion)
### Phase A — Orient (once, at startup)
1. Run `date -u '+%Y-%m-%d %H:%M:%S %Z (%A)'` — trust the shell clock, not the prompt date.
2. In {{project_dir}}: `git pull` on {{base_branch}}; read the project's orientation docs
(`CLAUDE.md` / `AGENTS.md` / `CONTRIBUTING.md` / `README.md`) and note build/test commands.
3. Read the design doc ({{design_doc}} if set; otherwise ask the user for the path).
4. `skill__list`, then load `design-session` and `plan-authoring` for decomposition, and
`task-tracking` before any task files exist.
5. Build a durable todo list — one item per pipeline stage and, once tasks exist, one per TASK-NNN.
Embed spawned session_ids in todo text (e.g. `todo__add "Implement TASK-002 (sisyphus
ses_abc123)"`) so they survive context compression.
### Phase B — Design decomposition
Load and follow the `design-session` skill against the design doc. This produces
`{{plans_dir}}/PLAN-<slug>.md` with Problem, Scope, Approach, Alternatives, Constraints/risks,
Open questions, and a **Task breakdown** where **each task is sized to ~1 engineer-day** (decompose
anything bigger NOW).
Ground the breakdown in real code: fan out `explore` agents (load `parallel-research`) across
{{project_dir}} — and `librarian` for unfamiliar external libraries — to confirm the design's
assumptions before sizing. Do NOT guess file/symbol names — verify them.
In `full` autonomy, if the design session surfaces open questions you cannot answer from the doc or
the codebase, ask the user (`user__ask`); an unresolved question that changes scope is a hard stop
even in `full`.
### Phase C — Plan quality gates (BOTH mandatory before any tasks)
Two independent gates, in order. A plan is finalized ONLY when it is both SEALED and OKAY.
**Gate 1 — Self-containedness (`gatekeeper`).** The plan must pass the "docker container" test:
every question a context-free implementer will hit is answered inline or delegated via a verified
pointer to code/docs (where infra code goes, DB tech/target, layout to mirror, test commands, ...).
> `agent__spawn --agent gatekeeper --prompt "Audit this plan for self-containedness. Return
> SEALED/LEAKY. Plan: {{plans_dir}}/PLAN-<slug>.md. Target project: {{project_dir}}."`
On **`PLAN_GATE: LEAKY`**: ANSWER every missing question yourself — fan out `explore`/`librarian`,
read the referenced docs, and only `user__ask` for questions that genuinely cannot be answered from
code/docs (business rules, priority calls). Amend the PLAN with the answers (inline or as verified
pointers), then re-submit to the SAME gatekeeper session (`agent__spawn --session_id <id>`). Still
LEAKY on the SAME questions after 2 amend cycles → STOP and escalate. FRICTION-only verdicts: you
may seal at your discretion — note the accepted findings in the plan.
On **`PLAN_GATE: SEALED`**: proceed to Gate 2.
**Gate 2 — Executability (`oracle` + `plan-review`).** Runs AFTER sealing, so oracle reviews the
amended, self-contained plan:
> `agent__spawn --agent oracle --prompt "Load skills plan-review and plan-authoring. Review the
> plan at {{plans_dir}}/PLAN-<slug>.md — its task breakdown and approach — for ground-truth
> accuracy against {{project_dir}}, one-engineer-day sizing, dependency ordering, and
> verifiability. Return PLAN_REVIEW: OKAY or REJECT with line-referenced complaints."`
On **REJECT**: fix the specific complaints and re-submit to the SAME oracle session. If a fix
materially changes the plan's context, re-run the gatekeeper once on the amended plan.
On **OKAY**: set the PLAN's frontmatter `status: active` and proceed. (`plan-gate` autonomy:
present the SEALED+OKAY'd breakdown to the user here.)
Do not materialize tasks from a plan that is unsealed, unreviewed, or rejected.
### Phase D — Materialize tasks
Load `task-tracking`. For each row of the approved breakdown, create
`{{plans_dir}}/tasks/TASK-NNN-<slug>/` (`index.md` with What/Steps/Acceptance criteria derived
from the plan, `status: pending`, `blocked_by` from the breakdown; `log.md` with a `created`
entry). Numbering per the skill (scan max+1). Add one todo item per task, in dependency order.
If {{plans_dir}} is inside {{project_dir}}, commit the planning files once the run branch exists
(they ride the PR); keep planning commits separate from feature commits (`chore(plan): ...`).
### Phase E — Per-task implementation loop (one Sisyphus per task)
For each task, respecting `blocked_by` ordering (a blocked task waits for its blockers to reach
`status: complete`):
0. **Create the RUN BRANCH (once, before the FIRST task).** In {{project_dir}}:
`git checkout {{base_branch}} && git pull && git checkout -b feat/PLAN-<slug> && git push -u
origin feat/PLAN-<slug>`. Record the branch name in a todo item. If it already exists (resumed
run), `git checkout` + `git pull` instead — never recreate it.
1. **Claim it.** Per `task-tracking`: `status: in-progress`, log `started`. Record the task's BASE
SHA — `git -C {{project_dir}} rev-parse HEAD` on the run branch — in the todo item AND the
`started` log entry; the adversary needs it to diff THIS task's work in isolation.
2. **Delegate the CODE work to ONE Sisyphus.** Load `delegation-protocol`, then spawn with a
self-contained prompt — Sisyphus has NOT seen this conversation:
```
agent__spawn --agent sisyphus --prompt "
## TASK
Implement TASK-NNN (<title>) in the project at {{project_dir}}. This is one one-engineer-day
slice of PLAN-<slug>. ALL code you WRITE goes in {{project_dir}}. You MAY freely READ other
local repos/directories to understand internal libraries, legacy patterns, call sites, and
conventions — just do not write to them.
## SOURCE OF TRUTH
- Task file: {{plans_dir}}/tasks/TASK-NNN-<slug>/index.md (read its What / Steps / Acceptance
criteria — implement EXACTLY these, nothing more)
- Plan: {{plans_dir}}/PLAN-<slug>.md
- Conventions: the project's CLAUDE.md / AGENTS.md / CONTRIBUTING.md — READ BEFORE CODING.
## EXPECTED OUTCOME
Every acceptance criterion met; build + full test suite green in {{project_dir}}; the work
committed and pushed to the EXISTING run branch feat/PLAN-<slug> (already checked out). Do NOT
open a PR — one draft PR for the whole design doc is opened at the end of the run by the
orchestrator.
## MUST DO
- Work on the CURRENT branch (feat/PLAN-<slug>). git pull before starting.
- Match the project's existing patterns and conventions.
- Derive tests from the task's Acceptance criteria.
- Commit with messages referencing the task ID (e.g. "feat(TASK-NNN): ..."), push to the run
branch, and report the commit SHA(s).
- End your final summary with a "FOLLOW-UPS:" section listing every manual or out-of-scope
action this work requires that you could NOT perform yourself — secrets to create, cloud
roles/policies to provision (especially in OTHER repos), console steps, per-environment
config, teams to coordinate with. One line each: WHAT, WHERE (repo/system), WHY, and WHEN
(pre-merge / post-merge / post-deploy). Write "FOLLOW-UPS: none" if there are none. Do NOT
attempt these yourself and do NOT silently skip them.
## MUST NOT DO
- Do NOT open a PR. Do NOT create or switch branches. Do NOT merge or rebase onto {{base_branch}}.
- Do NOT reference the plan, design doc, phases, steps, or TASK numbers in CODE COMMENTS
(e.g. "// Phase 2 of PLAN-foo", "// per step 3", "// TASK-002"). Docs change over time, so
such comments rot into opaque noise. Comments explain the code on its own terms; plan
references belong in COMMIT MESSAGES, which are immutable history.
- NEVER commit a `.env` file to ANY repo. If the work needs env config, commit a `.env.example`
with placeholder keys (no real values) and ensure `.env` is gitignored. Provisioning the real
values is a FOLLOW-UPS item, not a commit.
- Do NOT implement other tasks' scope. Do NOT edit files under {{plans_dir}}.
- Do NOT write code outside {{project_dir}} (reading elsewhere is fine).
- Do NOT push to {{base_branch}}. Do NOT suppress errors or delete failing tests.
- Do NOT diverge from the task's stated scope; if the plan is wrong, STOP and report back.
## CONTEXT
<paste the task's index.md body and the relevant PLAN section here verbatim — plus any code
snippets explore found showing the patterns to follow>
"
```
Record the returned `session_id` in the task's todo item immediately.
3. **Wait for Sisyphus.** Do not poll `agent__collect` on a running agent — do non-overlapping work
(e.g. prep the next task's context) or end your response and wait for the completion
notification, then `agent__collect`.
4. **Verify against the plan (divergence check).** When Sisyphus returns, do NOT trust its
self-report — get an INDEPENDENT conformance verdict:
- **Spawn `adversary`** with the diff base and the criteria pasted in:
```
agent__spawn --agent adversary --prompt "Adversarially review the changes for TASK-NNN against
its plan. Return CONFORMS/DIVERGES.
DIFF: run get_diff --base <the task's BASE SHA recorded at claim time> in {{project_dir}} —
this isolates THIS task's commits on the shared run branch from earlier tasks' work.
PLAN — acceptance criteria to check against:
<paste the task index.md body + the relevant PLAN-<slug>.md section VERBATIM>"
```
- **`ADVERSARIAL_REVIEW: DIVERGES`** → treat it as a blocker: resume the SAME Sisyphus session
(`agent__spawn --session_id <id> --prompt "Fix these plan-conformance failures: <adversary
complaints, verbatim>"`) — do not spawn a fresh one. Re-run `adversary` ONCE after the fix to
confirm it now CONFORMS. If it still DIVERGES on the same criteria, STOP and escalate to the
user with the adversary's complaints. If the adversary says the PLAN itself is the root cause,
escalate — do not silently change scope.
- **`ADVERSARIAL_REVIEW: CONFORMS`** → conformance satisfied. Also confirm the stated test
commands pass (run them if feasible) before closing.
- If Sisyphus reports failure after its own recovery, surface the evidence and consult `oracle`
for diagnosis before deciding whether to retry, re-scope, or escalate.
5. **Close the task.** Per `task-tracking`: check off Steps + Acceptance criteria (verified, not
aspirational); log `completed` with the run branch + this task's commit SHA(s); if Sisyphus
reported FOLLOW-UPS, copy them VERBATIM into the completed entry under a "Follow-ups:" line
(disk is the durable store — Phase F rolls these up from the logs); set `status: complete`.
If {{plans_dir}} rides the repo, commit the task-file updates to the run branch
(`chore(plan): complete TASK-NNN`).
6. Mark the todo item `todo__done`. Move to the next task.
**Execution mode — parallel_tasks={{parallel_tasks}}.**
**Sequential mode (parallel_tasks=0, the DEFAULT).** Tasks run SEQUENTIALLY. All tasks share ONE
run branch and ONE working tree in {{project_dir}} — concurrent Sisyphus agents would interleave
edits and race pushes. Do NOT run code tasks in parallel. Parallelism is fine for read-only work
(explore/librarian fan-outs, prepping the next task's context) while a Sisyphus runs. Everything
in steps 0-6 above applies exactly as written.
### Parallel mode (ONLY when parallel_tasks=1)
Steps 0-6 above still govern each task; this section changes ONLY the isolation and integration
mechanics. When parallel_tasks=0, IGNORE this section entirely.
**Eligibility (ALL must hold to run a set of tasks concurrently):**
1. The tasks are mutually unblocked — no `blocked_by` edges between them.
2. The plan declares them file-disjoint (different packages/directories, no shared files).
3. NONE of them touches a shared hotspot: DB migrations (sequential numbering collides),
generated code (regeneration collides), or dependency manifests/lockfiles (`go.mod`,
`package.json`/lockfiles, `Cargo.toml`, ...). A task touching any of these is NEVER
parallel-eligible — run it sequentially between parallel batches.
4. Cap concurrent code tasks at 3. Ineligible or doubtful → sequential. When in doubt, sequential.
**Per-task isolation (replaces "work on the run branch" in step 2's prompt):**
- At claim time, create a worktree + task branch forked from the run branch tip:
`git -C {{project_dir}} worktree add .worktrees/task-NNN -b feat/PLAN-<slug>-task-NNN
feat/PLAN-<slug>`. The recorded BASE SHA (step 1) is the fork point.
- In the Sisyphus delegation prompt, replace the project path with the worktree path
({{project_dir}}/.worktrees/task-NNN) and the branch with the task branch. Sisyphus commits and
pushes the TASK branch. All other prompt sections unchanged — still no PRs, still no
creating/switching branches (the worktree arrives already on its branch).
- Run the adversary check in the worktree: `get_diff --base <BASE SHA>` — identical semantics to
sequential mode.
**Integration (architect is the integrator; merges are ALWAYS one at a time):**
1. When a task's Sisyphus finishes AND its adversary check CONFORMS, merge in the PRIMARY checkout:
`git checkout feat/PLAN-<slug> && git merge --no-ff feat/PLAN-<slug>-task-NNN`.
2. Run the FULL build + test suite on the run branch after EVERY merge — the task was verified
against its fork point, not against siblings' merged work. A post-merge failure is an
integration defect: resume the responsible task's Sisyphus session with the failure verbatim.
3. Merge conflict → abort the merge, resume that task's Sisyphus session with the conflict
verbatim (it rebases its task branch onto the current run branch, re-verifies, re-pushes), then
retry the merge. Two failed conflict cycles on the same task → STOP and escalate.
4. Only after the merge lands AND the integration build+tests are green: push the run branch, close
the task (step 5), and clean up — `git worktree remove .worktrees/task-NNN` and delete the task
branch (local + remote).
Phase F is UNCHANGED (same single draft PR from the run branch). Before opening it, verify no
stale worktrees or task branches remain (`git worktree list`); clean up any leftovers.
### Phase F — Finish (single draft PR for the whole design doc)
When every task is `status: complete`:
1. In {{project_dir}} on the run branch: confirm the FULL build + test suite is green one final
time (the integrated result of all tasks). Failures are yours to drive to resolution (resume
the responsible Sisyphus session) before any PR exists.
2. **Roll up follow-ups, then open the ONE PR — ALWAYS as a DRAFT** (`gh pr create --draft`) from
`feat/PLAN-<slug>` → {{base_branch}}. First collect every "Follow-ups:" line from the completed
tasks' `log.md` files. Title: `PLAN-<slug>: <design doc title>`. Body MUST contain, in order:
- the plan's Problem/Approach summary,
- a checklist of every TASK-NNN (title + commit SHAs),
- a **`## Follow-up / manual actions`** section: one checkbox line per follow-up (WHAT, WHERE,
WHY, WHEN — pre-merge items FIRST and clearly marked), or "None." if there are none. This
section is the reviewer's contract for what the code does NOT do by itself.
Report the PR URL. NEVER mark it ready for review — the user reviews the draft first and flips
it when THEY decide teammates should see it.
3. **Watch the PR checks until green.** Poll `gh pr checks <number>` (re-run every few minutes, or
use `--watch`) until every run/check completes. On ANY failure: read the failing check's log
(`gh run view --log-failed`), resume the responsible Sisyphus session with the failure verbatim,
let it fix + push to the run branch, then re-check. Repeat until all checks pass. A failure that
is demonstrably external (infra flake, unrelated broken {{base_branch}}) → note it in the PR
body and escalate to the user instead of blind-retrying. Do NOT finish the run with failing or
still-pending checks.
4. **Create follow-up tasks** so follow-ups are trackable work, not just PR prose: per
`task-tracking`, one task per follow-up item (group small related items), `type: followup`,
`status: pending`, with the WHAT/WHERE/WHY/WHEN and which TASK-NNN surfaced it. Then edit the
PR body's Follow-up section to append each created TASK id to its checkbox line. Do NOT
implement these yourself — creating them IS the deliverable; the user picks them up after the
merge.
5. Set `PLAN-<slug>.md` frontmatter `status: implemented`, add the PR link and a
`**Follow-ups:** TASK-NNN, ...` line when any exist; append a `pr-opened` entry to every
completed task's `log.md`. If {{plans_dir}} rides the repo, commit these planning updates to
the run branch (`chore(plan): ...`) — they become part of the PR.
6. Run the `task-tracking` consistency checks; fix anything you introduced.
7. Report: the PLAN, every TASK-NNN with its commits, the single draft PR URL with checks green,
the follow-up TASKs created (with their WHEN), and anything deferred/escalated. STOP.
## Durable state (survive context compression)
Long runs compress. Anything that lives ONLY in chat is lost. Keep it durable:
- **Todo list**: task progress AND resumable Sisyphus `session_id`s (embed in item text).
- **{{plans_dir}} on disk**: PLAN frontmatter, task `index.md` statuses, `log.md` entries ARE the
run state. After a suspected compression, re-read `todo__list` and the task statuses — trust
disk, not memory.
- User-approved decisions get one durable line (todo text or the PLAN file) so you don't
re-litigate them.
## Delegation targets
| Agent | Use for |
|-------|---------|
| `sisyphus` | Implement ONE task's code in {{project_dir}} (its own explore/coder/verify/review loop). One per task. |
| `explore` | Ground the design/plan in real code in {{project_dir}}; read other local repos for library usage/legacy patterns/call sites. Fan out in parallel. |
| `librarian` | External docs/OSS examples for unfamiliar libraries the design touches. |
| `oracle` | Plan review (`plan-review`), and diagnosis when a task fails after Sisyphus recovery. |
| `gatekeeper` | Plan self-containedness gate (Phase C Gate 1): audits the PLAN for the "docker container" standard, returns SEALED/LEAKY with the missing implementer questions. |
| `adversary` | Post-implementation plan-conformance verdict per task (CONFORMS/DIVERGES). |
## Escalation handling
If `pending_escalations` appears in a tool result, a spawned Sisyphus is blocked on user input.
Answer from context if you can, else prompt the user, then `agent__reply_escalation` to unblock the
child. Do not leave a child hanging.
## Anti-patterns (BLOCKING)
- Opening a PER-TASK PR → the design doc gets exactly ONE PR, opened in Phase F.
- Opening the PR as non-draft, or marking the draft ready-for-review → the user flips it himself
after his own review.
- Finishing the run while PR checks are failing or still pending → the run is not done until
checks are green.
- Pushing to {{base_branch}}, or creating branches beyond the run branch (and, in parallel mode
ONLY, its per-task worktree branches).
- WRITING outside {{project_dir}} → wrong write target (reading elsewhere is fine).
- Materializing tasks from a plan the gatekeeper marked LEAKY (or never audited), or that Oracle
rejected (or never reviewed).
- Marking a task complete without the adversary's CONFORMS verdict and verified acceptance criteria.
- Code comments referencing the plan/design doc/phases/steps/TASK numbers → docs drift, comments
rot; plan references live in commit messages only.
- A `.env` file landing in any repo → only `.env.example` with placeholder keys is committable;
`.env` stays gitignored and real values are a follow-up.
- Dropping a Sisyphus-reported follow-up (not logged in the task's log.md, not in the PR's
Follow-up section, no follow-up task created) → manual actions get forgotten and the service
breaks at deploy time.
- Attempting a follow-up yourself (creating secrets, provisioning cloud roles, touching other
repos) instead of recording it → these are out of scope BY DEFINITION; record, don't do.
- Spawning a fresh Sisyphus for a follow-up/fix instead of resuming its `session_id`.
- Polling `agent__collect` on a running agent.
- Writing files via `execute_command` (heredocs, `cat >`, `echo >`) instead of `fs_write`/`fs_patch`.
- Losing a Sisyphus `session_id` or a follow-up to chat-only memory.
## Hard blocks (NEVER)
- Destructive/irreversible actions (`rm -rf`, force-push, dropping data, deleting branches) without
explicit user confirmation (parallel-mode post-merge worktree/task-branch cleanup excepted).
- Leaving code broken or a task half-done after a failure — reconcile, or escalate cleanly.
- Fabricating task completion — the acceptance criteria, the commits on the run branch, and the
final PR are the evidence.
## Available Tools
{{__tools__}}
## Context
- Project (WRITE target): {{project_dir}}
- Plans dir: {{plans_dir}}
- Design doc: {{design_doc}}
- Base branch: {{base_branch}}
- Autonomy: {{autonomy}}
- Parallel tasks: {{parallel_tasks}} (0 = sequential, 1 = worktree-parallel)
- OS: {{__os__}} Shell: {{__shell__}} CWD: {{__cwd__}} Now: {{__now__}}
conversation_starters:
- 'Implement the design doc at {{design_doc}} end to end'
- 'Decompose this design doc into a plan and tasks, then drive them to completion'
- 'Run the full design-to-PR pipeline on {{design_doc}}'
+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
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
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:
```yaml
+4
View File
@@ -19,8 +19,12 @@ variables:
- name: project_dir
description: Project directory to 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
+24 -16
View File
@@ -10,22 +10,30 @@ implement-fix loop enforced as graph edges rather than prose.
## Workflow
```
analyze_request (llm + output_schema) plan + complexity extraction
route_complexity (script) opt-out approval gate (complexity ≥ 7)
gate_approval (approval, optional)
implement (llm + fs tools) actual file edits
verify_build (script)
verify_tests (script)
fix_loop_gate (script) back-edge to implement (bounded)
end_success / end_rejected / end_failure
```mermaid
flowchart TD
resolve_paths{"resolve_paths<br/>script"} --> analyze_request
analyze_request["analyze_request<br/>llm + output_schema"] --> route_complexity
route_complexity{"route_complexity<br/>script"}
route_complexity -->|"complexity ≥ 7"| gate_approval
route_complexity -->|else| implement
gate_approval{{"gate_approval<br/>approval"}}
gate_approval -->|yes| implement
gate_approval -->|no| end_rejected
implement["implement<br/>llm + fs tools"] --> verify_build
verify_build{"verify_build<br/>script"}
verify_build -->|pass| verify_tests
verify_build -->|fail| fix_loop_gate
verify_tests{"verify_tests<br/>script"}
verify_tests -->|pass| end_success
verify_tests -->|fail| fix_loop_gate
fix_loop_gate{"fix_loop_gate<br/>script"}
fix_loop_gate -->|"budget left"| implement
fix_loop_gate -->|"budget spent"| end_failure
end_success(["end_success<br/>CODER_COMPLETE"])
end_rejected(["end_rejected<br/>CODER_REJECTED"])
end_failure(["end_failure<br/>CODER_FAILED"])
```
End nodes emit one of three sentinel outcomes for the caller:
+36 -21
View File
@@ -2,9 +2,9 @@ name: coder
description: |
Implementation agent. Plans, implements, and runs build + tests in a
bounded fix-loop until verified. Designed to be delegated to by sisyphus.
version: "1.0"
version: '1.0'
global_tools:
- ast_grep.sh
- fs_cat.sh
- fs_ls.sh
- fs_write.sh
@@ -25,23 +25,23 @@ variables:
Absolute path to the project directory. Defaults to "." which is the
directory you invoked `coyote` from. Override at runtime with
`coyote -a coder --agent-variable project_dir /abs/path "..."`.
default: "."
default: '.'
settings:
max_loop_iterations: 20
log_state_snapshots: true
validate_before_run: true
timeout: 1800
timeout: 14400
initial_state:
project_dir: ""
project_dir: ''
fix_attempts: 0
max_fix_attempts: 3
fix_instructions: ""
build_output: ""
tests_output: ""
last_node_output: ""
plan_summary: ""
fix_instructions: ''
build_output: ''
tests_output: ''
last_node_output: ''
plan_summary: ''
files_to_modify: []
files_to_create: []
risks: []
@@ -49,7 +49,7 @@ initial_state:
review_attempts: 0
max_review_attempts: 1
review_clean: true
review_notes: ""
review_notes: ''
start: resolve_paths
@@ -88,8 +88,9 @@ nodes:
etc. Empty list is fine.
Project directory: {{project_dir}}
prompt: "{{initial_prompt}}"
prompt: '{{initial_prompt}}'
tools: []
timeout: 300
output_schema:
type: object
properties:
@@ -109,9 +110,16 @@ nodes:
risks:
type: array
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:
last_node_output: "{{output}}"
last_node_output: '{{output}}'
fallback: end_failure
next: route_complexity
@@ -144,11 +152,11 @@ nodes:
Approve this plan?
options:
- "yes"
- "no"
- 'yes'
- 'no'
routes:
"yes": implement
"no": end_rejected
'yes': implement
'no': end_rejected
on_other: end_rejected
implement:
@@ -220,6 +228,11 @@ nodes:
on unfamiliar lints, etc.).
4. No dead code, no commented-out blocks, no premature abstractions.
5. End your turn when editing is done. The graph runs verification next.
6. VERIFICATION HONESTY: never state that a check, lint, build, or test
passed unless you paste its literal command and exit code. A gate
that did not run is UNVERIFIED — say so. An honest failure report
always beats a success-shaped one; a false "passed" poisons every
downstream consumer of your report.
Project directory: {{project_dir}}
prompt: |
@@ -241,9 +254,10 @@ nodes:
- fs_write
- fs_patch
- execute_command
max_iterations: 30
max_iterations: 100
timeout: 1800
state_updates:
last_node_output: "{{output}}"
last_node_output: '{{output}}'
fallback: end_failure
next: verify_build
@@ -315,6 +329,7 @@ nodes:
- fs_ls
- execute_command
max_iterations: 15
timeout: 600
output_schema:
type: object
properties:
@@ -326,7 +341,7 @@ nodes:
description: Concrete issues found, one per line as file:line - description. Empty when review_clean is true.
required: [review_clean, review_notes]
state_updates:
last_node_output: "{{output}}"
last_node_output: '{{output}}'
fallback: end_success
next: route_review_result
+2 -1
View File
@@ -13,6 +13,7 @@ else
fi
project_dir=$(echo "$state" | jq -r '.project_dir // "."')
project_dir=$(resolve_gate_dir "$project_dir")
if [[ -n "${BUILD_CMD:-}" ]]; then
cmd="$BUILD_CMD"
@@ -24,7 +25,7 @@ fi
if [[ -z "$cmd" || "$cmd" == "null" ]]; then
jq -nc '{
"build_ok": true,
"build_output": "(no build/check command available for this project type)",
"build_output": "(GATE NOT RUN: no build/check command configured or detected. This is NOT evidence that the build passed — set BUILD_CMD, and never report the build as verified.)",
"_next": "verify_tests"
}'
exit 0
+2 -1
View File
@@ -13,6 +13,7 @@ else
fi
project_dir=$(echo "$state" | jq -r '.project_dir // "."')
project_dir=$(resolve_gate_dir "$project_dir")
if [[ -n "${TEST_CMD:-}" ]]; then
cmd="$TEST_CMD"
@@ -24,7 +25,7 @@ fi
if [[ -z "$cmd" || "$cmd" == "null" ]]; then
jq -nc '{
"tests_ok": true,
"tests_output": "(no test command available for this project type)",
"tests_output": "(GATE NOT RUN: no test command configured or detected. This is NOT evidence that tests passed — set TEST_CMD, and never report the suite as green.)",
"_next": "self_review"
}'
exit 0
+36 -21
View File
@@ -22,28 +22,43 @@ agent, this is the file to read alongside the
## Workflow
17 nodes. `->` is the static route; a script node can also route
dynamically via `_next`. The `▶▶` line is a parallel super-step —
those branches run concurrently:
17 nodes. Solid arrows are static `next` / `routes` edges declared in
`graph.yaml`; script nodes can also route dynamically via `_next` (shown as
labeled branches out of the diamond). Dotted arrows show `map` fan-out — the
`research_each_question` node spawns one `research_one_question` branch per
sub-question and joins them before continuing.
```
parse_request (script) -> bootstrap_research (or -> ask_topic if no topic)
ask_topic (input) -> bootstrap_research
bootstrap_research (script) -> [plan, knowledge_lookup] ▶▶ parallel
plan (llm + output_schema) -> research_each_question
knowledge_lookup (rag) -> research_each_question
research_each_question (map) -> combine_findings (spawns one branch per question)
└─ research_one_question (llm) (atomic; runs N×, joins at map)
combine_findings (script) -> vet_sources
vet_sources (llm + custom tool) -> critique
critique (llm) -> reflexion_gate
reflexion_gate (script) -> synthesize (or -> research_each_question: reflexion loop)
synthesize (agent: report-writer) -> verify_sources
verify_sources (script) -> approve
approve (approval) -> end_accepted ("accept")
-> end_rejected ("reject")
-> incorporate_feedback (any free-form answer)
incorporate_feedback (script) -> research_each_question (the human-feedback loop)
```mermaid
flowchart TD
parse_request{"parse_request<br/>script"}
parse_request -->|"topic given"| bootstrap_research
parse_request -->|"no topic"| ask_topic
ask_topic[/"ask_topic<br/>input"/] --> bootstrap_research
bootstrap_research{"bootstrap_research<br/>script"}
bootstrap_research --> plan
bootstrap_research --> knowledge_lookup
plan["plan<br/>llm + output_schema"] --> research_each_question
knowledge_lookup[("knowledge_lookup<br/>rag")] --> research_each_question
research_each_question[\research_each_question<br/>map/]
research_each_question -. "spawns × N" .-> research_one_question["research_one_question<br/>llm + web tools"]
research_each_question --> combine_findings
combine_findings{"combine_findings<br/>script"} --> vet_sources
vet_sources["vet_sources<br/>llm + classify_source"] --> critique
critique["critique<br/>llm"] --> reflexion_gate
reflexion_gate{"reflexion_gate<br/>script"}
reflexion_gate -->|"PASS"| synthesize
reflexion_gate -->|"REVISE (budget left)"| research_each_question
reflexion_gate -->|"REVISE (budget spent)"| synthesize
synthesize[["synthesize<br/>agent → report-writer"]] --> verify_sources
verify_sources{"verify_sources<br/>script"} --> approve
approve{{"approve<br/>approval"}}
approve -->|"accept"| end_accepted
approve -->|"reject"| end_rejected
approve -->|"other (free-form feedback)"| incorporate_feedback
incorporate_feedback{"incorporate_feedback<br/>script"} --> research_each_question
end_accepted(["end_accepted<br/>report"])
end_rejected(["end_rejected"])
```
### Node-type breakdown
+10 -3
View File
@@ -1,6 +1,6 @@
name: explore
description: Fast codebase exploration agent - finds patterns, structures, and relevant files. Designed to be fanned out 2-5 in parallel by orchestrators.
version: 3.0.0
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.1.0
skills_enabled: true
enabled_skills:
@@ -10,10 +10,14 @@ variables:
- name: project_dir
description: Project directory to explore
default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
mcp_servers:
- ddg-search
global_tools:
- ast_grep.sh
- fs_read.sh
- fs_cat.sh
- fs_grep.sh
@@ -33,7 +37,7 @@ instructions: |
## 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.
@@ -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.
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.
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 "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_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)
+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
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
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:
```yaml
+3
View File
@@ -11,6 +11,9 @@ variables:
- name: project_dir
description: Project directory for context
default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
global_tools:
- fs_read.sh
+77
View File
@@ -0,0 +1,77 @@
# Gatekeeper
A **plan self-containedness gate**. Audits a plan against the "sealed container" standard before it
is finalized:
> A context-free LLM implementer must be able to execute the plan using ONLY what is on the page —
> every question it will hit mid-implementation is either **answered inline** or **delegated via a
> verified pointer** to the exact code/docs where the answer lives.
Where [`plan-review`](../../skills/plan-review/SKILL.md) (via `oracle`) judges the *approach*
(executability, verifiability, ordering), `gatekeeper` audits the *context*: does the implementer
know where infrastructure code goes, what DB tech to use (RDS vs in-cluster Postgres), which
directory layout to mirror, what commands verify the work — or at least where to look?
## The three review gates
| Gate | Agent | Question | When |
|------|-------|----------|------|
| Self-containedness | `gatekeeper` | "Can a context-free LLM implement from this file alone?" | Before the plan is finalized |
| Executability | `oracle` + `plan-review` | "Is the approach sound, verifiable, correctly ordered?" | Before the plan is promoted |
| Conformance | [`adversary`](../adversary/README.md) | "Is the built code what the plan asked for?" | After implementation |
## How it audits
Driven by the [`plan-gatekeeping`](../../skills/plan-gatekeeping/SKILL.md) skill:
1. Walks a 10-category manifest: code placement, infrastructure, data layer, interfaces/contracts,
conventions/tooling, testing/verification, dependencies/ordering, config/secrets, scope
boundaries, settled decisions.
2. For each category: answered inline, delegated via pointer, or **missing**.
3. **Verifies every pointer** with read-only tools — the path exists AND actually covers the claimed
topic. A pointer to a file that never mentions the topic is a leak wearing a pointer costume.
4. Phrases each gap as the question the implementer would actually ask, tagged **BLOCKING** (will
guess wrong) or **FRICTION** (will waste time rediscovering).
## Verdict (blocking)
```
PLAN_GATE: SEALED
Categories audited: N applicable, all answered or pointed.
```
```
PLAN_GATE: LEAKY
Missing questions (N):
1. [infrastructure] Where do I put the Terraform for the new service DB — infra/rds/ or a separate repo? — BLOCKING — plan says "provision a database" with no target — add inline: "RDS via infra/rds/, mirror rate_cards.tf"
Broken pointers (if any):
- "see docs/db.md for conventions" — path missing
```
`LEAKY` blocks finalization. The caller (typically `architect`) answers the questions — by exploring
the code repos, reading docs, or asking the user — amends the plan, and re-submits to the SAME
gatekeeper session until it seals.
## Usage
Spawned by `architect` during design-doc decomposition (Phase B/C), before the `oracle` plan-review:
```sh
agent__spawn --agent gatekeeper --prompt "Audit this plan for self-containedness. Return SEALED/LEAKY.
Plan: <plans_dir>/PLAN-<slug>.md
Target project: <project_dir>"
```
Ad-hoc use against any plan file:
```sh
coyote -a gatekeeper --agent-variable project_dir ~/code/my-service \
"Audit plans/PLAN-my-feature.md for self-containedness"
```
## Related
- [`plan-gatekeeping`](../../skills/plan-gatekeeping/SKILL.md) — the manifest + methodology it runs on.
- [`architect`](../architect/README.md) — the orchestrator that gates plans through it.
- [`adversary`](../adversary/README.md) — the post-implementation conformance counterpart.
+99
View File
@@ -0,0 +1,99 @@
name: gatekeeper
description: Plan self-containedness gate - audits a plan against the "sealed container" standard (every implementer question answered inline or via a verified pointer to code/docs) and returns a blocking PLAN_GATE SEALED/LEAKY verdict with the missing questions. Designed to be delegated to by architect before plans are finalized.
version: 2.0.0
auto_continue: true
max_auto_continues: 15
inject_todo_instructions: true
skills_enabled: true
enabled_skills:
- plan-gatekeeping
variables:
- name: project_dir
description: Absolute path to the project the plan targets - the ground truth for pointer verification
default: '.'
global_tools:
- ast_grep.sh
- fs_read.sh
- fs_cat.sh
- fs_grep.sh
- fs_glob.sh
- fs_ls.sh
instructions: |
You are the plan gatekeeper. You audit ONE plan for **self-containedness** before it is finalized:
the "sealed container" test. A context-free LLM implementer must be able to execute the plan using
ONLY what is on the page — every question it will hit mid-implementation must be answered inline or
delegated via a verified pointer to the exact code/docs where the answer lives. Your output is the
list of questions the plan FAILS to answer, and a blocking verdict.
You are NOT the approach reviewer (`plan-review` judges executability/verifiability of the design).
You audit completeness of CONTEXT. A brilliant approach with no answer to "where does the infra
code go?" or "managed RDS or an in-cluster Postgres container?" fails your gate.
## Step 0: Load the skill
Before anything else, `skill__load` `plan-gatekeeping`. It carries your methodology: the
answer-or-pointer rule, the 10-category manifest (code placement, infrastructure, data layer,
interfaces, conventions, testing, dependencies, config/secrets, scope, settled decisions), pointer
verification, severity tagging, and the exact verdict format. The skill body is your source of
truth; these instructions handle workflow and I/O.
## Input (the spawn prompt IS your entire context)
You are given a plan to audit — pasted inline or as a path to read. You may also be told which
project the plan targets; default ground truth is {{project_dir}}. Any other local repos/docs the
plan points into are readable for pointer verification.
If no plan is provided, STOP and say so.
## Workflow
1. Load `plan-gatekeeping`.
2. Read the plan in full (`fs_cat` for the whole file — do not audit a truncated view).
3. Walk EVERY manifest category. For each: answered inline, delegated via pointer, or MISSING.
Mark inapplicable categories explicitly.
4. Verify every pointer with the read-only tools: the path exists AND the target actually covers
the claimed topic. Check "mirror the layout of X" claims against X itself.
5. Phrase each gap as the QUESTION the implementer would actually ask, tag it BLOCKING or
FRICTION, and suggest the fix — an inline answer or a pointer you have VERIFIED resolves.
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:
```
PLAN_GATE: SEALED
Categories audited: N applicable, all answered or pointed.
```
```
PLAN_GATE: LEAKY
Missing questions (N):
1. [category] <implementer's actual question> — [BLOCKING|FRICTION] — <why they get stuck> — <suggested fix>
Broken pointers (if any):
- <pointer> — <path missing | doesn't cover topic>
```
## Rules
1. **You are read-only.** Never modify the plan. You produce questions; the author owns the fixes.
2. **Questions, not complaints.** "Infra section is thin" is noise. "Where do I put the Terraform
for the new database — {{project_dir}}/infra/ or a separate repo?" is signal.
3. **Verify every pointer you check AND every pointer you suggest.** Recommending an unverified
pointer is the same leak you exist to catch.
4. **BLOCKING findings always mean LEAKY.** Only-FRICTION findings: note the caller may seal at
their discretion.
5. **Do not re-litigate the approach.** Coherent-but-underdocumented means the fix is context.
6. Be terse and decisive. Three BLOCKING questions beat fifteen nitpicks.
## Context
- Project (ground truth): {{project_dir}}
- CWD: {{__cwd__}}
## Available Tools
{{__tools__}}
+19 -6
View File
@@ -10,13 +10,26 @@ library, API, or framework is involved.
## Workflow
```mermaid
flowchart TD
triage["triage<br/>llm"] --> search
triage --> search_oss
triage -.->|"fallback"| end_failure
search["search<br/>llm + ddg-search MCP"] --> synthesize
search_oss["search_oss<br/>llm + personal-github MCP"] --> synthesize
synthesize["synthesize<br/>llm + fetch_url_via_curl"] --> final_format
final_format{"final_format<br/>script"} --> end_success
end_success(["end_success<br/>LIBRARIAN_COMPLETE"])
end_failure(["end_failure<br/>LIBRARIAN_FAILED"])
```
search (llm + ddg-search) identify 3-5 authoritative sources
synthesize (llm + fetch_url_via_curl) fetch, extract, cite, synthesize
end_success / end_failure LIBRARIAN_COMPLETE / LIBRARIAN_FAILED
```
`triage` parses the prompt into language / doc-domain / query hints, then fans
out to `search` (authoritative docs via `ddg-search`) and `search_oss`
(production OSS examples via the `personal-github` MCP) in parallel. Both feed
into `synthesize`, which fetches each URL and produces a citation-backed
findings block. `final_format` (script) trims any LLM preamble before the
`LIBRARIAN_COMPLETE` sentinel is emitted.
Iteration 1 (this) is the happy-path MVP: single search pass, single synthesis
pass, no quality-check loop. Future iterations may add:
-6
View File
@@ -8,8 +8,6 @@ description: |
sisyphus alongside explore when unfamiliar libraries/APIs/frameworks are
involved.
Iteration 3: smart triage node up front + final-format trim of LLM
narrative leakage.
version: "1.0"
global_tools:
@@ -90,7 +88,6 @@ nodes:
prompt: |
Research prompt: {{initial_prompt}}
tools: []
temperature: 0.1
output_schema:
type: object
properties:
@@ -182,7 +179,6 @@ nodes:
tools:
- mcp:ddg-search
max_iterations: 15
temperature: 0.1
state_updates:
search_output: "{{output}}"
fallback: synthesize
@@ -253,7 +249,6 @@ nodes:
tools:
- mcp:personal-github
max_iterations: 15
temperature: 0.1
state_updates:
oss_output: "{{output}}"
fallback: synthesize
@@ -340,7 +335,6 @@ nodes:
tools:
- fetch_url_via_curl
max_iterations: 20
temperature: 0.1
state_updates:
findings: "{{output}}"
fallback: final_format
+14 -2
View File
@@ -1,20 +1,27 @@
name: oracle
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
enabled_skills:
- code-review
- ai-slop-remover
- plan-review
- plan-authoring
- iwe-knowledge-base
variables:
- name: project_dir
description: Project directory for context
default: '.'
- name: auto_confirm
description: Auto-confirm command execution
default: '1'
mcp_servers:
- ddg-search
global_tools:
- ast_grep.sh
- fs_read.sh
- fs_cat.sh
- fs_grep.sh
@@ -46,13 +53,16 @@ instructions: |
3. **Code review** — evaluating proposed designs or implementations.
4. **Risk assessment** — security, performance, reliability concerns.
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
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 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.
@@ -91,6 +101,8 @@ instructions: |
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
1. **Never modify files** — you advise, others implement.
+54 -4
View File
@@ -5,10 +5,45 @@ project management similar to OpenCode, ClaudeCode, Codex, or Gemini CLI.
_Inspired by the Sisyphus and Oracle agents of OpenCode._
Sisyphus acts as the primary entry point, capable of handling complex tasks by coordinating specialized sub-agents:
- **[Coder](../coder/README.md)**: For implementation and file modifications.
- **[Explore](../explore/README.md)**: For codebase understanding and research.
- **[Oracle](../oracle/README.md)**: For architecture and complex reasoning.
Sisyphus acts as the primary entry point. Every incoming request passes through a Phase 0 intent gate that verbalizes the intent, classifies it, and routes work to the specialized sub-agent(s) that fit — Sisyphus does not work alone when a specialist is available.
## Architecture
```mermaid
flowchart TD
user([User request]) --> sisyphus["Sisyphus<br/>orchestrator"]
sisyphus --> classify{"Phase 0<br/>Intent gate"}
classify -->|"Trivial<br/>(single file, obvious)"| direct["Direct tools<br/>fs_read / fs_patch / execute_command"]
classify -->|"Find in code<br/>How does Y work?"| explore[["explore<br/>internal codebase grep<br/>× 220 parallel"]]
classify -->|"External library<br/>docs / OSS examples"| librarian[["librarian<br/>docs + OSS grep<br/>× 26 parallel"]]
classify -->|"Architecture / hard debug<br/>Should I use X or Y?"| oracle[["oracle<br/>advisory, BLOCKING"]]
classify -->|"Implementation<br/>add / fix / create"| coder[["coder<br/>plan → edit → verify graph"]]
classify -->|"plans/ repo detected"| step_runner[["step-runner<br/>step-protocol graph"]]
coder --> broad_gate{"Broad scope?<br/>2+ coders / 5+ files /<br/>architectural boundary"}
broad_gate -->|"yes"| code_reviewer[["code-reviewer<br/>independent review"]]
broad_gate -->|"no"| spec_gate
code_reviewer --> spec_gate{"Implements<br/>a spec / plan?"}
spec_gate -->|"yes"| adversary[["adversary<br/>plan-conformance"]]
spec_gate -->|"no"| done
adversary --> done
direct --> done
done([Complete])
step_runner -. "internally spawns" .-> coder
step_runner -. "internally spawns" .-> code_reviewer
```
Spawnable sub-agents (from `config.yaml`):
- **[explore](../explore/README.md)** — internal codebase grep. Fan out one per distinct search angle or module (typically 26, up to 15+ for cross-cutting analysis).
- **[librarian](../librarian/README.md)** — external grep for official docs and production OSS examples. Fan out 26 in parallel with `explore` when unfamiliar libraries are involved.
- **[oracle](../oracle/README.md)** — advisory reasoning for architecture questions, hard debugging (after 2+ failed attempts), design review, and plan review. Blocking: Sisyphus never delivers a final answer with Oracle still running.
- **[coder](../coder/README.md)** — graph agent that plans, implements, and verifies (build + tests) in a bounded fix-loop.
- **[code-reviewer](../code-reviewer/README.md)** — independent post-implementation review; fires when the change is broad (2+ coders, 5+ files) or crosses architectural boundaries.
- **[adversary](../adversary/README.md)** — plan-conformance review; fires whenever the change implements a written spec, plan step, or acceptance-criteria list. Orthogonal to `code-reviewer` — both can run.
- **[step-runner](../step-runner/README.md)** — graph agent that executes one step of a phased plan repo. Internally delegates to `coder` for implementation and optionally to `code-reviewer` for review.
## Features
@@ -16,6 +51,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.
- 🔄 **Task Management**: Tracks progress and context across complex operations.
- 🛠️ **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
Many modern IDEs (JetBrains, VS Code, Cursor, Zed, etc.) expose MCP servers that let LLMs use IDE tools directly. Using
+104 -5
View File
@@ -1,6 +1,6 @@
name: sisyphus
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
auto_continue: true
@@ -8,6 +8,14 @@ max_auto_continues: 25
inject_todo_instructions: true
can_spawn_agents: true
spawnable_agents:
- explore
- librarian
- coder
- oracle
- code-reviewer
- adversary
- step-runner
max_concurrent_agents: 4
max_agent_depth: 3
inject_spawn_instructions: true
@@ -23,6 +31,10 @@ enabled_skills:
- parallel-research
- verification-gates
- oracle-protocol
- plan-authoring
- step-implementation
- handoff-protocol
- iwe-knowledge-base
variables:
- name: project_dir
@@ -35,6 +47,7 @@ variables:
mcp_servers:
- ddg-search
global_tools:
- ast_grep.sh
- fs_read.sh
- fs_grep.sh
- fs_glob.sh
@@ -101,6 +114,9 @@ instructions: |
| About to touch git history | `git-master` |
| About to touch UI/components | `frontend-ui-ux` (also nudge delegates to load it) |
| 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.
@@ -121,10 +137,11 @@ instructions: |
| Agent | Use For | Characteristics |
|-------|---------|-----------------|
| `explore` | Find patterns in THIS codebase, understand local code | Read-only, returns findings, fan out 2-5 in parallel |
| `librarian` | Find official docs, OSS examples, web best practices for EXTERNAL libraries | Read-only, returns citation-backed findings, fan out 1-3 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 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 |
| `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)
@@ -186,7 +203,17 @@ instructions: |
## 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
@@ -239,6 +266,12 @@ instructions: |
**No evidence = not complete.** Mark a todo `completed` only after evidence is collected.
### Verification honesty (NON-NEGOTIABLE)
- Never state that a lint, build, or test passed unless you can paste its literal command and exit code. A gate that did not run is UNVERIFIED — report it as not run, never as "covered by" something else.
- Never reuse a verification claim from an earlier report (yours or another agent's) without re-running the command yourself. Prior reports are unverified context, not evidence.
- An honest failure — "gate X failed / could not run, here is the verbatim error" — is an acceptable, preferable deliverable. A success-shaped report with missing evidence poisons every downstream consumer.
### Independent code review (post-coder, non-trivial work)
After completing delegated `coder` work, spawn `code-reviewer` for an independent review pass if ANY of these are true:
@@ -278,6 +311,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.
### 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)
When you write or modify files yourself (rather than delegating to coder):
@@ -312,6 +370,47 @@ instructions: |
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
**Do yourself**: trivial typos/renames, single-file changes you've already read, simple command execution, quick file searches you can express in one grep.
+38
View File
@@ -0,0 +1,38 @@
schemaVersion: '2'
kind: mixin
name: sisyphus-ddg
description: >
Allows Sisyphus to reach DuckDuckGo plus a curated set of common
content domains for its web-search MCP server. Schema v2 removed
the bare '*' allow-all, so frequently fetched result domains are
enumerated here.
agentInstructions:
content: |
Web search runs against an enumerated network allow list. If fetching a
search result is blocked by network policy, ask the user to run
`sbx policy allow network <domain>` on the host to extend it.
permissions:
network:
allow:
# DuckDuckGo search endpoints used by the ddg-search MCP server
- 'duckduckgo.com'
- 'html.duckduckgo.com'
- 'lite.duckduckgo.com'
# Common content/result domains fetched from search results
# ('*.host' matches exactly one label and not the bare host itself)
- '*.wikipedia.org'
- 'github.com'
- '*.githubusercontent.com'
- 'stackoverflow.com'
- '*.stackexchange.com'
- 'developer.mozilla.org'
- 'docs.python.org'
- 'doc.rust-lang.org'
- 'docs.rs'
- 'crates.io'
- 'pypi.org'
- 'www.npmjs.com'
# Jina reader fallback for fetching arbitrary pages as markdown
- 'r.jina.ai'
+122
View File
@@ -0,0 +1,122 @@
# 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
```mermaid
flowchart TD
resolve_step{"resolve_step<br/>script"}
resolve_step -->|"deps satisfied"| orient
resolve_step -->|"deps unsatisfied"| gate_blocked
gate_blocked{{"gate_blocked<br/>approval"}}
gate_blocked -->|"yes"| orient
gate_blocked -->|"no"| end_blocked
orient["orient<br/>llm, read-only"] --> route_staleness
route_staleness{"route_staleness<br/>script"}
route_staleness -->|"major deviation"| gate_deviation
route_staleness -->|"else"| implement
gate_deviation{{"gate_deviation<br/>approval"}}
gate_deviation -->|"proceed"| implement
gate_deviation -->|"abort"| end_rejected
gate_deviation -->|"other (user guidance)"| implement
implement[["implement<br/>agent → coder"]] --> route_coder_result
route_coder_result{"route_coder_result<br/>script"}
route_coder_result -->|"CODER_COMPLETE"| verify_format_lint
route_coder_result -->|"REJECTED / FAILED"| end_failure
verify_format_lint{"verify_format_lint<br/>script"}
verify_format_lint -->|"pass"| verify_build
verify_format_lint -->|"fail"| fix_loop_gate
verify_build{"verify_build<br/>script"}
verify_build -->|"pass"| verify_tests
verify_build -->|"fail"| fix_loop_gate
verify_tests{"verify_tests<br/>script"}
verify_tests -->|"pass"| edge_case_sweep
verify_tests -->|"fail"| fix_loop_gate
fix_loop_gate{"fix_loop_gate<br/>script"}
fix_loop_gate -->|"budget left"| implement
fix_loop_gate -->|"budget spent"| end_failure
edge_case_sweep["edge_case_sweep<br/>llm"] --> route_sweep
route_sweep{"route_sweep<br/>script"}
route_sweep -->|"5+ files or boundary"| independent_review
route_sweep -->|"else"| write_handoff
independent_review[["independent_review<br/>agent → code-reviewer"]] --> route_review
route_review{"route_review<br/>script"}
route_review -->|"🔴 critical findings"| implement
route_review -->|"else"| write_handoff
write_handoff["write_handoff<br/>llm"] --> check_handoff
check_handoff{"check_handoff<br/>script"}
check_handoff -->|"schema valid"| gate_user_review
check_handoff -->|"one retry"| write_handoff
gate_user_review{{"gate_user_review<br/>approval"}}
gate_user_review -->|"approve"| end_success
gate_user_review -->|"revise"| get_revision
gate_user_review -->|"other (comments)"| revise_from_choice
get_revision[/"get_revision<br/>input"/] --> implement
revise_from_choice{"revise_from_choice<br/>script"} --> implement
end_success(["end_success<br/>STEP_COMPLETE"])
end_blocked(["end_blocked<br/>STEP_BLOCKED"])
end_rejected(["end_rejected<br/>STEP_REJECTED"])
end_failure(["end_failure<br/>STEP_FAILED"])
```
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.
+612
View File
@@ -0,0 +1,612 @@
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.
VERIFICATION HONESTY: evidence marked "GATE NOT RUN" means that gate
is UNVERIFIED — record it as not run; never paraphrase a skipped gate
as covered, passing, or handled elsewhere. A handoff that admits an
unverified gate is correct; one that dresses it up as verified poisons
every downstream reader.
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
+58
View File
@@ -0,0 +1,58 @@
#!/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_dir=$(resolve_gate_dir "$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": "(GATE NOT RUN: no build/check command configured or detected. This is NOT evidence that the build passed — set BUILD_CMD, and never report the build as verified.)",
"_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
+84
View File
@@ -0,0 +1,84 @@
#!/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_dir=$(resolve_gate_dir "$project_dir")
project_info=$(detect_project "$project_dir")
project_type=$(echo "$project_info" | jq -r '.type // "unknown"')
format_cmd="${FORMAT_CMD:-}"
if [[ -z "$format_cmd" ]]; then
format_cmd=$(echo "$project_info" | jq -r '.fmt // ""')
fi
if [[ "$format_cmd" == "null" ]]; then format_cmd=""; fi
if [[ -z "$format_cmd" ]]; then
format_output="(GATE NOT RUN: no format command configured or detected for project type '$project_type'. This is NOT evidence that formatting is clean. 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
lint_cmd=$(echo "$project_info" | jq -r '.lint // ""')
fi
# The skip message must read as a WARNING, never a reassurance: the previous
# wording ("linting is covered by the build/check command") was quoted
# verbatim by workers as false evidence that linting passed
if [[ -z "$lint_cmd" || "$lint_cmd" == "null" ]]; then
jq -nc \
--arg fo "$format_output" \
'{
"format_output": $fo,
"lint_ok": true,
"lint_output": "(GATE NOT RUN: no lint command configured or detected. This is NOT evidence that linting passed — set LINT_CMD or add a Taskfile lint target, and never report linting as covered.)",
"_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
+58
View File
@@ -0,0 +1,58 @@
#!/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_dir=$(resolve_gate_dir "$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": "(GATE NOT RUN: no test command configured or detected. This is NOT evidence that tests passed — set TEST_CMD, and never report the suite as green.)",
"_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",
"command": "uvx",
"args": ["duckduckgo-mcp-server"]
},
"iwe": {
"type": "stdio",
"command": "iwec",
"args": ["--project", "."]
}
}
}
+44
View File
@@ -0,0 +1,44 @@
schemaVersion: '2'
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`.
permissions:
network:
allow:
# fetch_url_via_jina + jina reader fallback
- 'r.jina.ai'
# get_current_weather (.sh, .py, .ts)
- 'wttr.in'
# search_arxiv (the .sh tool still uses http://, so :80 is required until fixed)
- 'export.arxiv.org'
- 'export.arxiv.org:80'
# search_arxiv + search_wikipedia may follow DOI redirects
- 'doi.org'
# search_wikipedia
- 'en.wikipedia.org'
# search_wolframalpha
- 'api.wolframalpha.com'
# web_search_perplexity
- 'api.perplexity.ai'
# web_search_tavily
- 'api.tavily.com'
# send_twilio
- 'api.twilio.com'
# MCP: github (built-in mcp.json: api.githubcopilot.com)
- 'api.githubcopilot.com'
# MCP: atlassian (built-in mcp.json: mcp-remote -> mcp.atlassian.com)
- 'mcp.atlassian.com'
# MCP: ddg-search (built-in mcp.json: uvx duckduckgo-mcp-server)
- 'duckduckgo.com'
- 'html.duckduckgo.com'
- 'lite.duckduckgo.com'
# MCP: npx-based servers (mcp-remote) pull from npm
- 'registry.npmjs.org'
# MCP: docker server may pull images from common registries
- 'ghcr.io'
- 'registry-1.docker.io'
- 'auth.docker.io'
+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() {
# 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"
}
+14 -3
View File
@@ -17,8 +17,8 @@ main() {
local search_path="${argc_path:-.}"
if [[ ! -d "$search_path" ]]; then
echo "Error: directory not found: $search_path" >> "$LLM_OUTPUT"
return 1
echo "Error: directory not found: $search_path" >&2
exit 1
fi
local results
@@ -33,7 +33,18 @@ main() {
--exclude '.build' \
2>/dev/null | head -n "$MAX_RESULTS") || true
else
results=$(find "$search_path" -type f -name "$glob_pattern" \
local name_pattern dir_prefix effective_search
name_pattern="${glob_pattern##*/}"
[[ -z "$name_pattern" || "$name_pattern" == "**" ]] && name_pattern="*"
if [[ "$glob_pattern" == */* ]]; then
dir_prefix="${glob_pattern%%\**}"
dir_prefix="${dir_prefix%/}"
effective_search="${search_path}${dir_prefix:+/$dir_prefix}"
else
effective_search="$search_path"
fi
[[ -d "$effective_search" ]] || effective_search="$search_path"
results=$(find "$effective_search" -type f -name "$name_pattern" \
-not -path '*/.git/*' \
-not -path '*/node_modules/*' \
-not -path '*/target/*' \
+2 -2
View File
@@ -21,8 +21,8 @@ main() {
local include_filter="${argc_include:-}"
if [[ ! -e "$search_path" ]]; then
echo "Error: path not found: $search_path" >> "$LLM_OUTPUT"
return 1
echo "Error: path not found: $search_path" >&2
exit 1
fi
local grep_args=(-nH --color=never)
+14 -1
View File
@@ -9,5 +9,18 @@ set -e
main() {
# 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
}
+41 -3
View File
@@ -5,9 +5,31 @@ set -e
# 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.
# 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.
# - Hunks anchor at the FIRST exact match of their context in the file, so include enough context to make each hunk
# unique. Hunks must appear in file order.
# - Every hunk needs at least one context or removed line to anchor it; a hunk containing only additions is an error.
# - Unrecognized lines inside a hunk are hard errors: every hunk line must start with ' ' (context), '-' (removal),
# or '+' (addition).
# - 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 --contents! The patch to apply to the file
# @option --content! The patch to apply to the file
# @env LLM_OUTPUT=/dev/stdout The output path
@@ -16,7 +38,11 @@ source "$LLM_PROMPT_UTILS_FILE"
# shellcheck disable=SC2154
main() {
argc_contents="$(jq -r '.contents' <<< "$LLM_TOOL_RAW_JSON")"
# Command substitution strips *all* trailing newlines and `jq -r` appends one
# of its own, so read with `-j` and pin the real end of the content with a
# sentinel that is removed afterwards.
argc_contents="$(jq -j '.content' <<< "$LLM_TOOL_RAW_JSON"; printf x)"
argc_contents="${argc_contents%x}"
argc_path="$(jq -r '.path' <<< "$LLM_TOOL_RAW_JSON")"
if [[ ! -f "$argc_path" ]]; then
@@ -24,7 +50,19 @@ main() {
exit 1
fi
new_contents="$(patch_file "$argc_path" <(printf "%s" "$argc_contents"))"
# Same sentinel guard on the patched result, otherwise the trailing newline
# is stripped again on the way back out. `rc` preserves patch_file's exit
# status so a failure still aborts under `set -e`.
new_contents="$(patch_file "$argc_path" <(printf "%s" "$argc_contents"); rc=$?; printf x; exit "$rc")"
new_contents="${new_contents%x}"
# awk newline-terminates every printed line, so patching a file that lacks
# a final newline would silently add one. Preserve the original file's
# final-newline state instead.
if [[ -n "$(tail -c 1 "$argc_path")" ]]; then
new_contents="${new_contents%$'\n'}"
fi
printf "%s" "$new_contents" | git diff --no-index "$argc_path" - || true
guard_operation "Apply changes?"
+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.
# @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 --limit The maximum number of lines to read (default: 2000)
# @option --offset <INT> The line number to start reading from (1-indexed, default: 1)
# @option --limit <INT> The maximum number of lines to read (default: 2000)
# @env LLM_OUTPUT=/dev/stdout The output path
@@ -23,8 +23,8 @@ main() {
local limit="${argc_limit:-2000}"
if [[ ! -e "$target" ]]; then
echo "Error: path not found: $target" >> "$LLM_OUTPUT"
return 1
echo "Error: path not found: $target" >&2
exit 1
fi
if [[ -d "$target" ]]; then
@@ -33,9 +33,20 @@ main() {
fi
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)
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
{
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 | {
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
line="${line:0:$MAX_LINE_LENGTH}... (truncated)"
fi
+7 -2
View File
@@ -6,7 +6,7 @@ set -e
# sending less data, and is less prone to accidental data loss.
# @option --path! The path of the file to write to
# @option --contents! The full contents to write to the file
# @option --content! The full contents to write to the file
# @env LLM_OUTPUT=/dev/stdout The output path
@@ -15,7 +15,12 @@ source "$LLM_PROMPT_UTILS_FILE"
# shellcheck disable=SC2154
main() {
argc_contents="$(jq -r '.contents' <<< "$LLM_TOOL_RAW_JSON")"
# Command substitution strips *all* trailing newlines and `jq -r` appends one
# of its own, so read with `-j` and pin the real end of the content with a
# sentinel that is removed afterwards. Without this every written file loses
# its final newline, which breaks formatters such as `cargo fmt --check`.
argc_contents="$(jq -j '.content' <<< "$LLM_TOOL_RAW_JSON"; printf x)"
argc_contents="${argc_contents%x}"
argc_path="$(jq -r '.path' <<< "$LLM_TOOL_RAW_JSON")"
if [[ -f "$argc_path" ]]; then
+126 -15
View File
@@ -186,7 +186,9 @@ input() {
}
confirm() {
trap "stty echo; exit" EXIT
# stty targets stdin, which is /dev/null when the host spawns tool scripts;
# point it at the real terminal and stay quiet when there isn't one.
trap "stty echo </dev/tty 2>/dev/null; exit" EXIT
_prompt_text "$1 (y/N)"
echo -en "\033[36m\c " >&2
@@ -229,7 +231,7 @@ list() {
declare first_row
first_row=$((last_row - opts_count + 1))
trap "_cursor_blink_on; stty echo; exit" 2
trap "_cursor_blink_on; stty echo </dev/tty 2>/dev/null; exit" 2
_cursor_blink_off
@@ -275,7 +277,7 @@ checkbox() {
declare first_row
first_row=$((last_row - opts_count + 1))
trap "_cursor_blink_on; stty echo; exit" 2
trap "_cursor_blink_on; stty echo </dev/tty 2>/dev/null; exit" 2
_cursor_blink_off
@@ -403,7 +405,7 @@ range() {
declare current_row
current_row=$((first_row - 1))
trap "_cursor_blink_on; stty echo; exit" 2
trap "_cursor_blink_on; stty echo </dev/tty 2>/dev/null; exit" 2
_cursor_blink_off
@@ -528,7 +530,11 @@ guard_operation() {
# + print(f"Hello {name}")
patch_file() {
awk '
FNR == NR {
function isHeaderPair(i) {
return (patchLines[i] ~ /^--- / && patchLines[i+1] ~ /^\+\+\+ / && patchLines[i+2] ~ /^@@/)
}
FILENAME == ARGV[1] {
lines[FNR] = $0
next;
}
@@ -547,11 +553,6 @@ patch_file() {
while (patchLineIndex <= totalPatchLines) {
line = patchLines[patchLineIndex]
if (line ~ /^--- / || line ~ /^\+\+\+ /) {
patchLineIndex++
continue
}
if (line ~ /^@@/) {
mode = "hunk"
hunkIndex++
@@ -560,7 +561,22 @@ patch_file() {
}
if (mode == "hunk") {
while (patchLineIndex <= totalPatchLines && line ~ /^[-+ ]|^\s*$/ && line !~ /^--- /) {
while (patchLineIndex <= totalPatchLines) {
line = patchLines[patchLineIndex]
if (line ~ /^\\ No newline/) {
patchLineIndex++
continue
}
if (isHeaderPair(patchLineIndex)) {
break
}
if (line !~ /^[-+ ]/ && line !~ /^[ \t]*$/) {
break
}
sanitizedLine = substr(line, 2)
if (line !~ /^\+/) {
@@ -574,21 +590,79 @@ patch_file() {
}
patchLineIndex++
line = patchLines[patchLineIndex]
}
mode = "none"
} else {
patchLineIndex++
continue
}
if (isHeaderPair(patchLineIndex)) {
patchLineIndex += 2
continue
}
if (line ~ /^\\ No newline/) {
patchLineIndex++
continue
}
if (hunkIndex == 0) {
# Preamble before the first hunk: tolerate prose, code fences, and lone headers.
patchLineIndex++
continue
}
if (line ~ /^[ \t]*$/ || line ~ /^```/) {
patchLineIndex++
continue
}
print "error: unrecognized line in patch (line " patchLineIndex "): " line > "/dev/stderr"
print "" > "/dev/stderr"
print "Every line inside a hunk must start with \" \" (context), \"-\" (removal), or \"+\" (addition)." > "/dev/stderr"
exit 1
}
if (hunkIndex == 0) {
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
}
totalHunks = hunkIndex
if (totalLines == 0) {
for (h = 1; h <= totalHunks; h++) {
if (hunkTotalOriginalLines[h] > 0) {
print "error: unable to apply patch" > "/dev/stderr"
print "" > "/dev/stderr"
print "Hunk " h " expects existing content but the file is empty." > "/dev/stderr"
exit 1
}
}
for (h = 1; h <= totalHunks; h++) {
for (i = 1; i <= hunkTotalUpdatedLines[h]; i++) {
print hunkUpdatedLines[h,i]
}
}
exit 0
}
for (h = 1; h <= totalHunks; h++) {
if (hunkTotalOriginalLines[h] == 0) {
print "error: unable to apply patch" > "/dev/stderr"
print "" > "/dev/stderr"
print "Hunk " h " contains no context or removed lines; include at least one" > "/dev/stderr"
print "context line so the hunk can be anchored." > "/dev/stderr"
exit 1
}
}
hunkIndex = 1
for (lineIndex = 1; lineIndex <= totalLines; lineIndex++) {
@@ -599,7 +673,15 @@ patch_file() {
nextLineIndex = lineIndex + 1
for (i = 2; i <= hunkTotalOriginalLines[hunkIndex]; i++) {
if (lines[nextLineIndex] != hunkOriginalLines[hunkIndex,i]) {
if (nextLineIndex > totalLines || 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
break
}
@@ -621,7 +703,36 @@ patch_file() {
}
if (hunkIndex != totalHunks + 1) {
failingHunk = hunkIndex
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"
if (bestPartialDivergeLine[failingHunk] > totalLines) {
print "The hunk expects additional lines beyond the end of the file (file has " totalLines " lines)." > "/dev/stderr"
} else {
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
}
}
+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.
+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
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
point for all analysis, style questions, etc.
Should the root directory contain a `COYOTE.md` (or `AGENTS.md`/`CLAUDE.md`) file, this contains human-curated project
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
all relevant aspects for understanding and potentially contributing to the project.
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
if [ -z "$SSH_AUTH_SOCK" ]; then
echo "WARNING: [git-ssh-sign] no SSH agent — cannot sign commits"
fi
KEY=$(ssh-add -L 2>/dev/null | head -1)
if [ -z "$KEY" ]; then
echo "WARNING: [git-ssh-sign] no keys in SSH agent — cannot sign commits"
fi
KEY_FILE="/home/agent/.config/git/signing_key.pub"
mkdir -p "$(dirname "$KEY_FILE")"
printf '%s\n' "$KEY" > "$KEY_FILE"
EMAIL=$(git config user.email 2>/dev/null || echo "agent@sandbox.local")
printf '%s %s\n' "$EMAIL" "$KEY" > "/home/agent/.config/git/allowed_signers"
local_hook="$(git rev-parse --git-dir)/hooks/pre-commit"
if [ -x "$local_hook" ]; then
exec "$local_hook" "$@"
fi
+373
View File
@@ -0,0 +1,373 @@
# 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 run testing --kit ./sbx-kit/
schemaVersion: '2'
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.8.3'
entrypoint: ['bash', '-lc', 'exec /home/agent/.cargo/bin/coyote']
permissions:
network:
allow:
# Coyote release + self-update + model-registry sync
- 'github.com'
- 'api.github.com'
- 'raw.githubusercontent.com'
- 'objects.githubusercontent.com'
- '*.githubusercontent.com'
# Package managers and developer tools (cargo, uv, pip — useful at runtime for user installs)
- 'crates.io'
- 'static.crates.io'
- 'pypi.org'
- 'files.pythonhosted.org'
- 'astral.sh'
- 'sh.rustup.rs'
- 'static.rust-lang.org'
# LLM model OAuth + API endpoints
- 'claude.ai'
- 'console.anthropic.com'
- 'accounts.google.com'
# *.googleapis.com covers oauth2 + userinfo + VertexAI regional endpoints
# (*-aiplatform.googleapis.com). Do not narrow without re-checking VertexAI.
- '*.googleapis.com'
# Bedrock and GitHub Models use signed / GitHub-PAT auth that the proxy
# cannot rewrite; credentials must be injected separately (see README
# "Extending"). NOTE: '*.amazonaws.com' matches exactly ONE label, so
# two-label regional Bedrock hosts must be enumerated explicitly
# ('**.' is declared but not yet enforced by sbx). Add your region
# via a mixin if it's missing below.
- '*.amazonaws.com'
- 'bedrock-runtime.us-east-1.amazonaws.com'
- 'bedrock-runtime.us-east-2.amazonaws.com'
- 'bedrock-runtime.us-west-2.amazonaws.com'
- 'bedrock-runtime.eu-west-1.amazonaws.com'
- 'bedrock-runtime.eu-central-1.amazonaws.com'
- 'bedrock-runtime.ap-southeast-2.amazonaws.com'
- 'bedrock-runtime.ap-northeast-1.amazonaws.com'
- 'models.inference.ai.azure.com'
# Proxy-managed LLM provider APIs. Every credentials[].apiKey.inject
# domain below MUST also appear here. sbx does not derive allow entries
# from inject rules.
- 'api.openai.com'
- 'api.anthropic.com'
- 'generativelanguage.googleapis.com'
- 'api.cohere.ai'
- 'api.groq.com'
- 'openrouter.ai'
- 'api.ai21.com'
- 'api.cloudflare.com'
- 'api.deepinfra.com'
- 'api.deepseek.com'
- 'api.mistral.ai'
- 'api.perplexity.ai'
- 'api.voyageai.com'
- 'api.x.ai'
- 'api.jina.ai'
- 'r.jina.ai'
- 'qianfan.baidubce.com'
- 'api.hunyuan.cloud.tencent.com'
- 'api.minimax.chat'
- 'api.moonshot.cn'
- 'dashscope.aliyuncs.com'
- 'open.bigmodel.cn'
# Proxy-managed LLM providers: inside the sandbox each apiKey env var holds
# the `proxy-managed` sentinel; the proxy injects the real value into the
# request header per the inject rules at request time. Values are bound by
# the user via credential bindings (`sbx secret set <service>`); Coyote
# pre-seeds them from its vault at launch. Multiple domains may map to one
# service (e.g. jina) so they share a single credential.
credentials:
- service: openai
description: OpenAI API key, injected on api.openai.com
apiKey:
name: OPENAI_API_KEY
proxyManaged: true
inject:
- domain: api.openai.com
scheme: bearer
- service: anthropic
description: Anthropic API key, injected as x-api-key on api.anthropic.com
apiKey:
name: ANTHROPIC_API_KEY
proxyManaged: true
inject:
- domain: api.anthropic.com
header: x-api-key
format: '%s'
- service: gemini
description: Google Gemini API key, injected as x-goog-api-key on generativelanguage.googleapis.com
apiKey:
name: GEMINI_API_KEY
proxyManaged: true
inject:
- domain: generativelanguage.googleapis.com
header: x-goog-api-key
format: '%s'
- service: cohere
description: Cohere API key, injected on api.cohere.ai
apiKey:
name: COHERE_API_KEY
proxyManaged: true
inject:
- domain: api.cohere.ai
scheme: bearer
- service: groq
description: Groq API key, injected on api.groq.com
apiKey:
name: GROQ_API_KEY
proxyManaged: true
inject:
- domain: api.groq.com
scheme: bearer
- service: openrouter
description: OpenRouter API key, injected on openrouter.ai
apiKey:
name: OPENROUTER_API_KEY
proxyManaged: true
inject:
- domain: openrouter.ai
scheme: bearer
- service: ai21
description: AI21 Labs API key, injected on api.ai21.com
apiKey:
name: AI21_API_KEY
proxyManaged: true
inject:
- domain: api.ai21.com
scheme: bearer
- service: cloudflare
description: Cloudflare Workers AI API key, injected on api.cloudflare.com
apiKey:
name: CLOUDFLARE_API_KEY
proxyManaged: true
inject:
- domain: api.cloudflare.com
scheme: bearer
- service: deepinfra
description: DeepInfra API key, injected on api.deepinfra.com
apiKey:
name: DEEPINFRA_API_KEY
proxyManaged: true
inject:
- domain: api.deepinfra.com
scheme: bearer
- service: deepseek
description: DeepSeek API key, injected on api.deepseek.com
apiKey:
name: DEEPSEEK_API_KEY
proxyManaged: true
inject:
- domain: api.deepseek.com
scheme: bearer
- service: mistral
description: Mistral API key, injected on api.mistral.ai
apiKey:
name: MISTRAL_API_KEY
proxyManaged: true
inject:
- domain: api.mistral.ai
scheme: bearer
- service: perplexity
description: Perplexity API key, injected on api.perplexity.ai
apiKey:
name: PERPLEXITY_API_KEY
proxyManaged: true
inject:
- domain: api.perplexity.ai
scheme: bearer
- service: voyageai
description: Voyage AI API key, injected on api.voyageai.com
apiKey:
name: VOYAGE_API_KEY
proxyManaged: true
inject:
- domain: api.voyageai.com
scheme: bearer
- service: xai
description: xAI (Grok) API key, injected on api.x.ai
apiKey:
name: XAI_API_KEY
proxyManaged: true
inject:
- domain: api.x.ai
scheme: bearer
- service: jina
description: Jina API key, injected on api.jina.ai and r.jina.ai
apiKey:
name: JINA_API_KEY
proxyManaged: true
inject:
- domain: api.jina.ai
scheme: bearer
- domain: r.jina.ai
scheme: bearer
- service: ernie
description: Baidu ERNIE API key, injected on qianfan.baidubce.com
apiKey:
name: ERNIE_API_KEY
proxyManaged: true
inject:
- domain: qianfan.baidubce.com
scheme: bearer
- service: hunyuan
description: Tencent Hunyuan API key, injected on api.hunyuan.cloud.tencent.com
apiKey:
name: HUNYUAN_API_KEY
proxyManaged: true
inject:
- domain: api.hunyuan.cloud.tencent.com
scheme: bearer
- service: minimax
description: MiniMax API key, injected on api.minimax.chat
apiKey:
name: MINIMAX_API_KEY
proxyManaged: true
inject:
- domain: api.minimax.chat
scheme: bearer
- service: moonshot
description: Moonshot AI API key, injected on api.moonshot.cn
apiKey:
name: MOONSHOT_API_KEY
proxyManaged: true
inject:
- domain: api.moonshot.cn
scheme: bearer
- service: qianwen
description: Alibaba Qianwen (DashScope) API key, injected on dashscope.aliyuncs.com
apiKey:
name: DASHSCOPE_API_KEY
proxyManaged: true
inject:
- domain: dashscope.aliyuncs.com
scheme: bearer
- service: zhipuai
description: Zhipu AI (GLM) API key, injected on open.bigmodel.cn
apiKey:
name: ZHIPUAI_API_KEY
proxyManaged: true
inject:
- domain: open.bigmodel.cn
scheme: bearer
environment:
variables:
IS_SANDBOX: '1'
COYOTE_LOG_LEVEL: INFO
COYOTE_CONFIG_DIR: /home/agent/.config/coyote
EDITOR: nano
# Alias for the gemini credential: v2 apiKey supports a single env name
# (GEMINI_API_KEY above). Coyote also recognizes GOOGLE_API_KEY, so keep
# it set to the sentinel. Header injection happens per-domain regardless
# of which env var the app reads.
GOOGLE_API_KEY: proxy-managed
setup:
files:
- path: /home/agent/.config/git/ssh-signing-key-command
mode: '0755'
description: Resolve the forwarded SSH agent key for Git SSH signing
content: |
#!/bin/sh
set -e
if [ -z "$SSH_AUTH_SOCK" ]; then
echo "WARNING: [git-ssh-sign] no SSH agent - cannot sign commits" >&2
fi
key=$(ssh-add -L 2>/dev/null | head -n 1)
if [ -z "$key" ]; then
echo "WARNING: [git-ssh-sign] no keys in SSH agent - cannot sign commits" >&2
fi
config_dir="$GIT_SSH_SIGN_CONFIG_DIR"
if [ -z "$config_dir" ]; then
config_dir="/home/agent/.config/git"
fi
mkdir -p "$config_dir"
email=$(git config user.email 2>/dev/null || printf '%s' "agent@sandbox.local")
printf '%s %s\n' "$email" "$key" > "$config_dir/allowed_signers"
printf 'key::%s\n' "$key"
install:
- command: |
git config --system gpg.format ssh
git config --system --unset-all user.signingKey || true
git config --system commit.gpgSign true
git config --system tag.gpgSign true
git config --system gpg.ssh.defaultKeyCommand /home/agent/.config/git/ssh-signing-key-command
git config --system gpg.ssh.allowedSignersFile /home/agent/.config/git/allowed_signers
if [ "$(git config --system --get core.hooksPath || true)" = "/home/agent/.config/git/hooks" ]; then
git config --system --unset-all core.hooksPath
fi
user: '0'
description: Configure SSH commit signing with a dynamic key command
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
agentInstructions:
filename: COYOTE.md
content: |
## 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 via
credential bindings. Coyote pre-seeds them from its vault at launch
(`sbx secret set <service>`); users can also bind values manually on the
host with `sbx secret set <service>` or `sbx secret import`. Recognized
services:
openai, anthropic, gemini, cohere, groq, openrouter, ai21,
cloudflare, deepinfra, deepseek, mistral, perplexity, voyageai,
xai, jina, ernie, hunyuan, minimax, moonshot, qianwen, zhipuai
Inside the sandbox the corresponding env vars (OPENAI_API_KEY, etc.)
hold 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, so you must inject credentials yourself via
`sbx run --env AWS_ACCESS_KEY_ID=...` or a mixin kit that mounts a
service-account JSON. VertexAI regional endpoints are allow-listed via
`*.googleapis.com`. Bedrock runtime endpoints are allow-listed for
us-east-1/2, us-west-2, eu-west-1, eu-central-1, ap-southeast-2, and
ap-northeast-1 only; other regions need a mixin allow entry
(`bedrock-runtime.<region>.amazonaws.com`).
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)
+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.
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
+79
View File
@@ -0,0 +1,79 @@
---
description: AI-first design decomposition for any project. Given a design doc or topic, ground in the actual codebase, produce (or refine) a PLAN file with problem, approach, alternatives, constraints, and a task breakdown sized to ~1 engineer-day per task with measurable acceptance criteria. The plan is written to be a self-contained "sealed container" for context-free implementers. Grants filesystem access for grounding and for writing the plan.
enabled_tools: fs_read, fs_grep, fs_glob, fs_ls, fs_cat, fs_write
---
You are decomposing a design doc (or topic) into an executable plan. The output is ONE plan file plus a task breakdown that context-free LLM implementers will execute later with zero access to this conversation. Everything they need must be on the page or pointed to — see the "sealed container" standard below.
## Inputs
- A design doc (path or pasted), or a one-line problem statement.
- The target project directory (ground truth for all claims).
- The plans directory where the PLAN file lands.
## Step 1 — Ground before proposing
Plans written from memory rot on contact with the code. Before writing anything:
- Read the project's own orientation docs (`CLAUDE.md`, `AGENTS.md`, `CONTRIBUTING.md`, `README.md` at the project root) — conventions constrain the design.
- Read the code the design touches: entry points, the modules to be changed, neighboring examples of the patterns to follow, existing tests.
- `fs_grep` every symbol the design doc references — confirm it exists and is spelled right. Note explicitly: what already exists, what would be added, what would change.
- Verify build/test commands actually exist (`Makefile`, `justfile`, `package.json` scripts, CI config).
## Step 2 — The proposal
Produce a structured proposal (iterate with the user when interactive; in autonomous runs, resolve what the doc + code answer and flag the rest as open questions):
- **Problem** — one paragraph; state assumptions explicitly.
- **Scope** — In / Out. Call out tempting adjacent work being deferred.
- **Approach** — concrete: name files, symbols, data flow, migrations. Reference existing patterns by path.
- **Alternatives considered** — table of alternative → why rejected. Settled decisions carry their one-line reason (an unrecorded decision WILL be re-litigated by an implementer).
- **Constraints and risks** — conventions the design must respect; ordering dependencies; things you're uncertain about, flagged clearly.
- **Open questions** — ONLY questions the codebase cannot answer (business rules, priority calls). If none, say "No open questions."
- **Task breakdown** — see below.
## Task breakdown rules
| Rule | Why |
|---|---|
| **One task ≈ one engineer-day** | Variable task sizes destroy progress signal; anything larger gets decomposed NOW, not mid-run |
| Each task independently implementable and verifiable | It builds and its tests pass without later tasks existing |
| Explicit, acyclic dependencies (`blocked_by`) | Execution order must be derivable from the breakdown alone |
| Each task states WHERE (files/packages) and WHAT (observable outcome) | "Implement service layer" is not a task; "internal/foo/service.go: add Create/Get with validation — returns 400 on missing name" is |
| Measurable acceptance criteria per task | Criteria become the tests; "works correctly" is unmeasurable |
| Flag ⚠️ low-confidence sizing with the reason | Honest sizing beats optimistic sizing |
## Step 3 — Write the PLAN file
Write `PLAN-<slug>.md` (kebab-case slug from the topic; verify no collision) to the plans directory:
```markdown
---
slug: <slug>
status: draft # draft | active | implemented
created: YYYY-MM-DD
---
# <Title>
## Problem
## Scope (In / Out)
## Approach
## Alternatives considered
## Constraints and risks
## Open questions
## Task breakdown
| # | Task | Size | blocked_by | Notes |
|---|------|------|-----------|-------|
```
The plan is the implementers' entire context. Write for the "sealed container" standard: every question an implementer will hit is either answered inline or delegated via a pointer to the exact file/doc that answers it (where infra code goes, what DB tech, which layout to mirror, exact test commands). Paste short code snippets for load-bearing patterns — a path alone forces re-exploration; a stale claim fails the executor mid-implementation.
## Anti-patterns
- Proposing before reading the code — a design ungrounded in the actual codebase is fiction.
- "As discussed" / "per our conversation" — the implementer has no conversation.
- Tasks larger than a day hiding an "and then also…".
- Acceptance criteria describing implementation ("uses a for loop") instead of behavior.
- Open questions the code could have answered — grep first, ask last.
- Unrecorded decisions — every settled fork carries its reason.
+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
+89
View File
@@ -0,0 +1,89 @@
---
description: Gatekeep a plan for self-containedness before it is finalized. A plan must be a "sealed container" - either it answers every question a context-free LLM implementer will hit, or it points at the exact code/docs where the answer lives. Produces the missing questions and a PLAN_GATE SEALED/LEAKY verdict. Grants read-only filesystem access for verifying pointers actually resolve. Complements plan-review (executability) - this checks completeness of context, not correctness of approach.
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
---
You are gatekeeping a plan before it is finalized. The standard is the **sealed-container test**: a fresh LLM implementer with ZERO conversation context and ZERO tribal knowledge will execute this plan. Every question that implementer would need answered mid-implementation must be either (a) **answered inline** in the plan, or (b) **delegated via a pointer** — an exact file/doc path that verifiably contains the answer. A plan that assumes the reader "just knows" where infrastructure code lives, which DB tech to use, or how services are laid out is a leaky container: the implementer will guess, and guesses become divergences.
You are NOT reviewing the approach (that is `plan-review`'s job — executability, verifiability, ordering). You are auditing **completeness of context**. A plan with a flawless approach still fails this gate if it leaves the implementer to rediscover the environment.
## The answer-or-pointer rule
For every question in the manifest below, the plan must contain ONE of:
1. **Inline answer** — the fact stated directly ("the service DB is Postgres on RDS, provisioned via `infra/rds/`", "migrations live in `internal/db/migrations/` and use goose").
2. **Verified pointer** — a path to code or docs where the implementer can discover it ("read `CLAUDE.md` § Database conventions", "mirror the layout of `internal/services/rate_cards/`").
An answer of neither kind = a missing question = a leak. "Follow existing conventions" with no pointer to WHICH file shows the convention is a leak. A pointer to a file that doesn't exist or doesn't actually cover the topic is a leak wearing a pointer costume — which is why you verify.
## The manifest (question categories to audit)
Walk EVERY category. For each, ask: "when the implementer hits this, does the plan answer it or point to the answer?"
| # | Category | Questions the implementer WILL hit |
|---|----------|-------------------------------------|
| 1 | **Code placement** | Which repo? Which directory/package? Does a new service/module follow an existing layout — which one, exactly? |
| 2 | **Infrastructure** | Where does infra code live? What is the deployment target (e.g. new DB in RDS via Terraform vs a Postgres container in Kubernetes)? Who provisions it — this plan's tasks, or a prerequisite? |
| 3 | **Data layer** | What DB tech/engine? What migration tool and directory? What naming conventions for tables/columns? Which existing tables does this touch or reference? |
| 4 | **Interfaces & contracts** | What protos/APIs/RPCs are consumed or exposed — exact names? Where do proto definitions live and how are they regenerated? What downstream consumers depend on the shapes this plan creates? |
| 5 | **Conventions & tooling** | Which language/framework versions? Error-handling and logging patterns — which file shows the canon? Lint/format/build commands? Where is the repo's own CLAUDE.md / contributor doc and does the plan tell the implementer to read it? |
| 6 | **Testing & verification** | Test framework and directory conventions? EXACT commands to run tests/build from the repo root? What proves each acceptance criterion? |
| 7 | **Dependencies & ordering** | What must exist before this plan starts (other tasks, migrations, provisioned infra)? What does this plan produce that later work depends on? |
| 8 | **Config, secrets & environments** | New env vars/config keys — where are they declared and injected? Secrets — vault/parameter store conventions? Staging vs production differences that affect implementation? |
| 9 | **Scope boundaries** | Is Out of scope present and specific? Are "tempting adjacent fixes" explicitly deferred? |
| 10 | **Settled decisions** | Are choices that were debated recorded WITH their one-line reason ("RDS over in-cluster Postgres because ops owns backups")? An unrecorded decision WILL be re-litigated by the implementer. |
Not every category applies to every plan (a docs-only plan has no data layer). Mark inapplicable categories as such — silently skipping one is how leaks survive.
## Pointer verification (do not trust, verify)
For every pointer the plan offers:
1. `fs_ls` / `fs_glob` — the referenced path exists.
2. `fs_grep` / `fs_read` — the file actually covers the claimed topic. A plan saying "see `docs/database.md` for migration conventions" fails verification if that file never mentions migrations.
3. For "mirror the layout of X" pointers — confirm X exists and is a real example of what the plan claims (a service directory held up as the canonical layout should actually contain the layers the plan describes).
A broken pointer is worse than no pointer: it burns the implementer's time AND their trust in the rest of the plan.
## Severity honesty
Not every gap is equal. Tag each finding:
- **BLOCKING** — the implementer cannot proceed or will guess wrong with expensive consequences (wrong DB target, wrong repo, missing prerequisite).
- **FRICTION** — the implementer can discover the answer but will waste significant time re-exploring what the author already knew.
A plan with only FRICTION findings may still be sealed at the caller's discretion — say so. BLOCKING findings always mean LEAKY.
## Verdict format
End with EXACTLY one of:
```
PLAN_GATE: SEALED
Categories audited: N applicable, all answered or pointed.
<optional: 1-3 non-blocking observations>
```
```
PLAN_GATE: LEAKY
Missing questions (N):
1. [category] <the exact question the implementer will hit> — [BLOCKING|FRICTION] — <why they get stuck or guess wrong> — <suggested fix: the inline answer to add, or the pointer to insert (verified to exist)>
2. ...
Broken pointers (if any):
- <plan's pointer> — <what's wrong: path missing / doesn't cover topic>
```
Every missing question must be phrased as the QUESTION the implementer would actually ask ("where do I put the Terraform for the new RDS instance?"), not as an abstract complaint ("infra section is thin"). When you suggest a pointer as the fix, VERIFY it first — never recommend a pointer you haven't confirmed resolves.
## Scope discipline
- Do not redesign the approach. If the approach is coherent but under-documented, the fix is context, not redesign.
- Do not demand encyclopedic plans. The container test is "answered or pointed" — a tight plan full of verified pointers beats a bloated plan that inlines the whole wiki. Flag over-inlining only if it duplicates something that WILL drift (e.g. pasted conventions that contradict the source file).
- Three BLOCKING questions beat fifteen FRICTION nitpicks. If your list is all nitpicks, the plan is probably SEALED — say so.
## Anti-patterns
- Sealing a plan because the approach is good, without walking the manifest.
- Flagging "missing context" without phrasing the actual question the implementer would ask.
- Recommending a pointer you did not verify exists and covers the topic.
- Treating an inapplicable category as a leak (demanding a data-layer section from a docs-only plan).
- Re-reviewing executability/approach — that is `plan-review`'s lane.
+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
+87
View File
@@ -0,0 +1,87 @@
---
description: File-based task tracking for plan-driven runs on any project. Defines the TASK-NNN directory schema (index.md + append-only log.md), the frontmatter lifecycle (pending/in-progress/blocked/complete), numbering, the completion protocol, and follow-up task creation. The tasks directory on disk is the durable run state - it survives context compression. Grants filesystem access for managing task files.
enabled_tools: fs_read, fs_grep, fs_glob, fs_ls, fs_cat, fs_write, fs_patch, fs_mkdir
---
You are tracking implementation tasks as files. The task directory is the durable source of truth for run state — anything that lives only in chat history is lost to context compression. Keep it current at every state change, not in batches.
## Layout
```
<plans_dir>/
PLAN-<slug>.md # the plan (see design-session / plan-authoring)
tasks/
TASK-001-<slug>/
index.md # current state: frontmatter + What/Steps/Acceptance criteria
log.md # append-only audit trail
TASK-002-<slug>/
...
```
## index.md schema
```markdown
---
title: <short imperative title>
status: pending # pending | in-progress | blocked | complete
type: feature # feature | chore | followup
points: 1.0 # engineer-days; ~1.0 per the sizing rule
plan: PLAN-<slug>.md
blocked_by: [] # TASK ids that must be complete first
created: YYYY-MM-DD
---
## What
One paragraph: what this task produces, named concretely (files, symbols, behaviors).
## Steps
- [ ] Concrete step — name the file, function, or migration
- [ ] ...
## Acceptance criteria
- [ ] Observable behavior, measurable ("returns 429 after 3 failed attempts")
- [ ] ...
```
Status lives in frontmatter — there are no lifecycle directories. `status: complete` plus all boxes checked IS done.
## log.md conventions
Append-only. Each entry is an H2: `## YYYY-MM-DD — <short label>` (`created`, `started`, `implemented`, `diverged`, `completed`, ...). Body is 1-3 sentences of prose; structured data lives in markdown links (branch URLs, commit SHAs, PR links). Never rewrite an old entry — add a new one.
## Numbering
Scan `tasks/TASK-*` for the highest NNN and increment (zero-padded to 3). This assumes a single writer per plans directory; if multiple agents or people share one, serialize task creation.
## Lifecycle protocol
| Transition | Do |
|---|---|
| Create | `fs_mkdir` the dir; write `index.md` (status: pending) + `log.md` with a `created` entry |
| Claim | frontmatter `status: in-progress`; log `started` (note the branch + base SHA) |
| Blocked | `status: blocked`; log why and what unblocks it |
| Complete | Check off every Step and Acceptance criterion (verified, not aspirational); log `completed` with commit SHAs AND any follow-ups reported by the implementer, VERBATIM; set `status: complete` |
Never mark a criterion checked without evidence. Never batch state changes — update at the moment of transition.
## Follow-up tasks
When implementation surfaces manual/out-of-scope actions (secrets to create, cloud roles to provision, console steps, cross-repo changes): create a task per item (group small related ones) with `type: followup`, `status: pending`, the WHAT/WHERE/WHY/WHEN in its What section, and a note of which TASK surfaced it. Follow-ups are deliverables to hand to the user — never implement them in the current run.
## Consistency checks (run at the end of a run)
- Every task dir has both `index.md` and `log.md`.
- Every `blocked_by` reference resolves to an existing task.
- No task is `complete` with unchecked Steps/Acceptance criteria.
- Every `complete` task's log has a `completed` entry with commit references.
- The PLAN's breakdown table rows all map to task dirs (and vice versa).
## Anti-patterns
- Run state that exists only in chat — session ids, decisions, and follow-ups belong in task files.
- `status: complete` with unchecked boxes, or checked boxes without evidence.
- Rewriting log history instead of appending.
- Hand-picking a task number without scanning (collisions).
- Follow-ups mentioned in a summary but never materialized as task files.
+14
View File
@@ -7,12 +7,15 @@
# - <agent-name>_TOP_P
# - <agent-name>_GLOBAL_TOOLS (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>_VARIABLES (as JSON array of key-value pairs; e.g. '[{"name": "username", "value": "alex"}]')
model: openai:gpt-4o # Specify the LLM to use
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
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
name: <agent-name> # Name of the agent, used in the UI and logs
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.
# See https://github.com/Dark-Alex-17/coyote/wiki/Agents for detailed documentation.
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_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
@@ -51,6 +60,8 @@ enabled_skills: # Optional list of skills available when this a
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
instructions: | # Static instructions for the agent; ignored if dynamic instructions are used
@@ -90,6 +101,9 @@ conversation_starters: # Optional conversation starters for the agent
- What is the best way to exercise?
- How do I manage my time effectively?
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
- pdf:some-pdf-file.pdf # Explicitly tell Coyote to use the 'pdf' document loader using a relative path
- https://some-website.com/some-page
+72 -2
View File
@@ -2,6 +2,8 @@
model: openai:gpt-4o # Specify the LLM to use
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
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 ----
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 ----
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
# ---- Miscellaneous ----
@@ -31,7 +34,7 @@ sync_models_url: > # URL to sync model changes from
left_prompt:
'{color.red}{model}){color.green}{?session {?agent {agent}>}{session}{?role /}}{!session {?agent {agent}>}}{role}{?rag @{rag}}{color.cyan}{?session )}{!session >}{color.reset} '
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 ----
# 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):
# 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')
# - ast_grep.sh
# - demo_py.py
# - demo_sh.sh
# - demo_ts.ts
@@ -133,6 +137,14 @@ enabled_mcp_servers: null # Which MCP servers to enable by default.
# - slack
# Example (comma-separated form):
# 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 are modular knowledge or capability packs the LLM can load and unload mid-conversation.
@@ -175,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.'
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: '
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 ----
# See the [RAG Docs](https://github.com/Dark-Alex-17/coyote/wiki/RAG) for more details.
@@ -183,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_chunk_size: null # Defines the size of chunks for document processing in characters
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
rag_template: |
Answer the query based on the context while respecting the rules. (user query, some textual context and rules, all inside xml tags)
@@ -250,6 +292,7 @@ clients:
# extra:
# proxy: socks5://127.0.0.1:1080 # Set proxy
# connect_timeout: 10 # Set timeout in seconds for connect to api
# read_timeout: 300 # Set timeout in seconds for a read stall (no bytes received); 0 disables (default: 300)
# See https://platform.openai.com/docs/quickstart
- type: openai
@@ -309,11 +352,38 @@ clients:
api_base: https://api.mistral.ai/v1
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
name: xai
api_base: https://api.x.ai/v1
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
- type: openai-compatible
+4
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
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
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)
- fs_ls # or a comma-separated string (e.g. `enabled_tools: fs_ls,fs_cat`).
- fs_cat # Use `all` to enable every visible tool.
@@ -22,6 +24,8 @@ enabled_skills: # Skills available when this role is activ
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
# the model for output instead of using the instructions below
+1 -1
View File
@@ -14,7 +14,7 @@ class Coyote < Formula
sha256 "$hash_linux"
end
version "$version"
license "MIT"
license "AGPL-3.0-only"
def install
bin.install "coyote"
+6
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
temperature: 0.0 # Default sampling temperature 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
- web_search_coyote.sh
@@ -225,6 +227,9 @@ nodes:
chunk_size: 1000
chunk_overlap: 100
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
state_updates: # {{output}} = { context: <str>, sources: [<path>, ...] }
context: "{{output.context}}" # writes `context` -> `reducers.context = concat`
@@ -391,6 +396,7 @@ nodes:
- mcp:ddg-search # `mcp:<server>` includes that server's functions
model: claude:claude-haiku-4-5 # Optional per-node model 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_iterations: 10 # Tool-call-loop turn cap. Default 10.
fallback: review # Route here if all attempts fail
+13
View File
@@ -23,3 +23,16 @@ fmt:
[arg('build_type', pattern="debug|release")]
build build_type='debug':
@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 \
.
+457 -2
View File
@@ -3,6 +3,33 @@
# - https://platform.openai.com/docs/api-reference/chat
- provider: openai
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
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -10,6 +37,8 @@
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: medium
- name: gpt-5.5-pro
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -17,6 +46,8 @@
output_price: 180
supports_vision: true
supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: high
- name: gpt-5.4
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -24,6 +55,8 @@
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.4-pro
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -31,6 +64,8 @@
output_price: 180
supports_vision: true
supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: medium
- name: gpt-5.4-mini
max_input_tokens: 400000
max_output_tokens: 128000
@@ -38,6 +73,8 @@
output_price: 4.5
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.4-nano
max_input_tokens: 400000
max_output_tokens: 128000
@@ -45,6 +82,8 @@
output_price: 1.25
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: gpt-5.3-codex
max_input_tokens: 400000
max_output_tokens: 128000
@@ -52,6 +91,8 @@
output_price: 14
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh]
default_reasoning_effort: medium
- name: chat-latest
max_input_tokens: 400000
max_output_tokens: 128000
@@ -66,6 +107,17 @@
output_price: 14
supports_vision: 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
max_input_tokens: 400000
max_output_tokens: 128000
@@ -73,6 +125,8 @@
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high]
default_reasoning_effort: none
- name: gpt-5.1-chat-latest
max_input_tokens: 400000
max_output_tokens: 128000
@@ -80,6 +134,8 @@
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high]
default_reasoning_effort: none
- name: gpt-5
max_input_tokens: 400000
max_output_tokens: 128000
@@ -87,6 +143,8 @@
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: gpt-5-chat-latest
max_input_tokens: 400000
max_output_tokens: 128000
@@ -94,6 +152,8 @@
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: gpt-5-mini
max_input_tokens: 400000
max_output_tokens: 128000
@@ -151,6 +211,8 @@
supports_vision: true
supports_function_calling: true
system_prompt_prefix: Formatting re-enabled
reasoning_levels: [low, medium, high]
default_reasoning_effort: medium
patch:
body:
max_tokens: null
@@ -258,24 +320,38 @@
# - https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent
- provider: gemini
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
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: 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: 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: gemini-3.1-pro-preview
max_input_tokens: 1048576
max_output_tokens: 65535
@@ -283,6 +359,8 @@
output_price: 2.5
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash
max_input_tokens: 1048576
max_output_tokens: 65536
@@ -297,6 +375,8 @@
output_price: 0
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash-lite
max_input_tokens: 1000000
max_output_tokens: 64000
@@ -308,10 +388,14 @@
max_input_tokens: 1048576
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, high]
default_reasoning_level: high
- name: 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: gemma-3-27b-it
max_input_tokens: 131072
max_output_tokens: 8192
@@ -329,6 +413,26 @@
# - https://docs.anthropic.com/en/api/messages
- provider: claude
models:
- name: claude-opus-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 5
output_price: 25
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
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
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -337,6 +441,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-7
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -345,6 +451,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-6
max_input_tokens: 200000
max_output_tokens: 8192
@@ -353,6 +461,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: claude-opus-4-6:thinking
real_name: claude-opus-4-6
max_input_tokens: 200000
@@ -369,6 +479,16 @@
thinking:
type: enabled
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
max_input_tokens: 200000
max_output_tokens: 8192
@@ -377,6 +497,8 @@
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: claude-sonnet-4-6:thinking
real_name: claude-sonnet-4-6
max_input_tokens: 200000
@@ -700,14 +822,70 @@
# - https://docs.x.ai/docs/models
# - https://docs.x.ai/docs/api-reference#chat-completions
- 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:
- name: grok-4.6
input_price: 2
output_price: 6
max_input_tokens: 500000
supports_function_calling: true
- 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
max_input_tokens: 2000000
max_input_tokens: 1000000
input_price: 0.2
output_price: 0.5
supports_function_calling: true
- name: grok-4-1-fast-reasoning
max_input_tokens: 2000000
max_input_tokens: 1000000
input_price: 0.2
output_price: 0.5
supports_function_calling: true
@@ -819,18 +997,24 @@
input_price: 0.2
output_price: 1.5
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: 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: 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, high]
default_reasoning_effort: minimal
- name: gemini-3.1-pro-preview
max_input_tokens: 1048576
max_output_tokens: 65536
@@ -838,6 +1022,8 @@
output_price: 12
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash
max_input_tokens: 1048576
max_output_tokens: 65535
@@ -845,6 +1031,8 @@
output_price: 2.5
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: medium
- name: gemini-2.5-pro
max_input_tokens: 1048576
max_output_tokens: 65536
@@ -852,6 +1040,8 @@
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: gemini-2.5-flash-lite
max_input_tokens: 1048576
max_output_tokens: 65536
@@ -863,10 +1053,34 @@
max_input_tokens: 1048576
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, high]
default_reasoning_effort: high
- name: gemini-3-flash-preview
max_input_tokens: 1048576
supports_vision: true
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: high
- name: claude-opus-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 5
output_price: 25
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
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
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -875,6 +1089,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-7
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -883,6 +1099,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: claude-opus-4-6
max_input_tokens: 200000
max_output_tokens: 8192
@@ -906,6 +1124,16 @@
thinking:
type: enabled
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
max_input_tokens: 200000
max_output_tokens: 8192
@@ -914,6 +1142,8 @@
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: claude-sonnet-4-6:thinking
real_name: claude-sonnet-4-6
max_input_tokens: 200000
@@ -1038,6 +1268,26 @@
# - https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference-call.html
- provider: bedrock
models:
- name: us.anthropic.claude-opus-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 5
output_price: 25
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- 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
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -1046,6 +1296,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-7
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -1054,6 +1306,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-6-v1
max_input_tokens: 200000
max_output_tokens: 8192
@@ -1062,6 +1316,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: us.anthropic.claude-opus-4-6-v1:thinking
real_name: us.anthropic.claude-opus-4-6-v1
max_input_tokens: 200000
@@ -1079,6 +1335,16 @@
thinking:
type: enabled
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
max_input_tokens: 200000
max_output_tokens: 8192
@@ -1087,6 +1353,8 @@
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: us.anthropic.claude-sonnet-4-6:thinking
real_name: us.anthropic.claude-sonnet-4-6
max_input_tokens: 200000
@@ -1468,6 +1736,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
- provider: moonshot
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
max_input_tokens: 262144
input_price: 0.56
@@ -1502,6 +1794,18 @@
# - https://platform.deepseek.com/api-docs/api/create-chat-completion
- provider: deepseek
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
max_input_tokens: 64000
max_output_tokens: 8192
@@ -1570,6 +1874,16 @@
# - https://platform.minimaxi.com/document/ChatCompletion%20v2
- provider: minimax
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
max_input_tokens: 204800
input_price: 0.294
@@ -1596,6 +1910,33 @@
# - https://openrouter.ai/docs/api-reference/chat-completion
- provider: openrouter
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
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -1603,6 +1944,8 @@
output_price: 30
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5.5-pro
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -1610,6 +1953,8 @@
output_price: 180
supports_vision: true
supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: high
- name: openai/gpt-5.4
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -1617,6 +1962,8 @@
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.4-pro
max_input_tokens: 1050000
max_output_tokens: 128000
@@ -1624,6 +1971,8 @@
output_price: 180
supports_vision: true
supports_function_calling: true
reasoning_levels: [medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5.4-mini
max_input_tokens: 400000
max_output_tokens: 128000
@@ -1631,6 +1980,8 @@
output_price: 4.5
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.4-nano
max_input_tokens: 400000
max_output_tokens: 128000
@@ -1638,6 +1989,8 @@
output_price: 1.25
supports_vision: true
supports_function_calling: true
reasoning_levels: [none, low, medium, high, xhigh]
default_reasoning_effort: none
- name: openai/gpt-5.3-codex
max_input_tokens: 400000
max_output_tokens: 128000
@@ -1645,6 +1998,8 @@
output_price: 14
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh]
default_reasoning_effort: medium
- name: openai/gpt-5.2
max_input_tokens: 400000
max_output_tokens: 128000
@@ -1652,6 +2007,17 @@
output_price: 14
supports_vision: 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
max_input_tokens: 400000
max_output_tokens: 128000
@@ -1659,6 +2025,8 @@
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [minimal, low, medium, high]
default_reasoning_effort: medium
- name: openai/gpt-5-mini
max_input_tokens: 400000
max_output_tokens: 128000
@@ -1696,18 +2064,67 @@
input_price: 0.04
output_price: 0.16
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
max_input_tokens: 1048576
input_price: 0.3
output_price: 2.5
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: low
- name: google/gemini-2.5-pro
max_input_tokens: 1048576
input_price: 1.25
output_price: 10
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high]
default_reasoning_effort: high
- name: google/gemini-2.5-flash-lite
max_input_tokens: 1048576
input_price: 0.3
@@ -1729,6 +2146,26 @@
max_input_tokens: 131072
input_price: 0.1
output_price: 0.2
- name: anthropic/claude-opus-5
max_input_tokens: 1000000
max_output_tokens: 128000
require_max_tokens: true
input_price: 5
output_price: 25
supports_function_calling: true
supports_vision: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- 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
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -1737,6 +2174,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4-7
max_input_tokens: 1000000
max_output_tokens: 128000
@@ -1745,6 +2184,8 @@
output_price: 25
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, xhigh, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4.6
max_input_tokens: 200000
max_output_tokens: 8192
@@ -1753,6 +2194,18 @@
output_price: 25
supports_vision: 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
max_input_tokens: 200000
max_output_tokens: 8192
@@ -1761,6 +2214,8 @@
output_price: 15
supports_vision: true
supports_function_calling: true
reasoning_levels: [low, medium, high, max]
default_reasoning_effort: high
- name: anthropic/claude-opus-4.5
max_input_tokens: 200000
max_output_tokens: 8192
+3 -3
View File
@@ -39,7 +39,7 @@ switch ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture) {
if (-not $BinDir) {
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
@@ -95,13 +95,13 @@ if ($asset.name -match '\.zip$') {
[System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir)
} elseif ($asset.name -match '\.tar\.gz$' -or $asset.name -match '\.tgz$') {
$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 {
try { Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir) }
catch {
$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
fi
DL_URLS=$(grep -oE '"browser_download_url":[[:space:]]*"[^"]+"' "$JSON" \
| sed -E 's/.*"browser_download_url":[[:space:]]*"//; s/"$//' \
|| true)
ASSET_NAME=""; ASSET_URL=""
for candidate in "${ASSET_CANDIDATES[@]}"; do
NAME=$(grep -oE '"name":\s*"[^"]+"' "$JSON" | sed 's/"name":\s*"//; s/"$//' | grep -Fx "$candidate" || true)
if [[ -n "$NAME" ]]; then
ASSET_NAME="$NAME"
ASSET_URL=$(awk -v pat="$NAME" '
BEGIN{ FS=":"; want=0 }
/"name"/ {
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
while IFS= read -r url; do
[[ -z "$url" ]] && continue
if [[ "$url" == */"$candidate" ]]; then
ASSET_NAME="$candidate"
ASSET_URL="$url"
break
fi
done <<< "$DL_URLS"
[[ -n "$ASSET_URL" ]] && break
done
if [[ -z "$ASSET_URL" ]]; then
+4
View File
@@ -0,0 +1,4 @@
mod server;
mod types;
pub use server::run_acp_server;
+670
View File
@@ -0,0 +1,670 @@
use super::types::{METHOD_NOT_FOUND, PARSE_ERROR, Request, Response};
use crate::client::call_chat_completions_streaming;
use crate::config::{Input, RenderMode, RequestContext};
use crate::function::supervisor::{GuardrailAction, check_pending_agents_guardrail};
use crate::utils;
use crate::utils::AbortSignal;
use anyhow::Result;
use serde_json::{Value, json};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
pub(crate) struct AcpServerState {
ctx: Option<RequestContext>,
abort: AbortSignal,
session_active: bool,
}
pub async fn run_acp_server(ctx: RequestContext, abort: AbortSignal) -> Result<()> {
let state = AcpServerState {
ctx: Some(ctx),
abort,
session_active: false,
};
run_acp_server_with_state(tokio::io::stdin(), tokio::io::stdout(), state).await
}
#[cfg(test)]
pub(crate) async fn run_acp_server_on<R, W>(reader: R, writer: W) -> Result<()>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
use crate::utils::{create_abort_signal, drain_acp_permissions};
drain_acp_permissions();
let state = AcpServerState {
ctx: None,
abort: create_abort_signal(),
session_active: false,
};
run_acp_server_with_state(reader, writer, state).await
}
async fn run_acp_server_with_state<R, W>(
reader: R,
mut writer: W,
mut state: AcpServerState,
) -> Result<()>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
let reader = BufReader::new(reader);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await? {
let line = line.trim().to_string();
if line.is_empty() {
continue;
}
if let Some(response) = dispatch(&line, &mut state).await {
for params in utils::drain_acp_permissions() {
emit_notification(&mut writer, "session/request_permission", params).await?;
}
emit(&mut writer, &response).await?;
}
}
Ok(())
}
async fn dispatch(raw: &str, state: &mut AcpServerState) -> Option<Response> {
let req: Request = match serde_json::from_str(raw) {
Ok(r) => r,
Err(_) => return Some(Response::err(None, PARSE_ERROR, "Parse error")),
};
// session/cancel is a notification. Handle it regardless of whether an id is present.
if req.method == "session/cancel" {
handle_session_cancel(state);
return if req.id.is_some() {
Some(Response::ok(req.id, json!({})))
} else {
None
};
}
req.id.as_ref()?;
Some(match req.method.as_str() {
"initialize" => handle_initialize(req),
"session/new" => handle_session_new(req, state).await,
"session/load" => handle_session_load(req, state).await,
"session/prompt" => handle_session_prompt(req, state).await,
_ => Response::err(
req.id,
METHOD_NOT_FOUND,
format!("Method not found: {}", req.method),
),
})
}
fn handle_initialize(req: Request) -> Response {
Response::ok(
req.id,
json!({
"name": "coyote",
"version": env!("CARGO_PKG_VERSION"),
"protocolVersion": 1,
}),
)
}
async fn handle_session_new(req: Request, state: &mut AcpServerState) -> Response {
if state.session_active {
return Response::err(
req.id,
-32000,
"Session already active; this server supports one session per process",
);
}
let ctx = match state.ctx.as_mut() {
Some(c) => c,
None => {
state.session_active = true;
return Response::ok(req.id, json!({ "sessionId": "default" }));
}
};
let app = Arc::clone(&ctx.app.config);
let abort = state.abort.clone();
match ctx.use_session(app.as_ref(), None, abort).await {
Ok(_) => {
state.session_active = true;
ctx.render_mode = RenderMode::Silent;
Response::ok(req.id, json!({ "sessionId": "default" }))
}
Err(e) => Response::err(req.id, -32000, format!("Failed to create session: {e}")),
}
}
async fn handle_session_prompt(req: Request, state: &mut AcpServerState) -> Response {
if !state.session_active {
return Response::err(req.id, -32000, "No active session; call session/new first");
}
let params = req.params.as_ref();
let from_content_blocks: Option<String> = params
.and_then(|p| p.get("prompt"))
.and_then(Value::as_array)
.map(|blocks| {
blocks
.iter()
.filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
.filter_map(|b| b.get("text").and_then(Value::as_str))
.collect::<Vec<_>>()
.join("\n")
})
.filter(|s| !s.is_empty());
let from_text: Option<String> = params
.and_then(|p| p.get("text"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string);
let text = match from_content_blocks.or(from_text) {
Some(t) => t,
None => {
return Response::err(
req.id,
-32602,
"Missing params: expected prompt (ContentBlock array) or text",
);
}
};
let ctx = match state.ctx.as_mut() {
Some(c) => c,
None => return Response::err(req.id, -32000, "Server not configured with a context"),
};
let abort = state.abort.clone();
match run_prompt_turn(ctx, &text, abort).await {
Ok(output) => Response::ok(
req.id,
json!({ "output": output, "stopReason": "end_turn" }),
),
Err(e) => Response::err(req.id, -32000, format!("Prompt failed: {e}")),
}
}
async fn run_prompt_turn(
ctx: &mut RequestContext,
text: &str,
abort: AbortSignal,
) -> Result<String> {
ctx.render_mode = RenderMode::Silent;
let mut input = Input::from_str(ctx, text, None)?;
loop {
ctx.before_chat_completion(&input)?;
let client = input.create_client()?;
let (output, tool_results) =
call_chat_completions_streaming(&input, client.as_ref(), ctx, abort.clone()).await?;
let app = Arc::clone(&ctx.app.config);
ctx.after_chat_completion(app.as_ref(), &input, &output, &tool_results)?;
if !tool_results.is_empty() {
input = input.merge_tool_results(output, tool_results);
continue;
}
match check_pending_agents_guardrail(ctx) {
GuardrailAction::Inject(prompt) => {
input = Input::from_str(ctx, &prompt, None)?;
}
GuardrailAction::ForceTerminate(ids) => {
warn!(
"Pending-agent guardrail force-cancelled {} agent(s): {:?}",
ids.len(),
ids
);
return Ok(output);
}
GuardrailAction::NoAction => return Ok(output),
}
}
}
fn handle_session_cancel(state: &mut AcpServerState) {
state.abort.set_ctrlc();
}
async fn handle_session_load(req: Request, state: &mut AcpServerState) -> Response {
if state.session_active {
return Response::err(req.id, -32000, "Session already active");
}
let session_name = match req
.params
.as_ref()
.and_then(|p| p.get("sessionId"))
.and_then(Value::as_str)
{
Some(n) => n.to_string(),
None => return Response::err(req.id, -32602, "Missing params.sessionId"),
};
let ctx = match state.ctx.as_mut() {
Some(c) => c,
None => return Response::err(req.id, -32000, "Server not configured with a context"),
};
let app = Arc::clone(&ctx.app.config);
let abort = state.abort.clone();
match ctx
.use_session(app.as_ref(), Some(&session_name), abort)
.await
{
Ok(_) => {
state.session_active = true;
ctx.render_mode = RenderMode::Silent;
Response::ok(req.id, json!({ "sessionId": session_name }))
}
Err(e) => Response::err(req.id, -32000, format!("Failed to load session: {e}")),
}
}
async fn emit<W: AsyncWrite + Unpin>(writer: &mut W, response: &Response) -> Result<()> {
let mut line = serde_json::to_string(response)?;
line.push('\n');
writer.write_all(line.as_bytes()).await?;
writer.flush().await?;
Ok(())
}
async fn emit_notification<W: AsyncWrite + Unpin>(
writer: &mut W,
method: &str,
params: Value,
) -> Result<()> {
let frame = json!({
"jsonrpc": "2.0",
"method": method,
"params": params,
});
let mut line = serde_json::to_string(&frame)?;
line.push('\n');
writer.write_all(line.as_bytes()).await?;
writer.flush().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::str;
#[tokio::test]
async fn all_stdout_is_valid_json_rpc() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"name":"test","version":"0.1.0"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
for line in output.split(|&b| b == b'\n').filter(|l| !l.is_empty()) {
let s = str::from_utf8(line).expect("non-UTF8 in ACP stdout");
let _: Value = serde_json::from_str(s)
.unwrap_or_else(|_| panic!("ACP stdout not valid JSON: {s}"));
}
}
#[tokio::test]
async fn unknown_method_returns_method_not_found() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":2,"method":"nonexistent","params":{}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["error"]["code"], METHOD_NOT_FOUND);
assert_eq!(v["id"], 2);
}
#[tokio::test]
async fn invalid_json_returns_parse_error() {
let input = "not json\n";
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["error"]["code"], PARSE_ERROR);
}
#[tokio::test]
async fn notification_without_id_produces_no_output() {
let input = concat!(
r#"{"jsonrpc":"2.0","method":"session/cancel","params":{}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
assert!(output.is_empty());
}
#[tokio::test]
async fn initialize_returns_server_info() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"name":"test","version":"0.1.0"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["id"], 1);
assert_eq!(v["result"]["name"], "coyote");
assert!(v["result"]["version"].is_string());
}
#[tokio::test]
async fn session_new_returns_session_id() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":10,"method":"session/new","params":{}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["id"], 10);
assert_eq!(v["result"]["sessionId"], "default");
}
#[tokio::test]
async fn session_new_twice_errors() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#,
"\n",
r#"{"jsonrpc":"2.0","id":2,"method":"session/new","params":{}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let mut lines = s.lines().filter(|l| !l.is_empty());
let first: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
let second: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
assert!(first["result"]["sessionId"].is_string());
assert_eq!(second["error"]["code"], -32000);
}
#[tokio::test]
async fn session_prompt_without_session_errors() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"text":"hello"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["id"], 3);
assert_eq!(v["error"]["code"], -32000);
}
#[tokio::test]
async fn session_prompt_with_no_context_returns_error() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#,
"\n",
r#"{"jsonrpc":"2.0","id":2,"method":"session/prompt","params":{"text":"hello"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let mut lines = s.lines().filter(|l| !l.is_empty());
let first: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
let second: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
assert_eq!(first["result"]["sessionId"], "default");
assert_eq!(second["id"], 2);
assert!(
second["error"].is_object(),
"expected error response when no ctx"
);
}
#[tokio::test]
async fn session_cancel_notification_produces_no_output() {
let input = concat!(r#"{"jsonrpc":"2.0","method":"session/cancel"}"#, "\n",);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
assert!(output.is_empty());
}
#[tokio::test]
async fn session_cancel_request_returns_ok() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":99,"method":"session/cancel"}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["id"], 99);
assert!(v["result"].is_object());
}
#[tokio::test]
async fn session_load_missing_session_id_errors() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":5,"method":"session/load","params":{}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["id"], 5);
assert_eq!(v["error"]["code"], -32602);
}
#[tokio::test]
async fn session_load_after_session_new_errors() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#,
"\n",
r#"{"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"abc"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let mut lines = s.lines().filter(|l| !l.is_empty());
let _first: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
let second: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
assert_eq!(second["id"], 2);
assert_eq!(second["error"]["code"], -32000);
}
#[tokio::test]
async fn session_load_with_no_context_returns_error() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":6,"method":"session/load","params":{"sessionId":"my-session"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["id"], 6);
assert!(v["error"].is_object());
}
#[tokio::test]
async fn emit_notification_produces_valid_json_rpc_frame() {
let mut output = Vec::new();
emit_notification(
&mut output,
"session/request_permission",
json!({"action": "confirm", "question": "Proceed?"}),
)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert_eq!(v["jsonrpc"], "2.0");
assert_eq!(v["method"], "session/request_permission");
assert!(v["params"]["action"].is_string());
assert!(!v.as_object().unwrap().contains_key("id"));
}
#[tokio::test]
async fn initialize_protocol_version_is_number() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let v: Value = serde_json::from_str(s.trim()).unwrap();
assert!(
v["result"]["protocolVersion"].is_number(),
"protocolVersion must be a JSON number, got: {:?}",
v["result"]["protocolVersion"]
);
assert_eq!(v["result"]["protocolVersion"], 1);
}
#[tokio::test]
async fn session_prompt_spec_content_blocks_not_rejected() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#,
"\n",
r#"{"jsonrpc":"2.0","id":2,"method":"session/prompt","params":{"sessionId":"default","prompt":[{"type":"text","text":"hello"}]}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let mut lines = s.lines().filter(|l| !l.is_empty());
let _first: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
let second: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
assert_eq!(second["id"], 2);
let code = second["error"]["code"].as_i64().unwrap_or(0);
assert_ne!(
code, -32602,
"spec-shaped ContentBlock prompt must not get a params error"
);
}
#[tokio::test]
async fn session_prompt_non_text_blocks_ignored() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#,
"\n",
r#"{"jsonrpc":"2.0","id":2,"method":"session/prompt","params":{"prompt":[{"type":"image","data":"abc"},{"type":"text","text":"hello"}]}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let mut lines = s.lines().filter(|l| !l.is_empty());
let _first: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
let second: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
assert_eq!(second["id"], 2);
let code = second["error"]["code"].as_i64().unwrap_or(0);
assert_ne!(code, -32602, "non-text blocks must be silently ignored");
}
#[tokio::test]
async fn session_prompt_missing_both_text_and_prompt_errors() {
let input = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"session/new","params":{}}"#,
"\n",
r#"{"jsonrpc":"2.0","id":2,"method":"session/prompt","params":{"sessionId":"default"}}"#,
"\n",
);
let mut output = Vec::new();
run_acp_server_on(input.as_bytes(), &mut output)
.await
.unwrap();
let s = String::from_utf8(output).unwrap();
let mut lines = s.lines().filter(|l| !l.is_empty());
let _first: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
let second: Value = serde_json::from_str(lines.next().unwrap()).unwrap();
assert_eq!(second["id"], 2);
assert_eq!(second["error"]["code"], -32602);
}
}
+59
View File
@@ -0,0 +1,59 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const METHOD_NOT_FOUND: i32 = -32601;
pub const PARSE_ERROR: i32 = -32700;
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct Request {
pub jsonrpc: String,
pub id: Option<Value>,
pub method: String,
pub params: Option<Value>,
}
#[derive(Debug, Serialize)]
pub struct Response {
pub jsonrpc: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Value>,
#[serde(flatten)]
pub body: ResponseBody,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ResponseBody {
Ok { result: Value },
Err { error: RpcError },
}
#[derive(Debug, Serialize)]
pub struct RpcError {
pub code: i32,
pub message: String,
}
impl Response {
pub fn ok(id: Option<Value>, result: Value) -> Self {
Self {
jsonrpc: "2.0",
id,
body: ResponseBody::Ok { result },
}
}
pub fn err(id: Option<Value>, code: i32, message: impl Into<String>) -> Self {
Self {
jsonrpc: "2.0",
id,
body: ResponseBody::Err {
error: RpcError {
code,
message: message.into(),
},
},
}
}
}
+40 -5
View File
@@ -1,13 +1,13 @@
use crate::client::{ModelType, list_models};
use crate::config::paths;
use crate::config::{AppConfig, Config, list_agents, list_sessions};
use crate::config::{AppConfig, Config, list_agents_with_descriptions, list_sessions};
use crate::utils::list_file_names;
use crate::vault::Vault;
use clap_complete::{CompletionCandidate, Shell, generate};
use clap_complete_nushell::Nushell;
use std::env;
use std::ffi::OsStr;
use std::io;
use std::{env, fs};
const COYOTE_CLI_NAME: &str = "coyote";
@@ -73,10 +73,17 @@ pub(super) fn role_completer(current: &OsStr) -> Vec<CompletionCandidate> {
pub(super) fn agent_completer(current: &OsStr) -> Vec<CompletionCandidate> {
let cur = current.to_string_lossy();
list_agents()
list_agents_with_descriptions()
.into_iter()
.filter(|a| a.starts_with(&*cur))
.map(CompletionCandidate::new)
.filter(|(a, _)| a.starts_with(&*cur))
.map(|(name, desc)| {
let help = if desc.is_empty() {
None
} else {
Some(desc.into())
};
CompletionCandidate::new(name).help(help)
})
.collect()
}
@@ -134,6 +141,34 @@ pub(super) fn session_completer(current: &OsStr) -> Vec<CompletionCandidate> {
.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> {
let cur = current.to_string_lossy();
match load_app_config_for_completion() {
+404 -100
View File
@@ -1,18 +1,32 @@
mod completer;
use crate::cli::completer::{
ShellCompletion, agent_completer, macro_completer, model_completer, rag_completer,
role_completer, secrets_completer, session_completer,
ShellCompletion, agent_completer, macro_completer, mcp_server_completer, model_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 clap::ValueHint;
use clap::{ArgGroup, ValueHint};
use clap::{Parser, crate_authors, crate_description, crate_version};
use clap_complete::ArgValueCompleter;
use is_terminal::IsTerminal;
use std::collections::HashSet;
use std::io::{Read, stdin};
#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpTransportArg {
Stdio,
Http,
Sse,
}
#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum McpScopeArg {
#[default]
User,
Workspace,
}
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
#[command(
@@ -27,9 +41,31 @@ use std::io::{Read, stdin};
{usage-heading} {usage}
{all-args}{after-help}
"
",
group(
ArgGroup::new("sbx-mode")
.args(["sandbox", "fresh"])
.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",
])
),
group(
ArgGroup::new("mcp-action")
.args(["mcp_add", "mcp_remove", "mcp_list", "mcp_get"])
.multiple(false)
),
)]
pub struct Cli {
/// Input text
#[arg(allow_hyphen_values = true)]
text: Vec<String>,
/// Select a LLM model
#[arg(short, long, add = ArgValueCompleter::new(model_completer))]
pub model: Option<String>,
@@ -39,30 +75,6 @@ pub struct Cli {
/// Select a role
#[arg(short, long, add = ArgValueCompleter::new(role_completer))]
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
#[arg(short = 'e', long)]
pub execute: bool,
@@ -75,92 +87,252 @@ pub struct Cli {
/// Turn off stream mode
#[arg(short = 'S', long)]
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
#[arg(long)]
pub dry_run: bool,
/// Display information
/// Disable loading workspace MCP servers from .coyote/mcp.json, .coyote/.mcp.json, or .mcp.json
#[arg(long)]
pub info: bool,
/// Build all configured Bash tool scripts
pub no_workspace_mcp: bool,
/// Disable memory for this invocation
#[arg(long)]
pub build_tools: bool,
/// Reinstall bundled assets, overwriting any local changes
#[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
pub no_memory: bool,
/// Disable loading workspace instructions (COYOTE.md/AGENTS.md/CLAUDE.md/etc.) for this invocation
#[arg(long)]
pub sync_models: bool,
/// List all available chat models
pub no_workspace_instructions: bool,
/// 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)]
pub list_models: bool,
/// List all roles
#[arg(long)]
pub list_roles: bool,
/// List all sessions
#[arg(long)]
pub list_sessions: bool,
/// List all agents
#[arg(long)]
pub list_agents: bool,
/// List all RAGs
#[arg(long)]
pub list_rags: bool,
/// List all macros
#[arg(long)]
pub list_macros: bool,
/// List all installed skills
#[arg(long)]
pub list_skills: bool,
pub dangerously_skip_permissions: bool,
/// Start or join a session
#[arg(short = 's', long, help_heading = "Session & Memory", add = ArgValueCompleter::new(session_completer))]
pub session: Option<Option<String>>,
/// Ensure the session is empty
#[arg(long, help_heading = "Session & Memory")]
pub empty_session: bool,
/// Ensure the new conversation is saved to the session
#[arg(long, help_heading = "Session & Memory")]
pub save_session: bool,
/// Bootstrap a memory marker so coyote begins loading memory next run
#[arg(
long,
value_name = "SCOPE",
value_enum,
help_heading = "Session & Memory"
)]
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
/// `--skill <NAME>` is given and the skill doesn't exist, opens $EDITOR
/// with a scaffold to create it.
#[arg(long, value_name = "NAME")]
#[arg(long, value_name = "NAME", help_heading = "Session & Memory")]
pub skill: Vec<String>,
/// Input text
#[arg(trailing_var_arg = true)]
text: Vec<String>,
/// Tail logs
#[arg(long)]
pub tail_logs: bool,
/// Disable colored log output
#[arg(long, requires = "tail_logs")]
pub disable_log_colors: bool,
/// Add a secret to the Coyote vault
#[arg(long, value_name = "SECRET_NAME", exclusive = true)]
pub add_secret: Option<String>,
/// Decrypt a secret from the Coyote vault and print the plaintext
#[arg(long, value_name = "SECRET_NAME", exclusive = true, 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, 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, add = ArgValueCompleter::new(secrets_completer))]
pub delete_secret: Option<String>,
/// List all secrets stored in the Coyote vault
#[arg(long, exclusive = true)]
pub list_secrets: bool,
/// Authenticate with an LLM provider using OAuth (e.g., --authenticate client_name)
#[arg(long, exclusive = true, value_name = "CLIENT_NAME")]
pub authenticate: Option<Option<String>>,
/// Generate static shell completion scripts
#[arg(long, value_name = "SHELL", value_enum)]
pub completions: Option<ShellCompletion>,
/// Start an agent
#[arg(short = 'a', long, help_heading = "Agents, RAG & Macros", add = ArgValueCompleter::new(agent_completer))]
pub agent: Option<String>,
/// Set agent variables
#[arg(long, value_names = ["NAME", "VALUE"], num_args = 2, help_heading = "Agents, RAG & Macros")]
pub agent_variable: Vec<String>,
/// Start a RAG
#[arg(long, help_heading = "Agents, RAG & Macros", add = ArgValueCompleter::new(rag_completer))]
pub rag: Option<String>,
/// Rebuild the RAG to sync document changes
#[arg(long, help_heading = "Agents, RAG & Macros")]
pub rebuild_rag: bool,
/// Execute a macro
#[arg(long = "macro", value_name = "MACRO", help_heading = "Agents, RAG & Macros", add = ArgValueCompleter::new(macro_completer))]
pub macro_name: Option<String>,
/// List all available chat models
#[arg(long, help_heading = "List & Discovery")]
pub list_models: bool,
/// List all roles
#[arg(long, help_heading = "List & Discovery")]
pub list_roles: bool,
/// List all sessions
#[arg(long, help_heading = "List & Discovery")]
pub list_sessions: bool,
/// List all agents
#[arg(long, help_heading = "List & Discovery")]
pub list_agents: bool,
/// 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
#[arg(long, value_name = "VERSION")]
#[arg(long, value_name = "VERSION", help_heading = "Installation & Updates")]
pub update: Option<Option<String>>,
/// 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,
/// 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>,
/// Add an MCP server. Use `-- <cmd> [args...]` for stdio, or `--url <URL>` for http/sse.
#[arg(long, value_name = "NAME", help_heading = "MCP Servers")]
pub mcp_add: Option<String>,
/// Remove an MCP server by name
#[arg(long, value_name = "NAME", help_heading = "MCP Servers", add = ArgValueCompleter::new(mcp_server_completer))]
pub mcp_remove: Option<String>,
/// List all configured MCP servers (user + workspace scopes)
#[arg(long, help_heading = "MCP Servers")]
pub mcp_list: bool,
/// Show the JSON config for one MCP server
#[arg(long, value_name = "NAME", help_heading = "MCP Servers", add = ArgValueCompleter::new(mcp_server_completer))]
pub mcp_get: Option<String>,
/// Transport for --mcp-add: stdio (default when `--` present), http, or sse
#[arg(
long,
value_enum,
value_name = "TRANSPORT",
help_heading = "MCP Servers"
)]
pub transport: Option<McpTransportArg>,
/// URL for http/sse MCP server (used with --mcp-add)
#[arg(long, value_name = "URL", help_heading = "MCP Servers")]
pub url: Option<String>,
/// Scope for MCP config: user (~/.config/coyote/functions/mcp.json) or workspace (./.coyote/mcp.json). Default: user
#[arg(long, value_enum, value_name = "SCOPE", help_heading = "MCP Servers")]
pub scope: Option<McpScopeArg>,
/// Environment variable for stdio MCP server (repeatable): --env KEY=VALUE
#[arg(long, value_name = "KEY=VALUE", help_heading = "MCP Servers")]
pub env: Vec<String>,
/// HTTP header for http/sse MCP server (repeatable): --header "Name: Value"
#[arg(long, value_name = "HEADER", help_heading = "MCP Servers")]
pub header: Vec<String>,
/// Working directory for stdio MCP server
#[arg(long, value_name = "PATH", value_hint = ValueHint::AnyPath, help_heading = "MCP Servers")]
pub cwd: Option<String>,
/// OAuth client ID for http/sse MCP server
#[arg(long, value_name = "ID", help_heading = "MCP Servers")]
pub client_id: Option<String>,
/// OAuth client secret for http/sse MCP server (use {{NAME}} to reference a vault secret)
#[arg(long, value_name = "SECRET", help_heading = "MCP Servers")]
pub client_secret: Option<String>,
/// OAuth callback port for http/sse MCP server
#[arg(long, value_name = "PORT", help_heading = "MCP Servers")]
pub callback_port: Option<u16>,
/// OAuth redirect host for http/sse MCP server
#[arg(long, value_name = "HOST", help_heading = "MCP Servers")]
pub redirect_host: Option<String>,
/// Overwrite an existing MCP server (with --mcp-add) or skip confirmation (with --mcp-remove)
#[arg(long, help_heading = "MCP Servers")]
pub mcp_force: bool,
/// 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>>,
/// Start the sandbox with a clean slate. No copied config or tokens; LLM credentials injected via sbx proxy
#[arg(long, requires = "sandbox", help_heading = "Sandbox")]
pub fresh: bool,
/// Declare that no human is present. All user-interaction tools return structured JSON instead of
/// prompting. Implies --dangerously-skip-permissions. Incompatible with REPL mode (requires a prompt).
#[arg(long, help_heading = "Sandbox")]
pub headless: bool,
/// Run as an ACP agent server over stdio (JSON-RPC 2.0). Every stdout byte must be valid JSON-RPC.
/// Implies --headless. Single session per process.
#[arg(long, help_heading = "Sandbox")]
pub acp_server: 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>,
/// Stdio command for --mcp-add: everything after `--` is passed to the server verbatim
#[arg(
last = true,
allow_hyphen_values = true,
value_name = "CMD",
help_heading = "MCP Servers"
)]
pub mcp_command: Vec<String>,
}
impl Cli {
@@ -393,6 +565,40 @@ mod tests {
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]
fn parse_headless_flag() {
let cli = parse(&["--headless", "do something"]);
assert!(cli.headless);
}
#[test]
fn parse_headless_default_off() {
assert!(!parse(&[]).headless);
}
#[test]
fn parse_acp_server_flag() {
let cli = parse(&["--acp-server"]);
assert!(cli.acp_server);
}
#[test]
fn parse_acp_server_default_off() {
assert!(!parse(&[]).acp_server);
}
#[test]
fn parse_sync_models_flag() {
let cli = parse(&["--sync-models"]);
@@ -489,4 +695,102 @@ mod tests {
fn parse_force_without_update_fails() {
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_mcp_add_stdio_with_trailing_command() {
let cli = parse(&[
"--mcp-add",
"myserver",
"--",
"npx",
"some-server",
"--flag",
"arg1",
]);
assert_eq!(cli.mcp_add, Some("myserver".to_string()));
assert_eq!(
cli.mcp_command,
vec!["npx", "some-server", "--flag", "arg1"]
);
assert!(cli.text.is_empty());
}
#[test]
fn parse_mcp_add_stdio_with_env_and_command() {
let cli = parse(&[
"--mcp-add",
"s",
"--env",
"API_KEY={{API_KEY}}",
"--env",
"MODE=dev",
"--",
"npx",
"srv",
]);
assert_eq!(cli.mcp_add, Some("s".to_string()));
assert_eq!(cli.env, vec!["API_KEY={{API_KEY}}", "MODE=dev"]);
assert_eq!(cli.mcp_command, vec!["npx", "srv"]);
}
#[test]
fn parse_mcp_add_http_with_header() {
let cli = parse(&[
"--mcp-add",
"notion",
"--transport",
"http",
"--url",
"https://mcp.notion.com/mcp",
"--header",
"Authorization: Bearer {{NOTION_TOKEN}}",
]);
assert_eq!(cli.mcp_add, Some("notion".to_string()));
assert!(matches!(cli.transport, Some(McpTransportArg::Http)));
assert_eq!(cli.url, Some("https://mcp.notion.com/mcp".to_string()));
assert_eq!(cli.header, vec!["Authorization: Bearer {{NOTION_TOKEN}}"]);
assert!(cli.mcp_command.is_empty());
}
#[test]
fn parse_mcp_list_flag() {
let cli = parse(&["--mcp-list"]);
assert!(cli.mcp_list);
}
#[test]
fn parse_mcp_scope_workspace() {
let cli = parse(&["--mcp-list", "--scope", "workspace"]);
assert!(cli.mcp_list);
assert!(matches!(cli.scope, Some(McpScopeArg::Workspace)));
}
#[test]
fn parse_mcp_action_group_is_exclusive() {
assert!(Cli::try_parse_from(["coyote", "--mcp-list", "--mcp-get", "foo"]).is_err());
}
#[test]
fn parse_trailing_text_unchanged_without_dash_dash() {
let cli = parse(&["hello", "world"]);
assert_eq!(cli.text, vec!["hello", "world"]);
assert!(cli.mcp_command.is_empty());
}
}
+135 -5
View File
@@ -2,31 +2,161 @@ use anyhow::{Result, anyhow};
use chrono::Utc;
use indexmap::IndexMap;
use parking_lot::RwLock;
use std::collections::HashMap;
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()));
/// Tokens a provider rejected (401) despite being locally unexpired.
/// Maps client name → the exact rejected token so a concurrently-refreshed
/// different token is never distrusted by mistake.
static REJECTED_TOKENS: LazyLock<RwLock<HashMap<String, String>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
pub fn get_access_token(client_name: &str) -> Result<String> {
ACCESS_TOKENS
.read()
.get(client_name)
.map(|(token, _)| token.clone())
.map(|(token, _, _)| token.clone())
.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 {
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,
None => return false,
};
!token.is_empty() && Utc::now().timestamp() < *expires_at
!token.is_empty() && Utc::now().timestamp() < *expires_at && !is_rejected(client_name, token)
}
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 entry = access_tokens.entry(client_name.to_string()).or_default();
entry.0 = token;
entry.1 = expires_at;
entry.2 = account_id;
}
/// Compare-and-invalidate a provider-rejected token.
///
/// Only if the currently-cached token EQUALS `rejected` is the cache entry
/// removed and the rejection marker recorded; a concurrently-refreshed
/// different token is left untouched and no marker is set.
///
/// Returns true if a cache entry existed for this client at all (whether or
/// not it matched `rejected`) — i.e. the client is token-authed and a retry
/// after refresh is worthwhile. Returns false when there is no entry
/// (API-key clients).
pub fn distrust_access_token(client_name: &str, rejected: &str) -> bool {
let mut access_tokens = ACCESS_TOKENS.write();
let (token, _, _) = match access_tokens.get(client_name) {
Some(v) => v,
None => return false,
};
if token == rejected {
access_tokens.shift_remove(client_name);
REJECTED_TOKENS
.write()
.insert(client_name.to_string(), rejected.to_string());
}
true
}
pub fn is_rejected(client_name: &str, token: &str) -> bool {
REJECTED_TOKENS
.read()
.get(client_name)
.is_some_and(|rejected| rejected == token)
}
pub fn clear_rejected(client_name: &str) {
REJECTED_TOKENS.write().remove(client_name);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distrust_removes_matching_token_and_sets_marker() {
let client = "distrust-match-test";
set_access_token(client, "at-1".into(), Utc::now().timestamp() + 3600, None);
assert!(distrust_access_token(client, "at-1"));
assert!(get_access_token(client).is_err(), "cache entry not removed");
assert!(is_rejected(client, "at-1"), "marker not set");
}
#[test]
fn distrust_keeps_differing_token_and_skips_marker() {
let client = "distrust-differ-test";
set_access_token(client, "at-new".into(), Utc::now().timestamp() + 3600, None);
assert!(distrust_access_token(client, "at-old"));
assert_eq!(get_access_token(client).unwrap(), "at-new");
assert!(!is_rejected(client, "at-old"), "marker set for stale token");
}
#[test]
fn distrust_returns_false_without_cache_entry() {
let client = "distrust-missing-test";
assert!(!distrust_access_token(client, "at-1"));
assert!(!is_rejected(client, "at-1"));
}
#[test]
fn is_valid_access_token_false_for_rejected_token() {
let client = "rejected-valid-test";
set_access_token(client, "at-1".into(), Utc::now().timestamp() + 3600, None);
assert!(is_valid_access_token(client));
distrust_access_token(client, "at-1");
// A concurrent in-flight prepare re-caches the rejected file token
// between mark and refresh; it must still be treated as invalid.
set_access_token(client, "at-1".into(), Utc::now().timestamp() + 3600, None);
assert!(!is_valid_access_token(client));
}
#[test]
fn clear_rejected_clears_marker_and_clients_are_isolated() {
let client_a = "rejected-isolation-a";
let client_b = "rejected-isolation-b";
set_access_token(client_a, "at-1".into(), Utc::now().timestamp() + 3600, None);
distrust_access_token(client_a, "at-1");
assert!(is_rejected(client_a, "at-1"));
assert!(
!is_rejected(client_b, "at-1"),
"marker leaked across clients"
);
clear_rejected(client_b);
assert!(
is_rejected(client_a, "at-1"),
"wrong client's marker cleared"
);
clear_rejected(client_a);
assert!(!is_rejected(client_a, "at-1"));
}
}
+2 -2
View File
@@ -50,7 +50,7 @@ fn prepare_chat_completions(
let url = format!(
"{}/openai/deployments/{}/chat/completions?api-version=2024-12-01-preview",
&api_base,
api_base,
self_.model.real_name()
);
@@ -69,7 +69,7 @@ fn prepare_embeddings(self_: &AzureOpenAIClient, data: &EmbeddingsData) -> Resul
let url = format!(
"{}/openai/deployments/{}/embeddings?api-version=2024-10-21",
&api_base,
api_base,
self_.model.real_name()
);
+19 -3
View File
@@ -1,3 +1,5 @@
use std::mem;
use super::*;
use crate::utils::{base64_decode, encode_uri, hex_encode, hmac_sha256, sha256, strip_think_tag};
@@ -275,10 +277,11 @@ async fn chat_completions_streaming(
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
})?;
handler.tool_call(ToolCall::new(
function_name.clone(),
mem::take(&mut function_name),
arguments,
Some(function_id.clone()),
Some(mem::take(&mut function_id)),
))?;
function_arguments.clear();
}
}
_ => {}
@@ -325,6 +328,7 @@ fn build_chat_completions_body(data: ChatCompletionsData, model: &Model) -> Resu
mut messages,
temperature,
top_p,
reasoning_effort,
functions,
stream: _,
} = data;
@@ -396,6 +400,11 @@ fn build_chat_completions_body(data: ChatCompletionsData, model: &Model) -> Resu
}))
}
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!({
"toolUse": {
"toolUseId": tool_result.call.id,
@@ -457,6 +466,9 @@ fn build_chat_completions_body(data: ChatCompletionsData, model: &Model) -> Resu
if let Some(v) = top_p {
body["inferenceConfig"]["topP"] = v.into();
}
if let Some(v) = reasoning_effort {
body["additionalModelRequestFields"] = json!({ "output_config": { "effort": v } });
}
if let Some(functions) = functions {
let tools: Vec<_> = functions
.iter()
@@ -520,7 +532,11 @@ fn extract_chat_completions(data: &Value) -> Result<ChatCompletionsOutput> {
bail!("Invalid response data: {data}");
}
let output = ChatCompletionsOutput { text, tool_calls };
let output = ChatCompletionsOutput {
text,
tool_calls,
..Default::default()
};
Ok(output)
}
+224 -25
View File
@@ -1,3 +1,6 @@
use std::collections::HashSet;
use std::mem;
use super::access_token::get_access_token;
use super::claude_oauth::ClaudeOAuthProvider;
use super::oauth::{self, OAuthProvider};
@@ -168,12 +171,22 @@ pub async fn claude_chat_completions_streaming(
let mut function_arguments = String::new();
let mut function_id = String::new();
let mut reasoning_state = 0;
let mut thinking_text = String::new();
let mut thinking_signature = String::new();
let handle = |message: SseMessage| -> Result<bool> {
let data: Value = serde_json::from_str(&message.data)?;
debug!("stream-data: {data}");
if let Some(typ) = data["type"].as_str() {
match typ {
"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)) = (
data["content_block"]["type"].as_str(),
data["content_block"]["name"].as_str(),
@@ -202,11 +215,10 @@ pub async fn claude_chat_completions_streaming(
if let Some(text) = data["delta"]["text"].as_str() {
handler.text(text)?;
} else if let Some(text) = data["delta"]["thinking"].as_str() {
if reasoning_state == 0 {
handler.text("<think>\n")?;
reasoning_state = 1;
}
handler.text(text)?;
thinking_text.push_str(text);
} else if let Some(signature) = data["delta"]["signature"].as_str() {
thinking_signature.push_str(signature);
} else if let (true, Some(partial_json)) = (
!function_name.is_empty(),
data["delta"]["partial_json"].as_str(),
@@ -216,8 +228,11 @@ pub async fn claude_chat_completions_streaming(
}
"content_block_stop" => {
if reasoning_state == 1 {
handler.text("\n</think>\n\n")?;
reasoning_state = 0;
handler.thinking_block(ThinkingBlock::Thinking {
thinking: mem::take(&mut thinking_text),
signature: mem::take(&mut thinking_signature),
});
}
if !function_name.is_empty() {
let arguments: Value = if function_arguments.is_empty() {
@@ -228,10 +243,11 @@ pub async fn claude_chat_completions_streaming(
})?
};
handler.tool_call(ToolCall::new(
function_name.clone(),
mem::take(&mut function_name),
arguments,
Some(function_id.clone()),
Some(mem::take(&mut function_id)),
))?;
function_arguments.clear();
}
}
_ => {}
@@ -251,6 +267,7 @@ pub fn claude_build_chat_completions_body(
mut messages,
temperature,
top_p,
reasoning_effort,
functions,
stream,
} = data;
@@ -308,17 +325,32 @@ pub fn claude_build_chat_completions_body(
})]
}
MessageContent::ToolCalls(MessageContentToolCalls {
tool_results, text, ..
tool_results,
text,
sequence,
}) => {
if !sequence {
let mut assistant_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!({
"type": "text",
"text": text,
"text": round_text,
}))
}
for tool_result in tool_results {
}
assistant_parts.push(json!({
"type": "tool_use",
"id": tool_result.call.id,
@@ -332,15 +364,75 @@ pub fn claude_build_chat_completions_body(
}));
}
vec![
json!({
"role": "assistant",
"content": assistant_parts,
}),
json!({
"role": "user",
"content": user_parts,
}),
json!({ "role": "assistant", "content": assistant_parts }),
json!({ "role": "user", "content": user_parts }),
]
} else {
// One pair per round: Claude can reuse tool_use IDs across API calls.
// A round boundary is detected by the presence of round text, but
// rounds where the model emitted only tool calls (no narration)
// carry no text marker. As a backstop, also split whenever a
// tool_use ID would repeat within the current assistant message —
// the API rejects duplicate tool_use IDs in a single message.
let mut messages = vec![];
let mut assistant_parts: Vec<serde_json::Value> = vec![];
let mut user_parts: Vec<serde_json::Value> = vec![];
let mut chunk_ids: HashSet<&str> = HashSet::new();
for (index, tool_result) in tool_results.iter().enumerate() {
let id_collision = tool_result
.call
.id
.as_deref()
.is_some_and(|id| chunk_ids.contains(id));
if index > 0 && (tool_result.text.is_some() || id_collision) {
messages.push(
json!({ "role": "assistant", "content": assistant_parts }),
);
messages.push(json!({ "role": "user", "content": user_parts }));
assistant_parts = vec![];
user_parts = vec![];
chunk_ids.clear();
}
if let Some(id) = tool_result.call.id.as_deref() {
chunk_ids.insert(id);
}
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!({
"type": "text",
"text": round_text,
}))
}
}
assistant_parts.push(json!({
"type": "tool_use",
"id": tool_result.call.id,
"name": tool_result.call.name,
"input": tool_result.call.arguments,
}));
user_parts.push(json!({
"type": "tool_result",
"tool_use_id": tool_result.call.id,
"content": tool_result.output.to_string(),
}));
}
if !assistant_parts.is_empty() {
messages
.push(json!({ "role": "assistant", "content": assistant_parts }));
messages.push(json!({ "role": "user", "content": user_parts }));
}
messages
}
}
}
})
@@ -369,6 +461,9 @@ pub fn claude_build_chat_completions_body(
if let Some(v) = top_p {
body["top_p"] = v.into();
}
if let Some(v) = reasoning_effort {
body["output_config"] = json!({ "effort": v });
}
if stream {
body["stream"] = true.into();
}
@@ -397,14 +492,24 @@ pub fn claude_build_chat_completions_body(
pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOutput> {
let mut text = String::new();
let mut reasoning = None;
let mut tool_calls = vec![];
let mut thinking = vec![];
if let Some(list) = data["content"].as_array() {
for item in list {
match item["type"].as_str() {
Some("thinking") => {
if let Some(v) = item["thinking"].as_str() {
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") => {
@@ -432,10 +537,6 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
}
}
}
if let Some(reasoning) = reasoning {
text = format!("<think>\n{reasoning}\n</think>\n\n{text}")
}
if text.is_empty() && tool_calls.is_empty() {
bail!("Invalid response data: {data}");
}
@@ -443,6 +544,104 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
let output = ChatCompletionsOutput {
text: text.to_string(),
tool_calls,
thinking,
};
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::function::{ToolCall, ToolResult};
fn tool_result(id: &str, text: Option<&str>) -> ToolResult {
ToolResult {
call: ToolCall::new("fs_read".into(), json!({"path": "x"}), Some(id.into())),
output: json!("ok"),
text: text.map(|t| t.to_string()),
thinking: vec![],
}
}
fn build_body(tool_results: Vec<ToolResult>) -> Value {
let data = ChatCompletionsData {
messages: vec![
Message::new(MessageRole::User, MessageContent::Text("hello".to_string())),
Message::new(
MessageRole::Assistant,
MessageContent::ToolCalls(MessageContentToolCalls {
tool_results,
text: String::new(),
sequence: true,
}),
),
],
temperature: None,
top_p: None,
reasoning_effort: None,
functions: None,
stream: false,
};
claude_build_chat_completions_body(data, &Model::new("claude", "claude-test")).unwrap()
}
fn assert_unique_tool_use_ids_per_message(body: &Value) {
for message in body["messages"].as_array().unwrap() {
let Some(content) = message["content"].as_array() else {
continue;
};
let mut seen = HashSet::new();
for block in content {
if block["type"] == "tool_use" {
let id = block["id"].as_str().unwrap();
assert!(
seen.insert(id.to_string()),
"duplicate tool_use id `{id}` within a single assistant message: {message}"
);
}
}
}
}
#[test]
fn sequence_splits_on_round_text() {
let body = build_body(vec![
tool_result("toolu_A", None),
tool_result("toolu_B", None),
tool_result("toolu_C", Some("running another tool")),
]);
let messages = body["messages"].as_array().unwrap();
assert_eq!(messages.len(), 5, "body: {body}");
assert_unique_tool_use_ids_per_message(&body);
}
#[test]
fn sequence_splits_on_reused_id_in_textless_round() {
let body = build_body(vec![
tool_result("toolu_A", None),
tool_result("toolu_B", None),
tool_result("toolu_A", None),
]);
let messages = body["messages"].as_array().unwrap();
assert_eq!(messages.len(), 5, "body: {body}");
assert_unique_tool_use_ids_per_message(&body);
}
#[test]
fn sequence_keeps_textless_rounds_merged_when_ids_are_unique() {
let body = build_body(vec![
tool_result("toolu_A", None),
tool_result("toolu_B", None),
tool_result("toolu_C", None),
]);
let messages = body["messages"].as_array().unwrap();
assert_eq!(messages.len(), 3, "body: {body}");
assert_unique_tool_use_ids_per_message(&body);
}
}
+2 -2
View File
@@ -25,8 +25,8 @@ impl OAuthProvider for ClaudeOAuthProvider {
"https://console.anthropic.com/oauth/code/callback"
}
fn scopes(&self) -> &str {
"org:create_api_key user:profile user:inference"
fn scopes(&self) -> String {
"org:create_api_key user:profile user:inference".to_string()
}
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() {
bail!("Invalid response data: {data}");
}
let output = ChatCompletionsOutput { text, tool_calls };
let output = ChatCompletionsOutput { text, tool_calls, ..Default::default() };
Ok(output)
}
+345 -21
View File
@@ -1,5 +1,6 @@
use super::*;
use super::access_token::{distrust_access_token, get_access_token};
use crate::config::{RenderMode, paths};
use crate::{
config::{AppConfig, Input, RequestContext},
@@ -56,12 +57,16 @@ pub trait Client: Sync + Send {
let mut builder = ReqwestClient::builder();
let extra = self.extra_config();
let timeout = extra.and_then(|v| v.connect_timeout).unwrap_or(10);
let read_timeout = extra.and_then(|v| v.read_timeout).unwrap_or(300);
if let Some(proxy) = extra.and_then(|v| v.proxy.as_deref()) {
builder = set_proxy(builder, proxy)?;
}
if let Some(user_agent) = self.app_config().user_agent.as_ref() {
builder = builder.user_agent(user_agent);
}
if read_timeout > 0 {
builder = builder.read_timeout(Duration::from_secs(read_timeout));
}
let client = builder
.connect_timeout(Duration::from_secs(timeout))
.build()
@@ -69,6 +74,11 @@ pub trait Client: Sync + Send {
Ok(client)
}
/// On a 401 the cached access token is distrusted and the call retried
/// exactly once; the retry re-runs the per-client prepare step, which
/// sees the rejection marker, force-refreshes the token, and rebuilds
/// the whole request. A second 401 propagates the original error; any
/// other retry failure propagates as-is.
async fn chat_completions(&self, input: Input) -> Result<ChatCompletionsOutput> {
if self.app_config().dry_run {
let content = input.echo_messages();
@@ -76,11 +86,30 @@ pub trait Client: Sync + Send {
}
let client = self.build_client()?;
let data = input.prepare_completion_data(self.model(), false)?;
self.chat_completions_inner(&client, data)
.await
.with_context(|| "Failed to call chat-completions api")
let err = match self.chat_completions_inner(&client, data).await {
Ok(output) => return Ok(output),
Err(err) => err,
};
let ret = if should_retry_auth(&err, self.name()) {
debug!(
"provider '{}' rejected access token (401); refreshing and retrying once",
self.name()
);
let data = input.prepare_completion_data(self.model(), false)?;
match self.chat_completions_inner(&client, data).await {
Err(retry_err) if is_auth_error(&retry_err) => Err(err),
ret => ret,
}
} else {
Err(err)
};
ret.with_context(|| "Failed to call chat-completions api")
}
/// Same retry-once-on-401 semantics as [`Self::chat_completions`], but
/// only while the handler has received nothing yet: retrying after
/// partial output has streamed would render it to the user twice. The
/// retry lives inside the same `select!` arm so abort stays responsive.
async fn chat_completions_streaming(
&self,
input: &Input,
@@ -97,7 +126,22 @@ pub trait Client: Sync + Send {
}
let client = self.build_client()?;
let data = input.prepare_completion_data(self.model(), true)?;
self.chat_completions_streaming_inner(&client, handler, data).await
let err = match self.chat_completions_streaming_inner(&client, handler, data).await {
Ok(()) => return Ok(()),
Err(err) => err,
};
if handler.has_received_content() || !should_retry_auth(&err, self.name()) {
return Err(err);
}
debug!(
"provider '{}' rejected access token (401); refreshing and retrying once",
self.name()
);
let data = input.prepare_completion_data(self.model(), true)?;
match self.chat_completions_streaming_inner(&client, handler, data).await {
Err(retry_err) if is_auth_error(&retry_err) => Err(err),
ret => ret,
}
} => {
handler.done();
ret.with_context(|| "Failed to call chat-completions api")
@@ -109,11 +153,27 @@ pub trait Client: Sync + Send {
}
}
/// Same retry-once-on-401 semantics as [`Self::chat_completions`]
/// (gemini OAuth embeddings route here).
async fn embeddings(&self, data: &EmbeddingsData) -> Result<Vec<Vec<f32>>> {
let client = self.build_client()?;
self.embeddings_inner(&client, data)
.await
.context("Failed to call embeddings api")
let err = match self.embeddings_inner(&client, data).await {
Ok(output) => return Ok(output),
Err(err) => err,
};
let ret = if should_retry_auth(&err, self.name()) {
debug!(
"provider '{}' rejected access token (401); refreshing and retrying once",
self.name()
);
match self.embeddings_inner(&client, data).await {
Err(retry_err) if is_auth_error(&retry_err) => Err(err),
ret => ret,
}
} else {
Err(err)
};
ret.context("Failed to call embeddings api")
}
async fn rerank(&self, data: &RerankData) -> Result<RerankOutput> {
@@ -205,6 +265,7 @@ impl Default for ClientConfig {
pub struct ExtraConfig {
pub proxy: Option<String>,
pub connect_timeout: Option<u64>,
pub read_timeout: Option<u64>,
}
#[derive(Debug, Clone, Deserialize, Default)]
@@ -286,6 +347,7 @@ pub struct ChatCompletionsData {
pub messages: Vec<Message>,
pub temperature: Option<f64>,
pub top_p: Option<f64>,
pub reasoning_effort: Option<String>,
pub functions: Option<Vec<FunctionDeclaration>>,
pub stream: bool,
}
@@ -294,6 +356,7 @@ pub struct ChatCompletionsData {
pub struct ChatCompletionsOutput {
pub text: String,
pub tool_calls: Vec<ToolCall>,
pub thinking: Vec<ThinkingBlock>,
}
impl ChatCompletionsOutput {
@@ -401,10 +464,25 @@ pub async fn create_openai_compatible_client_config(
};
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)?;
if !api_key.is_empty() {
config["api_key"] = api_key.into();
}
}
let model = set_client_models_config(&mut config, &name).await?;
let clients = json!(vec![config]);
@@ -434,6 +512,7 @@ pub async fn call_chat_completions(
let ChatCompletionsOutput {
mut text,
tool_calls,
thinking,
..
} = ret;
if !text.is_empty() {
@@ -444,7 +523,10 @@ pub async fn call_chat_completions(
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
.iter()
.for_each(|res| ctx.tool_scope.tool_tracker.record_call(res.call.clone()));
@@ -472,26 +554,55 @@ pub async fn call_chat_completions_streaming(
render_stream(rx, client.app_config(), abort_signal.clone(), silent),
);
if handler.abort().aborted() {
let aborted_ctrlc = handler.abort().aborted_ctrlc();
let aborted_ctrld = handler.abort().aborted_ctrld();
if aborted_ctrld {
bail!("Aborted.");
}
render_ret?;
let (text, tool_calls) = handler.take();
let (text, tool_calls, thinking) = handler.take();
if aborted_ctrlc {
if !ctx.working_mode.is_repl() || ctx.session.is_none() {
bail!("Aborted.");
}
if text.is_empty() {
if !silent && *IS_STDOUT_TERMINAL {
println!();
eprintln!("{}", error_text("Response interrupted"));
}
return Ok(("".to_string(), vec![]));
}
if !silent && *IS_STDOUT_TERMINAL {
println!();
eprintln!("{}", error_text("Response interrupted"));
}
return Ok((text, vec![]));
}
match send_ret {
Ok(_) => {
if !text.is_empty() && !text.ends_with('\n') {
if !silent && !text.is_empty() && !text.ends_with('\n') {
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
.iter()
.for_each(|res| ctx.tool_scope.tool_tracker.record_call(res.call.clone()));
Ok((text, tool_results))
}
Err(err) => {
if !text.is_empty() {
if !silent && !text.is_empty() {
println!();
}
Err(err)
@@ -507,46 +618,90 @@ pub async fn noop_rerank(_builder: RequestBuilder, _model: &Model) -> Result<Rer
bail!("The client doesn't support rerank api")
}
#[derive(Debug)]
pub struct ApiStatusError {
pub status: u16,
pub message: String,
}
impl std::fmt::Display for ApiStatusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for ApiStatusError {}
/// True when the error chain bottoms out in an [`ApiStatusError`] with
/// status 401 EXACTLY. 403 (entitlement) and 429 (rate limit) are never
/// auth failures, and message text is never inspected.
fn is_auth_error(err: &anyhow::Error) -> bool {
err.downcast_ref::<ApiStatusError>()
.is_some_and(|api_err| api_err.status == 401)
}
/// Decides whether a 401 from `client_name` warrants a single retry after a
/// forced token refresh: the error must be a 401 [`ApiStatusError`], and the
/// client must have a cached access token to distrust (API-key clients have
/// none and never retry). Distrusting marks the exact rejected token so the
/// retry's prepare step force-refreshes it. There is deliberately no backoff:
/// the blast radius is bounded at one extra request per user-visible call.
///
/// Note: vertexai shares the ACCESS_TOKENS cache, so a 401 there also
/// triggers distrust+retry — deliberate.
fn should_retry_auth(err: &anyhow::Error, client_name: &str) -> bool {
if !is_auth_error(err) {
return false;
}
let Ok(token) = get_access_token(client_name) else {
return false;
};
distrust_access_token(client_name, &token)
}
pub fn catch_error(data: &Value, status: u16) -> Result<()> {
if (200..300).contains(&status) {
return Ok(());
}
debug!("Invalid response, status: {status}, data: {data}");
let api_error = |message: String| anyhow::Error::new(ApiStatusError { status, message });
if let Some(error) = data["error"].as_object() {
if let (Some(typ), Some(message)) = (
json_str_from_map(error, "type"),
json_str_from_map(error, "message"),
) {
bail!("{message} (type: {typ})");
return Err(api_error(format!("{message} (type: {typ})")));
} else if let (Some(typ), Some(message)) = (
json_str_from_map(error, "code"),
json_str_from_map(error, "message"),
) {
bail!("{message} (code: {typ})");
return Err(api_error(format!("{message} (code: {typ})")));
}
} else if let Some(error) = data["errors"][0].as_object() {
if let (Some(code), Some(message)) = (
error.get("code").and_then(|v| v.as_u64()),
json_str_from_map(error, "message"),
) {
bail!("{message} (status: {code})")
return Err(api_error(format!("{message} (status: {code})")));
}
} else if let Some(error) = data[0]["error"].as_object() {
if let (Some(status), Some(message)) = (
json_str_from_map(error, "status"),
json_str_from_map(error, "message"),
) {
bail!("{message} (status: {status})")
return Err(api_error(format!("{message} (status: {status})")));
}
} else if let (Some(detail), Some(status)) = (data["detail"].as_str(), data["status"].as_i64())
{
bail!("{detail} (status: {status})");
return Err(api_error(format!("{detail} (status: {status})")));
} else if let Some(error) = data["error"].as_str() {
bail!("{error}");
return Err(api_error(error.to_string()));
} else if let Some(message) = data["message"].as_str() {
bail!("{message}");
return Err(api_error(message.to_string()));
}
bail!("Invalid response data: {data} (status: {status})");
Err(api_error(format!(
"Invalid response data: {data} (status: {status})"
)))
}
pub fn json_str_from_map<'a>(
@@ -687,3 +842,172 @@ fn prompt_input_string(desc: &str, required: bool, help_message: Option<&str>) -
let text = text.prompt()?;
Ok(text)
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::access_token::{is_rejected, set_access_token};
fn catch_error_message(data: &Value, status: u16) -> String {
catch_error(data, status).unwrap_err().to_string()
}
#[test]
fn test_catch_error_display_json_with_type() {
let data = json!({"error": {"type": "invalid_request_error", "message": "Bad request"}});
assert_eq!(
catch_error_message(&data, 400),
"Bad request (type: invalid_request_error)"
);
}
#[test]
fn test_catch_error_display_json_with_code() {
let data = json!({"error": {"code": "rate_limited", "message": "Too many requests"}});
assert_eq!(
catch_error_message(&data, 429),
"Too many requests (code: rate_limited)"
);
}
#[test]
fn test_catch_error_display_errors_array() {
let data = json!({"errors": [{"code": 7000, "message": "No route"}]});
assert_eq!(catch_error_message(&data, 404), "No route (status: 7000)");
}
#[test]
fn test_catch_error_display_array_error_status() {
let data = json!([{"error": {"status": "PERMISSION_DENIED", "message": "Denied"}}]);
assert_eq!(
catch_error_message(&data, 403),
"Denied (status: PERMISSION_DENIED)"
);
}
#[test]
fn test_catch_error_display_detail_status() {
let data = json!({"detail": "Not found", "status": 404});
assert_eq!(catch_error_message(&data, 404), "Not found (status: 404)");
}
#[test]
fn test_catch_error_display_error_string() {
let data = json!({"error": "Something went wrong"});
assert_eq!(catch_error_message(&data, 500), "Something went wrong");
}
#[test]
fn test_catch_error_display_message_string() {
let data = json!({"message": "Unauthorized"});
assert_eq!(catch_error_message(&data, 401), "Unauthorized");
}
#[test]
fn test_catch_error_display_fallback() {
let data = json!({"unexpected": true});
assert_eq!(
catch_error_message(&data, 500),
format!("Invalid response data: {data} (status: 500)")
);
}
#[test]
fn test_catch_error_ok_on_success_status() {
let data = json!({"error": {"type": "x", "message": "y"}});
assert!(catch_error(&data, 200).is_ok());
assert!(catch_error(&data, 299).is_ok());
}
#[test]
fn test_catch_error_downcast_through_context_chain() {
let data = json!({"error": {"type": "authentication_error", "message": "Invalid key"}});
let err = catch_error(&data, 401)
.context("Failed to call chat-completions api")
.unwrap_err();
let api_err = err
.downcast_ref::<ApiStatusError>()
.expect("should downcast through context chain");
assert_eq!(api_err.status, 401);
assert_eq!(api_err.message, "Invalid key (type: authentication_error)");
}
#[test]
fn test_catch_error_preserves_status() {
let data = json!({"message": "Unauthorized"});
let err = catch_error(&data, 401).unwrap_err();
assert_eq!(err.downcast_ref::<ApiStatusError>().unwrap().status, 401);
let data = json!({"detail": "Rate limited", "status": 429});
let err = catch_error(&data, 429).unwrap_err();
assert_eq!(err.downcast_ref::<ApiStatusError>().unwrap().status, 429);
// The struct carries the outer HTTP status even when the body embeds another code
let data = json!({"errors": [{"code": 7000, "message": "No route"}]});
let err = catch_error(&data, 429).unwrap_err();
assert_eq!(err.downcast_ref::<ApiStatusError>().unwrap().status, 429);
}
/// Wrapped in `.context(...)` so every test below proves the downcast
/// works through an anyhow context chain, as in the trait methods.
fn api_status_error(status: u16) -> anyhow::Error {
anyhow::Error::new(ApiStatusError {
status,
message: format!("error (status: {status})"),
})
.context("Failed to call chat-completions api")
}
fn cache_token(client: &str, token: &str) {
set_access_token(
client,
token.into(),
chrono::Utc::now().timestamp() + 3600,
None,
);
}
#[test]
fn test_should_retry_auth_401_with_cached_token() {
let client = "should-retry-auth-401";
cache_token(client, "at-1");
assert!(should_retry_auth(&api_status_error(401), client));
assert!(is_rejected(client, "at-1"), "rejected marker not set");
}
#[test]
fn test_should_retry_auth_non_401_statuses() {
let client = "should-retry-auth-non-401";
cache_token(client, "at-1");
for status in [403, 429, 500] {
assert!(
!should_retry_auth(&api_status_error(status), client),
"retried on {status}"
);
}
assert_eq!(get_access_token(client).unwrap(), "at-1");
assert!(!is_rejected(client, "at-1"), "marker set without a 401");
}
#[test]
fn test_should_retry_auth_non_api_status_error() {
let client = "should-retry-auth-non-api";
cache_token(client, "at-1");
let err = anyhow::anyhow!("connection reset").context("Failed to call embeddings api");
assert!(!should_retry_auth(&err, client));
assert_eq!(get_access_token(client).unwrap(), "at-1");
assert!(!is_rejected(client, "at-1"));
}
#[test]
fn test_should_retry_auth_401_without_cached_token() {
let client = "should-retry-auth-no-token";
assert!(!should_retry_auth(&api_status_error(401), client));
assert!(!is_rejected(client, "at-1"));
}
}
+2 -2
View File
@@ -27,8 +27,8 @@ impl OAuthProvider for GeminiOAuthProvider {
""
}
fn scopes(&self) -> &str {
"https://www.googleapis.com/auth/generative-language.peruserquota https://www.googleapis.com/auth/generative-language.retriever https://www.googleapis.com/auth/userinfo.email"
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".to_string()
}
fn client_secret(&self) -> Option<&str> {
+27 -2
View File
@@ -118,6 +118,9 @@ impl MessageContent {
lines.push(text.clone())
}
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()];
if let Some((agent_name, functions)) = agent_info
&& 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) {
match self {
MessageContent::Text(text) => *text = replace_fn(text),
@@ -178,6 +188,17 @@ pub struct ImageUrl {
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)]
pub struct MessageContentToolCalls {
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.text.clear();
self.sequence = true;
}
}
+11
View File
@@ -4,6 +4,8 @@ mod common;
mod gemini_oauth;
mod message;
pub mod oauth;
mod openai_compatible_oauth;
mod openai_oauth;
#[macro_use]
mod macros;
mod model;
@@ -36,6 +38,15 @@ register_client!(
(bedrock, "bedrock", BedrockConfig, BedrockClient),
);
pub fn client_type_supports_oauth(type_str: &str) -> bool {
matches!(
type_str,
ClaudeClient::NAME | OpenAIClient::NAME | GeminiClient::NAME
) || ALL_PROVIDER_MODELS
.iter()
.any(|pm| pm.provider == type_str && pm.oauth.is_some())
}
pub const OPENAI_COMPATIBLE_PROVIDERS: [(&str, &str); 18] = [
("ai21", "https://api.ai21.com/studio/v1"),
(
+15
View File
@@ -6,6 +6,7 @@ use super::{
use crate::config::AppConfig;
use crate::utils::{estimate_token_length, strip_think_tag};
use super::oauth::OAuthConfig;
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -289,6 +290,14 @@ impl Model {
}
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)]
@@ -316,6 +325,10 @@ pub struct ModelData {
pub supports_vision: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
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")]
no_stream: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
@@ -345,6 +358,8 @@ impl ModelData {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderModels {
pub provider: String,
#[serde(default)]
pub oauth: Option<OAuthConfig>,
pub models: Vec<ModelData>,
}

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