20 Commits
Author SHA1 Message Date
owen b35c4fb7e1 Send reasoning effort 'none' when reasoning is off
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
When a reasoning-capable model has reasoning effort set to off, send
'none' rather than omitting the field or sending 'off'. This applies
to both the ChatGPT Codex Responses API and OpenAI-compatible chat
completions (both reasoning_effort and reasoning object formats).
Non-reasoning models continue to send no reasoning field at all.

Bumps version to 0.3.4.
2026-06-25 20:08:15 -05:00
owen d05bb87a23 Prepare v0.3.3 release
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 19:48:48 -05:00
owen 52eca6477e Bump version to 0.3.2
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 19:22:56 -05:00
IrrelevantandGitHub 8b87e11e53 Merge pull request #13 from owenqwenstarsky/feat/fast-mode
Implement fast mode preference
2026-06-25 19:20:05 -05:00
owen 62e1d53f60 Implement fast mode preference 2026-06-25 19:17:44 -05:00
owen 39e0c14eec Plan tool output context reliability 2026-06-25 19:04:49 -05:00
owen 909c28d587 Plan v0.3.2 fast mode
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 18:55:23 -05:00
owen a2d2549df4 Fix transcript bottom scroll 2026-06-25 18:54:24 -05:00
owen b37bc677bd Add ChatGPT Codex provider
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 18:21:03 -05:00
owen 6767bef88e Replace MkDocs pages build with plain markdown HTML 2026-06-25 14:45:02 -05:00
owen cd6b2ca034 Fix MkDocs config path 2026-06-25 14:11:22 -05:00
owen 4687f835cb Moving docs config 2026-06-25 14:00:53 -05:00
owen 1ab982167b Install MkDocs Material for Pages build 2026-06-25 13:57:10 -05:00
owen 1c1eeb18f7 Cleaning up the docs website 2026-06-25 13:55:12 -05:00
owen 93348269a8 Adding mkdocs 2026-06-25 13:38:33 -05:00
owen a59c9fbbae Add provider login management
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 12:45:29 -05:00
owen 2845529682 Bump version to 0.2.8
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 11:47:37 -05:00
owen bcbb9dfa1b Add conversation branching and restore 2026-06-25 11:46:24 -05:00
owen 7c84a54e6a Add self-update command
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 07:50:05 -05:00
owen 71f84c03ce Add Rust embedding API
CI / Build (push) Waiting to run
CI / Test (push) Waiting to run
2026-06-25 06:53:13 -05:00
52 changed files with 9187 additions and 153 deletions
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Build the docs Markdown files into a static GitHub Pages site.
This intentionally avoids themed site generators and template files. Each Markdown
file is converted to a minimal standalone HTML page, and relative .md links are
rewritten to the generated .html filenames.
"""
from __future__ import annotations
import html
import re
import shutil
from pathlib import Path, PurePosixPath
from urllib.parse import urlsplit, urlunsplit
import markdown
ROOT = Path(__file__).resolve().parents[2]
DOCS_DIR = ROOT / "docs"
SITE_DIR = ROOT / "site"
MARKDOWN_EXTENSIONS = ["fenced_code", "tables", "toc"]
HREF_RE = re.compile(r'href="([^"]+)"')
def output_path(source: Path) -> Path:
if source.name == "README.md":
return SITE_DIR / "index.html"
return SITE_DIR / f"{source.stem}.html"
def page_title(text: str, fallback: str) -> str:
for line in text.splitlines():
if line.startswith("# "):
return line[2:].strip()
return fallback
def rewrite_markdown_links(rendered: str) -> str:
def replace(match: re.Match[str]) -> str:
href = html.unescape(match.group(1))
parts = urlsplit(href)
if parts.scheme or parts.netloc or not parts.path.endswith(".md"):
return match.group(0)
url_path = PurePosixPath(parts.path)
if url_path.name == "README.md":
new_path = str(url_path.with_name("index.html"))
else:
new_path = parts.path[:-3] + ".html"
new_href = urlunsplit(("", "", new_path, parts.query, parts.fragment))
return f'href="{html.escape(new_href, quote=True)}"'
return HREF_RE.sub(replace, rendered)
def render_page(source: Path) -> str:
text = source.read_text(encoding="utf-8")
title = page_title(text, "Cassady docs")
body = markdown.markdown(
text,
extensions=MARKDOWN_EXTENSIONS,
output_format="html5",
)
body = rewrite_markdown_links(body)
return "\n".join(
[
"<!doctype html>",
'<html lang="en">',
"<head>",
' <meta charset="utf-8">',
' <meta name="viewport" content="width=device-width, initial-scale=1">',
f" <title>{html.escape(title)}</title>",
"</head>",
"<body>",
body,
"</body>",
"</html>",
"",
]
)
def copy_static_assets() -> None:
for item in DOCS_DIR.iterdir():
if item.suffix == ".md":
continue
destination = SITE_DIR / item.name
if item.is_dir():
shutil.copytree(item, destination)
elif item.is_file():
shutil.copy2(item, destination)
def main() -> None:
if SITE_DIR.exists():
shutil.rmtree(SITE_DIR)
SITE_DIR.mkdir(parents=True)
for source in sorted(DOCS_DIR.glob("*.md")):
output_path(source).write_text(render_page(source), encoding="utf-8")
copy_static_assets()
(SITE_DIR / ".nojekyll").write_text("", encoding="utf-8")
if __name__ == "__main__":
main()
+67
View File
@@ -0,0 +1,67 @@
name: Publish Markdown site
on:
push:
branches:
- main
paths:
- 'docs/**'
- '.github/scripts/build-pages.py'
- '.github/workflows/pages.yml'
pull_request:
paths:
- 'docs/**'
- '.github/scripts/build-pages.py'
- '.github/workflows/pages.yml'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: github-pages
cancel-in-progress: false
jobs:
build:
name: Build Markdown site
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install Markdown converter
run: python -m pip install Markdown
- name: Build site
run: python .github/scripts/build-pages.py
- name: Configure Pages
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
uses: actions/configure-pages@v5
- name: Upload Pages artifact
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
uses: actions/upload-pages-artifact@v3
with:
path: site
deploy:
name: Deploy to GitHub Pages
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy Pages artifact
id: deployment
uses: actions/deploy-pages@v4
+1
View File
@@ -1,2 +1,3 @@
/target/ /target/
/dist/ /dist/
/site/
Generated
+128 -2
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "aho-corasick" name = "aho-corasick"
version = "1.1.4" version = "1.1.4"
@@ -91,6 +97,15 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]] [[package]]
name = "assert-json-diff" name = "assert-json-diff"
version = "2.0.2" version = "2.0.2"
@@ -211,7 +226,7 @@ checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
[[package]] [[package]]
name = "cassady" name = "cassady"
version = "0.2.5" version = "0.3.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
@@ -219,6 +234,7 @@ dependencies = [
"clap", "clap",
"crossterm", "crossterm",
"dirs", "dirs",
"flate2",
"futures-util", "futures-util",
"ignore", "ignore",
"include_dir", "include_dir",
@@ -227,13 +243,17 @@ dependencies = [
"ratatui", "ratatui",
"regex", "regex",
"reqwest", "reqwest",
"semver",
"serde", "serde",
"serde_json", "serde_json",
"sha2",
"tar",
"tempfile", "tempfile",
"thiserror 1.0.69", "thiserror 1.0.69",
"tokio", "tokio",
"unicode-width 0.1.14", "unicode-width 0.1.14",
"wiremock", "wiremock",
"zip",
] ]
[[package]] [[package]]
@@ -365,6 +385,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "crossbeam-deque" name = "crossbeam-deque"
version = "0.8.6" version = "0.8.6"
@@ -501,6 +530,17 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]] [[package]]
name = "derive_more" name = "derive_more"
version = "2.1.1" version = "2.1.1"
@@ -638,6 +678,16 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.9" version = "0.1.9"
@@ -656,6 +706,16 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flate2"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@@ -1376,6 +1436,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]] [[package]]
name = "mio" name = "mio"
version = "1.2.1" version = "1.2.1"
@@ -2231,6 +2301,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "simd-adler32"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.3" version = "1.0.3"
@@ -2346,6 +2422,17 @@ dependencies = [
"syn 2.0.118", "syn 2.0.118",
] ]
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.27.0" version = "3.27.0"
@@ -2976,7 +3063,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [ dependencies = [
"windows-sys 0.48.0", "windows-sys 0.61.2",
] ]
[[package]] [[package]]
@@ -3301,6 +3388,16 @@ version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.3" version = "0.8.3"
@@ -3404,8 +3501,37 @@ dependencies = [
"syn 2.0.118", "syn 2.0.118",
] ]
[[package]]
name = "zip"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
dependencies = [
"arbitrary",
"crc32fast",
"crossbeam-utils",
"displaydoc",
"flate2",
"indexmap",
"memchr",
"thiserror 2.0.18",
"zopfli",
]
[[package]] [[package]]
name = "zmij" name = "zmij"
version = "1.0.21" version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
+6 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "cassady" name = "cassady"
version = "0.2.5" version = "0.3.4"
edition = "2021" edition = "2021"
description = "Cassady/Cass minimal terminal coding agent" description = "Cassady/Cass minimal terminal coding agent"
license = "MIT" license = "MIT"
@@ -33,11 +33,16 @@ ratatui = { version = "0.30", default-features = false, features = ["crossterm",
regex = "1" regex = "1"
pulldown-cmark = "0.12" pulldown-cmark = "0.12"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
semver = "1"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
sha2 = "0.10"
flate2 = "1"
tar = "0.4"
thiserror = "1" thiserror = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time", "process", "io-util"] } tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time", "process", "io-util"] }
unicode-width = "0.1" unicode-width = "0.1"
zip = { version = "2", default-features = false, features = ["deflate"] }
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
+42 -9
View File
@@ -1,16 +1,17 @@
# Cassady / Cass # Cassady / Cass
Cassady (`cass`) is a terminal coding agent written in Rust. It runs an interactive chat in your project, can inspect files, apply exact edits, run shell commands when the active safety mode allows them, and persist sessions for later resume. Cassady currently talks to OpenAI-compatible providers. Cassady (`cass`) is a terminal coding agent written in Rust. It runs an interactive chat in your project, can inspect files, apply exact edits, run shell commands when the active safety mode allows them, and persist sessions for later resume. Cassady talks to OpenAI-compatible providers and a built-in ChatGPT Codex provider preset.
The project installs two equivalent commands, `cass` and `cassady`; examples use `cass`. The project installs two equivalent commands, `cass` and `cassady`; examples use `cass`.
## Current scope and limitations ## Current scope and limitations
- Provider support is OpenAI-compatible chat/completions APIs only. - Provider support includes OpenAI-compatible chat/completions APIs plus the `ChatGPT Codex` preset for users already signed in to Codex.
- The primary interface is an interactive terminal UI. - The primary interface is an interactive terminal UI.
- v0.2.6 adds an experimental Rust embedding API for headless sessions; it is useful for early integrations but not yet a stable long-term library contract.
- Config and conversation state live under `~/.cass`. - Config and conversation state live under `~/.cass`.
- Windows binaries are built for releases, but deeper Windows terminal, path, shell, and filesystem polish is planned for a later release. - Windows binaries are built for releases, but deeper Windows terminal, path, shell, and filesystem polish is planned for a later release.
- Cassady is not an installer, updater, or package manager. - `cass update` can update release-archive installs from official GitHub releases; external package managers should still be updated through their own tools.
## Install from source ## Install from source
@@ -33,15 +34,17 @@ Start Cassady in a project directory:
cass cass
``` ```
If Cassady cannot resolve a usable provider, model, or API key, it offers to run setup before opening a chat. You can also run setup explicitly: If Cassady cannot resolve a usable provider, model, or API key, it offers to run setup before opening a chat. You can also run setup or provider login explicitly:
```sh ```sh
cass login
cass setup cass setup
cass check cass check
cass update --check
cass cass
``` ```
The setup wizard lets you choose one or more OpenAI-compatible providers, enter the API key environment-variable name, discover models from `GET /models` when the key is available, or enter a model id manually. The setup wizard lets you choose one or more providers. OpenAI-compatible providers use an API key environment variable and can discover models from `GET /models` when the key is available. `ChatGPT Codex` uses your existing local Codex login (`~/.codex/auth.json`) and the Codex responses endpoint instead of a Cassady API-key environment variable.
Set your provider key in the shell where you run Cassady. For example, on macOS/Linux: Set your provider key in the shell where you run Cassady. For example, on macOS/Linux:
@@ -64,17 +67,24 @@ cass [--model MODEL] [--cwd PATH]
cass --resume <chat-id> cass --resume <chat-id>
cass --resume cass --resume
cass check cass check
cass login
cass logout
cass setup cass setup
cass update
``` ```
`cass --resume` without an id lists saved chats for the current directory. When Cassady exits a chat, it prints a resume command for that session. `cass --resume` without an id lists saved chats for the current directory. `cass update` checks official GitHub releases and can update both `cass` and `cassady` in the current install directory. When Cassady exits a chat, it prints a resume command for that session.
Common in-chat commands: Common in-chat commands:
- `/branch` or `/restore`: open the branch/restore menu.
- `/login`: configure or update provider login settings.
- `/logout`: remove saved provider config and associated model entries.
- `/fast`, `/fast on`, `/fast off`, `/fast status`: prefer faster inference when the active provider/model supports it. ChatGPT Codex models, including `gpt-5.5`, are treated as fast-capable.
- `/model <model>`: switch to a model from `~/.cass/models.json`. - `/model <model>`: switch to a model from `~/.cass/models.json`.
- `/new`: create a new chat for the current directory. - `/new`: create a new chat for the current directory.
- `/resume <chat>`: resume a saved chat for the current directory. - `/resume <chat>`: resume a saved chat for the current directory.
- `/status`: show chat id, model, mode, cwd, record count, and current status. - `/status`: show chat id, model, fast-mode state, mode, cwd, record count, and current status.
Helpful keys: Helpful keys:
@@ -85,7 +95,7 @@ Helpful keys:
- `Tab`: cycle reasoning effort while idle. - `Tab`: cycle reasoning effort while idle.
- `Ctrl-O`: toggle compact/full tool output display. - `Ctrl-O`: toggle compact/full tool output display.
- `Ctrl-Shift-R` or `Ctrl-R`: toggle reasoning display. - `Ctrl-Shift-R` or `Ctrl-R`: toggle reasoning display.
- `Esc`: request turn cancellation while a turn is running. - `Esc`: request turn cancellation while a turn is running; while idle, press twice within 1.5 seconds to open branch/restore.
- `Ctrl-C` twice within 1.5 seconds: exit. - `Ctrl-C` twice within 1.5 seconds: exit.
## Safety model ## Safety model
@@ -98,6 +108,12 @@ Cassady exposes tools according to the active access mode:
Use `--readonly`, `--workspace-edit`, or `--full-access` to choose a mode at launch, or press `Shift-Tab` while idle. Use `--readonly`, `--workspace-edit`, or `--full-access` to choose a mode at launch, or press `Shift-Tab` while idle.
## Branch and restore
Press `Esc` twice while idle, or type `/branch`, to browse the current conversation's branch family. Selecting an earlier user message, assistant message, tool call, or tool result creates a new branch conversation instead of truncating the original chat. The menu also lets you switch back to related branches later.
Conversation-only branching is the safe default. If you choose file restore, Cassady restores only file changes it tracked from successful `write` and `edit` tools. Shell commands, manual edits, unsupported files, and hash conflicts are reported or skipped rather than overwritten blindly.
## Configuration and docs ## Configuration and docs
Cassady stores user-editable files in `~/.cass`: Cassady stores user-editable files in `~/.cass`:
@@ -108,16 +124,33 @@ Cassady stores user-editable files in `~/.cass`:
- `global.md`: optional global instructions added to new chat system prompts when they fit the active request; they cannot override access modes, tool denials, approvals, or workspace boundaries. - `global.md`: optional global instructions added to new chat system prompts when they fit the active request; they cannot override access modes, tool denials, approvals, or workspace boundaries.
- `docs/`: bundled documentation installed from the current binary. - `docs/`: bundled documentation installed from the current binary.
API key references should usually be written as environment variables such as `"$OPENAI_API_KEY"`. API key references should usually be written as environment variables such as `"$OPENAI_API_KEY"`. The `ChatGPT Codex` provider is different: it stores no key in `~/.cass` and reads the bearer token from local Codex auth at check/request time.
Detailed bundled docs live in this repository under [`docs/`](docs/README.md) and are installed to `~/.cass/docs` at runtime. Detailed bundled docs live in this repository under [`docs/`](docs/README.md) and are installed to `~/.cass/docs` at runtime.
## Experimental Rust embedding API
Rust applications can import Cassady and run headless sessions without launching the TUI:
```rust
use cassady::prelude::*;
let session = SessionBuilder::new()
.cwd(".")
.access_mode(AccessMode::ReadOnly)
.build()
.await?;
```
See [Experimental Rust embedding API](docs/embedding.md) for session creation, streamed events, approval handling, cancellation, and current limitations.
## More documentation ## More documentation
- [Commands](docs/commands.md) - [Commands](docs/commands.md)
- [Configuration](docs/configuration.md) - [Configuration](docs/configuration.md)
- [Providers and models](docs/providers.md) - [Providers and models](docs/providers.md)
- [Access modes and tool safety](docs/access-modes.md) - [Access modes and tool safety](docs/access-modes.md)
- [Experimental Rust embedding API](docs/embedding.md)
- [Workflows](docs/workflows.md) - [Workflows](docs/workflows.md)
- [Troubleshooting](docs/troubleshooting.md) - [Troubleshooting](docs/troubleshooting.md)
- [Platform notes](docs/platforms.md) - [Platform notes](docs/platforms.md)
+264
View File
@@ -1,5 +1,269 @@
# Cassady (Cass) Roadmap # Cassady (Cass) Roadmap
## v0.3.3 — Codex Fast-Mode Compatibility
This release focuses on keeping fast mode available for ChatGPT Codex users when local model metadata predates the fast-mode capability flag. Cassady should treat active `chatgpt-codex` provider models, including `gpt-5.5`, as fast-capable while leaving OpenAI-compatible and custom providers capability-gated by model metadata.
### Fast Mode Compatibility
- [x] **Treat ChatGPT Codex models as fast-capable at runtime.** Make `/fast` active for any active `chatgpt-codex` provider model even when legacy `models.json` metadata says `fast_mode.supported` is false.
- Keep non-Codex providers governed by their model metadata.
- Preserve the saved fast-mode preference behavior and status reporting.
- [x] **Document the Codex capability fallback.** Update README and bundled docs so users understand that ChatGPT Codex models, including `gpt-5.5`, can honor fast mode without refreshed metadata.
- Keep docs clear that provider-specific fast-mode request shaping remains Codex-only.
- [x] **Add regression coverage for legacy metadata.** Test that a ChatGPT Codex model with older `fast_mode.supported: false` metadata still reports fast mode as supported and active when preferred.
- Verify `cargo fmt` and `cargo test --locked --all-targets` pass before handoff.
## v0.3.4 — Tool Output Context Reliability
This release focuses on making large tool outputs easier for the assistant to recover from when model-context compaction or truncation hides important details. Cassady should guide the assistant toward smaller, targeted reads and searches, preserve enough provenance for follow-up inspection, and add regression coverage for broad-output workflows that previously stalled safe edits. See `plans/V0_3_4_TOOL_OUTPUT_CONTEXT_RELIABILITY_PLAN.md`.
### Model Context Recovery
- [ ] **Improve compacted tool-output guidance.** Replace generic head/tail compaction notices with actionable guidance that tells the assistant what was omitted and how to inspect it again safely.
- Include tool name, output size, retained excerpt shape, and suggested narrower follow-up reads or searches when available.
- Keep model-facing guidance concise enough that it does not worsen context pressure.
- [ ] **Preserve targeted reinspection metadata.** Track enough structured context for large reads and command output so the assistant can recover omitted details without repeating broad requests.
- For file reads, preserve path and line-range coverage even after compaction.
- For shell and search output, prefer guidance toward narrower commands or `grep`/`read` follow-ups rather than blindly rerunning the same broad command.
### Tool Behavior and Prompting
- [ ] **Bias tool use toward smaller inspections.** Update tool descriptions, prompt guidance, and result messages so broad reads become a fallback rather than the default.
- Encourage search-first workflows for large files and unknown locations.
- Mention result limits before or at truncation points so the assistant knows when context may be incomplete.
- [ ] **Make truncation and compaction visible across layers.** Align model-facing messages, stored conversation records, and UI summaries so users and the assistant can tell when output was incomplete.
- Do not let UI-only collapsed output change what is stored or sent to the model.
- Keep existing conversation files readable and resumable.
### Validation
- [ ] **Add regression coverage for broad-output recovery.** Test workflows where an early broad read or command output is compacted before the assistant needs exact context for an edit.
- Cover superseded reads, compacted non-newest tool outputs, provider-message validity, and suggested follow-up guidance.
- Verify `cargo fmt` and `cargo test --locked --all-targets` pass before handoff.
## v0.3.2 — Provider Fast Mode
This release focuses on adding a `/fast` command that lets users prefer faster inference when the active provider/model supports it. The first supported provider is `ChatGPT Codex`; other providers can add their own fast-mode request behavior later without changing the user-facing command. See `plans/V0_3_2_FAST_MODE_PLAN.md`.
### Fast Mode Command
- [ ] **Add a persisted `/fast` preference.** Let users toggle fast mode from an idle chat and keep that preference across sessions.
- Store the preference in `config.json` without disturbing provider/model configuration.
- Keep the preference separate from whether the current provider/model can honor it.
- [ ] **Show capability-aware fast-mode status.** Display fast mode as enabled only when the active provider/model supports it.
- If the user switches to an unsupported provider/model, hide the enabled state and report fast mode as unavailable when relevant.
- If the user switches back to a supported provider/model, apply the existing preference again.
### Provider Support
- [ ] **Implement ChatGPT Codex fast-mode requests.** Add the provider-specific request option for Codex when fast mode is active.
- Verify and test the exact Codex responses request shape during implementation.
- Do not send Codex-specific fast-mode fields to OpenAI-compatible providers.
- [ ] **Add extensible provider/model capability metadata.** Model fast-mode support as provider/model metadata so future providers can opt in case by case.
- Default unknown and custom providers to unsupported.
- Mark built-in ChatGPT Codex model metadata as supported when Cassady can send the fast-mode request.
### Documentation and Validation
- [ ] **Document fast mode behavior and limits.** Update README and bundled docs for `/fast`, `default_fast_mode`, model capability metadata, and Codex-only initial support.
- Explain the difference between a saved fast-mode preference and active fast-mode support.
- [ ] **Test fast-mode preference, switching, and provider requests.** Cover command parsing, persistence, status rendering, model/provider switching, and Codex request body behavior.
- Verify `cargo fmt` and `cargo test --locked --all-targets` pass before handoff.
## v0.3.1 — Transcript Scroll Stability
This release focuses on keeping the live transcript anchored correctly above the input and footer during long sessions with blank reasoning or tool-output lines.
### TUI Reliability
- [x] **Fix bottom-scroll row counting for whitespace-only lines.** Count indented blank transcript rows the same way Ratatui renders them so accumulated blank rows no longer hide recent transcript content above the footer.
- Add regression coverage for whitespace-only wrapped row counting.
## v0.3.0 — ChatGPT Codex Provider ✅ Completed
This release focuses on letting users who are already signed in to Codex with a ChatGPT subscription use that account from Cassady. `ChatGPT Codex` becomes a provider preset that calls the Codex responses endpoint and reads its bearer token from local Codex auth instead of an API-key environment variable. See `plans/V0_3_0_CHATGPT_CODEX_PROVIDER_PLAN.md`.
### Provider Setup
- [x] **Add a ChatGPT Codex provider preset.** Make `ChatGPT Codex` available from `cass login`, `/login`, and first-run setup as a distinct provider option.
- Use provider id `chatgpt-codex` and endpoint `https://chatgpt.com/backend-api/codex/responses`.
- Skip the normal API-key environment-variable prompt for this preset.
- Prefer the model configured in local Codex config when available, with manual model entry as a fallback.
- [x] **Read local Codex auth safely.** Resolve the bearer token from `$CODEX_HOME/auth.json` or `~/.codex/auth.json` at check/request time.
- Support the local Codex `tokens.access_token` shape without copying the token into `~/.cass`.
- Give clear recovery steps when the user has not run `codex login`, signed in to the Codex app, or has an expired/missing token.
### Provider Runtime
- [x] **Add a ChatGPT Codex responses client.** Route `chatgpt-codex` providers to the exact Codex responses endpoint instead of the OpenAI-compatible `/chat/completions` path.
- Translate Cassady messages, tools, tool calls, and tool outputs to the endpoint's expected responses format.
- Stream assistant text, safe reasoning summaries when available, and function-call deltas back into the existing agent loop.
- [x] **Keep OpenAI-compatible providers unchanged.** Refactor provider dispatch only as much as needed to support the new provider kind.
- Existing provider config, setup, model discovery, API-key env vars, `/model`, and `cass check` behavior should continue to work.
- Avoid leaking ChatGPT access tokens in errors, logs, transcripts, or config files.
### Documentation and Validation
- [x] **Document ChatGPT Codex prerequisites and caveats.** Update README and bundled docs for setup, config examples, `cass check`, troubleshooting, and the distinction between ChatGPT subscription-backed access and API-key providers.
- Make clear that Cassady uses an existing Codex login and does not implement its own browser login or token refresh flow in this release.
- Note that the ChatGPT backend endpoint may change outside Cassady's control.
- [x] **Test Codex auth and provider behavior.** Cover Codex auth fixtures, config validation, setup catalog behavior, provider dispatch, streaming response parsing, tool calls, and secret redaction.
- Verify `cargo fmt` and `cargo test --locked --all-targets` pass before handoff.
## v0.2.9 — Provider Login Management ✅ Completed
This release focuses on making provider configuration available from both the shell and an active Cassady chat. Users can add or update OpenAI-compatible provider/model settings with `cass login` or `/login`, and remove saved providers and their associated models with `cass logout` or `/logout`. See `plans/V0_2_9_PROVIDER_LOGIN_MANAGEMENT_PLAN.md`.
### Login Commands
- [x] **Add login commands for provider setup.** Make `cass login` and `/login` open the provider setup flow so users can configure providers without remembering that setup is the underlying implementation.
- Reuse the existing provider catalog, model discovery, model capability prompts, and safe JSON writes.
- Keep `/login` idle-only and reload active provider/model config after the menu closes.
- [x] **Keep existing setup behavior intact.** Preserve `cass setup` and first-run setup while making login language feel natural for account/provider management.
- Direct `cass login` should save configuration and exit rather than unexpectedly starting a chat.
- Existing setup validation and missing API key guidance should continue to apply.
### Logout Commands
- [x] **Add a safe provider removal menu.** Make `cass logout` and `/logout` let users choose saved providers to remove from `providers.json`.
- Remove associated `models.json` entries for selected providers.
- Confirm the removal before writing changes.
- [x] **Repair active defaults after removal.** Ensure `config.json` never points at a provider/model that was just removed.
- Select a valid remaining provider/model when possible.
- Clear active provider/model defaults when no providers remain so the next startup offers login/setup.
### Documentation and Validation
- [x] **Document provider login and logout workflows.** Update command, configuration, and workflow docs with the new shell and in-chat commands.
- Clarify that logout removes Cassady provider config, not environment variables or external provider accounts.
- [x] **Test provider management behavior.** Cover provider/model removal, active default repair, local command parsing, and autocomplete.
- Verify `cargo fmt` and `cargo test --locked --all-targets` pass before handoff.
## v0.2.8 — Conversation Branch and Restore ✅ Completed
This release focuses on making conversation recovery safe and explorable. Pressing `Esc` twice while idle opens a branch/restore menu where users can browse prior user messages, assistant messages, and tool calls, create a new branch from a selected checkpoint, and optionally restore Cassady-tracked file edits without destroying the original conversation. See `plans/V0_2_8_CONVERSATION_BRANCH_RESTORE_PLAN.md`.
### Branch Navigation
- [x] **Open a branch/restore menu with double Esc.** Add an idle `Esc`-twice shortcut that mirrors the discoverability of double `Ctrl-C` while preserving current busy-turn cancellation and approval-denial behavior.
- Keep draft input intact when the menu is opened or cancelled.
- Provide clear status text after the first `Esc` so users know a second press opens branch/restore.
- [x] **Browse checkpoints across the related branch family.** Show user messages, assistant messages, tool-call requests, and tool results from the current chat and related branches.
- Include enough preview text, tool names, paths, timestamps, and branch labels to choose the right point.
- Allow switching back to the original conversation or another existing branch from the same menu.
### Safe Conversation Branching
- [x] **Create branches instead of destructive reverts.** Selecting a checkpoint should write a new conversation JSONL with parent/checkpoint metadata, leaving the source conversation unchanged.
- Support repeated branching so users can return to the menu later and branch or switch again.
- Keep older conversations without branch metadata loadable.
- [x] **Handle tool-call checkpoints cleanly.** Branching at a specific tool call or tool result should preserve a valid provider message history.
- Repair partial multi-tool assistant turns with synthetic cancelled/omitted tool results where needed.
- Add tests for branching at user, assistant, and tool boundaries.
### File Edit Restoration
- [x] **Journal Cassady file edits with restorable snapshots.** Record successful `write` and `edit` tool mutations outside the model-visible transcript with before/after hashes and snapshots.
- Keep restore support limited to Cassady-tracked file tools; warn that shell commands and manual edits are not automatically reversible.
- Store enough data to restore both backward and forward between tracked checkpoints.
- [x] **Offer explicit conversation-only or conversation-plus-files restore actions.** Make conversation-only branching the safe default, and require confirmation before changing workspace files.
- Preview files to update or delete, detect hash conflicts, and refuse unsafe overwrites by default.
- Use atomic writes for restored files and preserve clear status/transcript messages for skipped or conflicted paths.
### Documentation and Validation
- [x] **Document branch/restore workflows and limitations.** Update README and bundled docs with the double-`Esc` shortcut, menu controls, branch semantics, and file-restore safety model.
- Include troubleshooting for restore conflicts and unsupported shell/manual filesystem changes.
- [x] **Test the branch and restore model.** Cover branch metadata, checkpoint extraction, tool-call repair, edit journaling, restore planning, and keybinding behavior where practical.
- Verify `cargo fmt` and `cargo test --locked --all-targets` pass before release.
## v0.2.7 — Self-Update Command
This release focuses on making Cassady easy to keep current after installation. The goal is to let users run one clean command, `cass update`, to check GitHub releases, choose the recommended prebuilt binary or a source-build fallback, verify what will be installed, and update both `cass` and `cassady` safely. See `plans/V0_2_7_SELF_UPDATE_COMMAND_PLAN.md`.
### Update Command Experience
- [x] **Add a polished `cass update` command.** Check the official Cassady GitHub releases, compare the running version to the selected release, and guide the user through an interactive update flow.
- Keep update independent of provider/model setup so it works even when config is missing or invalid.
- Support script-friendly checks with flags such as `--check`, `--dry-run`, and `--yes`.
- [x] **Select the right update path.** Prefer a matching prebuilt release archive when available, with explicit `--prebuilt` and `--source` modes for users who want to choose.
- Support the same macOS, Linux, and Windows targets used by Cassady releases.
- Offer source builds for unsupported targets or users who prefer building locally.
### Safe Installation
- [x] **Verify and stage prebuilt artifacts before replacing binaries.** Download archives and SHA-256 files from the release, verify checksums, extract safely, and validate staged `cass`/`cassady` binaries.
- Reject checksum mismatches, unsafe archive paths, missing binaries, and unexpected versions.
- Show clear progress and failure messages without dumping raw implementation details.
- [x] **Replace installed binaries cleanly.** Update the current binary and same-directory companion binary when possible, using backups and rollback on failure.
- Do not auto-run `sudo` or administrator prompts.
- Handle Windows executable replacement with a staged helper or documented manual fallback if necessary.
### Source Build Fallback and Documentation
- [x] **Build from release source when requested.** Download the selected release source, validate its version, check for Rust tooling, run a locked release build, and install the resulting local binaries.
- Keep source mode tied to release tags rather than arbitrary branches.
- Do not attempt cross-compilation or Rust toolchain installation in this release.
- [x] **Document and test update behavior.** Update README and bundled docs for `cass update`, platform notes, troubleshooting, and package-manager caveats.
- Add tests for release parsing, target mapping, asset selection, checksum validation, archive extraction safety, install planning, and mocked update flows.
## v0.2.6 — Rust Embedding API ✅ Completed
This release focuses on adding the first intentional Rust library surface for embedding Cassady in other Rust projects. The goal is to provide the bones for programmatic, headless agent sessions: configure a workspace, start or resume an agent session, send turns, stream typed events, and handle approvals without launching the TUI. See `plans/V0_2_6_RUST_EMBEDDING_API_PLAN.md`.
### Experimental Public API
- [x] **Add a supported embedding module.** Provide a small `cassady::embedding` API with builder, session, turn, event, approval, and error types so callers do not need to stitch together internal modules directly.
- Mark the API experimental for v0.2.6 rather than promising long-term semver stability.
- Keep existing CLI/TUI behavior unchanged while steering library users toward the new module.
- [x] **Support host-configured agent sessions.** Let Rust callers create or resume headless sessions with explicit cwd, access mode, model/provider overrides, reasoning effort, and Cassady config root.
- Reuse existing config files, global instructions, bundled docs, security policy, and JSONL conversation storage.
- Avoid requiring callers to construct CLI-specific types.
### Headless Turn Execution
- [x] **Run agent turns programmatically.** Add a Tokio-native API for sending one user message, streaming assistant/tool/status events, and returning the updated session or conversation state.
- Prevent or clearly reject overlapping turns unless the type design makes them impossible.
- Preserve provider streaming, tool execution, prompt generation, and context behavior from the existing agent loop.
- [x] **Expose approval handling to host applications.** Allow embedded callers to approve or deny tool approval requests, especially shell commands in `workspace-edit` mode.
- Include request id, tool call id, tool name, arguments, and reason in approval events.
- Document cancellation/drop behavior for active turns.
### Documentation and Validation
- [x] **Add a minimal headless example.** Include a compilable Rust example that imports Cassady, starts a session, sends a prompt, and prints streamed assistant output.
- Note that a configured OpenAI-compatible provider and API key are still required.
- Show where to handle approval requests even if the first example defaults to `read-only`.
- [x] **Document the experimental Rust API.** Add bundled docs and README links for setup requirements, basic usage, event handling, approvals, limitations, and current non-goals.
- Make clear that multi-agent orchestration, custom providers, custom tools, daemons, and stable plugin APIs are deferred.
- [x] **Test embedding without a terminal.** Add integration tests that use temporary config/conversation roots and mock provider responses to verify session creation, turn streaming, resume, approval flow, and access-mode behavior.
- Ensure `cargo test --locked --all-targets` covers the new public API and examples.
## v0.2.4 — System Prompt Refinement ## v0.2.4 — System Prompt Refinement
This release focuses on making Cassady's system prompt clearer, more intuitive, and more useful for everyday coding work without letting it become bulky. The target is a well-structured prompt around 1,000 tokens that gives the model enough product context, safety expectations, and workflow guidance to behave consistently across read-only, workspace-edit, and full-access sessions. See `plans/V0_2_4_SYSTEM_PROMPT_REFINEMENT_PLAN.md`. This release focuses on making Cassady's system prompt clearer, more intuitive, and more useful for everyday coding work without letting it become bulky. The target is a well-structured prompt around 1,000 tokens that gives the model enough product context, safety expectations, and workflow guidance to behave consistently across read-only, workspace-edit, and full-access sessions. See `plans/V0_2_4_SYSTEM_PROMPT_REFINEMENT_PLAN.md`.
+4 -3
View File
@@ -6,11 +6,12 @@ Cassady tools may list, search, and read this directory. Mutating tools are bloc
## Contents ## Contents
- [Commands](commands.md): CLI forms, global flags, in-chat commands, and keys. - [Commands](commands.md): CLI forms, global flags, `cass update`, in-chat commands, and keys.
- [Configuration](configuration.md): `~/.cass` files, setup, precedence, schema examples, and validation. - [Configuration](configuration.md): `~/.cass` files, setup, precedence, schema examples, and validation.
- [Providers and models](providers.md): built-in OpenAI-compatible providers, custom endpoints, model discovery, and reasoning metadata. - [Providers and models](providers.md): built-in provider presets, custom OpenAI-compatible endpoints, ChatGPT Codex auth, model discovery, reasoning metadata, and fast-mode support.
- [Access modes and tool safety](access-modes.md): what tools can read, write, edit, and run in each mode. - [Access modes and tool safety](access-modes.md): what tools can read, write, edit, and run in each mode.
- [Experimental Rust embedding API](embedding.md): import Cassady from Rust, start headless sessions, stream events, and handle approvals.
- [Workflows](workflows.md): common ways to inspect code, apply edits, run checks, switch models, and resume chats. - [Workflows](workflows.md): common ways to inspect code, apply edits, run checks, switch models, and resume chats.
- [Troubleshooting](troubleshooting.md): symptoms, likely causes, fixes, and verification commands. - [Troubleshooting](troubleshooting.md): symptoms, likely causes, fixes, and verification commands.
- [Platform notes](platforms.md): macOS, Linux, and Windows environment/path notes. - [Platform notes](platforms.md): macOS, Linux, Windows, release artifact, and update notes.
- [Glossary](glossary.md): short definitions for Cassady terms. - [Glossary](glossary.md): short definitions for Cassady terms.
+56 -6
View File
@@ -8,11 +8,14 @@ Cassady installs two equivalent binaries: `cass` and `cassady`. This page uses `
cass [OPTIONS] cass [OPTIONS]
cassady [OPTIONS] cassady [OPTIONS]
cass check [OPTIONS] cass check [OPTIONS]
cass login [OPTIONS]
cass logout [OPTIONS]
cass setup [OPTIONS] cass setup [OPTIONS]
cass update [OPTIONS]
cass --resume [CHAT_ID] cass --resume [CHAT_ID]
``` ```
Run `cass --help`, `cass check --help`, or `cass setup --help` for the help generated by the current binary. Run `cass --help`, `cass check --help`, `cass login --help`, `cass logout --help`, `cass setup --help`, or `cass update --help` for the help generated by the current binary.
## Startup behavior ## Startup behavior
@@ -32,7 +35,7 @@ Resume this chat with: cass --resume <id>
- `--resume [CHAT_ID]`: resume a chat, or list chats for the current cwd when no id is provided. - `--resume [CHAT_ID]`: resume a chat, or list chats for the current cwd when no id is provided.
- `--model MODEL`: use `MODEL` for this session. - `--model MODEL`: use `MODEL` for this session.
- `--base-url URL`: override the active provider's OpenAI-compatible base URL for this session. - `--base-url URL`: override the active provider's base URL or endpoint for this session.
- `--api-key-env ENV`: read the API key from environment variable `ENV` for this session. - `--api-key-env ENV`: read the API key from environment variable `ENV` for this session.
- `--cwd PATH`: use `PATH` as the launch cwd and workspace root. - `--cwd PATH`: use `PATH` as the launch cwd and workspace root.
- `--readonly`: force read-only mode. - `--readonly`: force read-only mode.
@@ -53,22 +56,64 @@ Validates Cassady configuration under `~/.cass`:
- duplicate provider/model ids. - duplicate provider/model ids.
- model/provider references. - model/provider references.
- active provider and model resolution. - active provider and model resolution.
- active API key availability. - active authentication availability.
Missing API keys for inactive providers are warnings. A missing active API key is an error and `cass check` exits with a non-zero status. Missing API keys for inactive OpenAI-compatible providers are warnings. A missing active API key is an error. For `ChatGPT Codex`, missing or expired local Codex auth is an error when it is active. `cass check` exits with a non-zero status when errors are present.
### `cass login`
Runs the provider login/configuration wizard. This is the same provider setup flow used by `cass setup`, framed for adding or updating saved provider access. It can configure multiple providers, discover or manually enter models, update active defaults, and validate the saved files.
`cass login` edits Cassady files under `~/.cass`; it does not create provider accounts. For `ChatGPT Codex`, sign in with `codex login` or the Codex app first; Cassady then uses local Codex auth instead of storing an API key.
### `cass logout`
Opens an interactive menu for removing saved providers from Cassady config. Removing a provider also removes its associated `models.json` entries. If the active provider is removed, Cassady chooses a remaining provider/model when possible. If no providers remain, active defaults are cleared and the next chat startup will offer setup/login again.
`cass logout` does not delete environment variables, API keys stored elsewhere, or external provider accounts.
### `cass setup` ### `cass setup`
Runs the interactive setup wizard in a terminal. It configures OpenAI-compatible providers, API key environment-variable references, and first models. It updates `config.json`, `providers.json`, and `models.json` while preserving unrelated entries where possible. Runs the interactive setup wizard in a terminal. It configures providers, authentication sources, and first models. OpenAI-compatible providers use API key environment-variable references; `ChatGPT Codex` uses local Codex auth. It updates `config.json`, `providers.json`, and `models.json` while preserving unrelated entries where possible.
### `cass update`
Checks official GitHub releases for Cassady, including Cassady prereleases, and updates the current install directory. The updater runs before provider/model config is loaded, so it can be used even if `~/.cass` is missing or invalid.
By default, Cassady selects the matching prebuilt archive for the current platform, downloads the archive and `.sha256` file, verifies SHA-256, stages both `cass` and `cassady`, and replaces same-directory binaries with rollback backups. If no prebuilt archive is available, it can build from the selected release source when you choose source mode.
Useful options:
- `--check`: check the selected release without installing.
- `--dry-run`: show the selected release, mode, asset, and install plan without downloading or installing.
- `--yes` / `-y`: accept default prompts for non-interactive use.
- `--prebuilt`: require a matching prebuilt archive.
- `--source`: build from release source even when a prebuilt archive exists.
- `--to TAG`: use a specific release tag such as `v0.2.7`.
Examples:
```sh
cass update --check
cass update --dry-run
cass update
cass update --source
```
The updater does not invoke `sudo` or administrator prompts. If the install directory is not writable, rerun the update from an install location you own or update through the same package manager or manual process you originally used.
## In-chat commands ## In-chat commands
Type `/` to open command autocomplete. Type `/` to open command autocomplete.
- `/branch` or `/restore`: open the branch/restore menu for the current conversation family.
- `/fast`, `/fast on`, `/fast off`, `/fast status`: toggle or inspect a persisted fast-mode preference. Fast mode is active only when the current provider/model supports it; ChatGPT Codex models, including `gpt-5.5`, are treated as fast-capable.
- `/login`: configure or update provider login settings, then reload active provider/model config.
- `/logout`: remove saved providers and their associated models, then reload active provider/model config when any remain.
- `/model <model>`: switch the model for future turns. Autocomplete lists models from `~/.cass/models.json`. - `/model <model>`: switch the model for future turns. Autocomplete lists models from `~/.cass/models.json`.
- `/new`: create a new chat for the current directory. - `/new`: create a new chat for the current directory.
- `/resume <chat>`: resume a saved chat from the current directory. Autocomplete lists matching chats. - `/resume <chat>`: resume a saved chat from the current directory. Autocomplete lists matching chats.
- `/status`: show chat id, state, model, access mode, cwd, record count, and current status. - `/status`: show chat id, state, model, fast-mode state, access mode, cwd, record count, and current status.
Local commands can be used only when the agent is idle. Local commands can be used only when the agent is idle.
@@ -86,8 +131,13 @@ Local commands can be used only when the agent is idle.
- `y`: approve a pending tool approval prompt. - `y`: approve a pending tool approval prompt.
- `n` or `Esc`: deny a pending tool approval prompt. - `n` or `Esc`: deny a pending tool approval prompt.
- `Esc`: request cancellation while a turn is running. - `Esc`: request cancellation while a turn is running.
- `Esc` twice while idle: open the branch/restore menu without discarding draft input.
- `Ctrl-C`: request cancellation while busy; press twice within 1.5 seconds to exit. - `Ctrl-C`: request cancellation while busy; press twice within 1.5 seconds to exit.
## Branch/restore notes
The branch/restore menu lists related conversations plus checkpoints for user messages, assistant messages, tool-call requests, and tool results. Selecting a checkpoint creates a new branch JSONL conversation and leaves the source conversation unchanged. Conversation-only branching leaves files untouched; branch-plus-file restore applies Cassady's tracked `write`/`edit` snapshots and skips unsafe hash conflicts.
## Output notes ## Output notes
Tool calls are shown compactly by default. Press `Ctrl-O` to expand full tool output. Provider-streamed reasoning is hidden by default unless `show_reasoning` is enabled in config or toggled at runtime. Tool calls are shown compactly by default. Press `Ctrl-O` to expand full tool output. Provider-streamed reasoning is hidden by default unless `show_reasoning` is enabled in config or toggled at runtime.
+42 -9
View File
@@ -19,13 +19,17 @@ Run:
cass setup cass setup
``` ```
Cassady also offers setup automatically when `cass` cannot resolve a usable active provider, model, or API key before starting a chat. Cassady also offers setup automatically when `cass` cannot resolve a usable active provider, model, or authentication source before starting a chat.
For everyday provider management, `cass login` opens the same provider configuration flow with login-oriented wording. Inside an idle chat, `/login` temporarily opens that flow and reloads the active provider/model after it closes.
To remove saved provider configuration, run `cass logout` or type `/logout` while idle. Logout removes selected providers from `providers.json` and removes their associated entries from `models.json`. It does not remove environment variables, local shell profile exports, or external provider accounts.
The wizard uses keyboard prompts: `↑`/`↓` moves through choices, `Space` selects providers in the multi-select screen, and `Enter` submits. Text fields use the same prompt style instead of falling back to plain line input. The wizard uses keyboard prompts: `↑`/`↓` moves through choices, `Space` selects providers in the multi-select screen, and `Enter` submits. Text fields use the same prompt style instead of falling back to plain line input.
The wizard supports configuring multiple OpenAI-compatible providers at once. If more than one provider is configured, setup asks which one should be active first. If the selected API key environment variable is set, Cassady tries to fetch models from `GET {base_url}/models` and lets you choose one. If discovery fails, it offers a retry before falling back to manual model entry. If the API key is not set, setup asks for a model id manually. The wizard supports configuring multiple providers at once. If more than one provider is configured, setup asks which one should be active first. For OpenAI-compatible providers, if the selected API key environment variable is set, Cassady tries to fetch models from `GET {base_url}/models` and lets you choose one. If discovery fails, it offers a retry before falling back to manual model entry. If the API key is not set, setup asks for a model id manually. For `ChatGPT Codex`, setup skips API-key prompts and reads model defaults from local Codex config when available.
Setup stores API keys as environment-variable references such as `"$OPENAI_API_KEY"` by default. After setup, Cassady writes/updates `config.json`, `providers.json`, and `models.json`, validates them, and starts a chat only when the active API key is available in the current shell. Setup stores API keys as environment-variable references such as `"$OPENAI_API_KEY"` by default for OpenAI-compatible providers. `ChatGPT Codex` stores no API key in `~/.cass`; it reads local Codex auth at check/request time. After setup, Cassady writes/updates `config.json`, `providers.json`, and `models.json`, validates them, and starts a chat only when the active authentication source is available.
## `config.json` ## `config.json`
@@ -38,6 +42,7 @@ Example:
"default_provider": "openai", "default_provider": "openai",
"default_model": "gpt-4.1", "default_model": "gpt-4.1",
"default_reasoning_effort": "medium", "default_reasoning_effort": "medium",
"default_fast_mode": false,
"default_access_mode": "read-only", "default_access_mode": "read-only",
"context_message_limit": 80, "context_message_limit": 80,
"model_tool_result_limit": 24000, "model_tool_result_limit": 24000,
@@ -52,6 +57,7 @@ Fields:
- `default_provider`: optional provider id from `providers.json`. If omitted, Cassady infers the provider from `default_model` when possible. - `default_provider`: optional provider id from `providers.json`. If omitted, Cassady infers the provider from `default_model` when possible.
- `default_model`: optional model id to use by default. - `default_model`: optional model id to use by default.
- `default_reasoning_effort`: optional `off`, `low`, `medium`, or `high`, clamped to model metadata. - `default_reasoning_effort`: optional `off`, `low`, `medium`, or `high`, clamped to model metadata.
- `default_fast_mode`: optional boolean, defaults to `false`. When `true`, Cassady requests faster inference only for provider/model combinations that advertise fast-mode support.
- `default_access_mode`: `"read-only"`, `"workspace-edit"`, or `"full-access"`. - `default_access_mode`: `"read-only"`, `"workspace-edit"`, or `"full-access"`.
- `context_message_limit`: optional legacy upper bound for recent non-system messages. Cassady primarily budgets context from model metadata and trims along valid tool-call boundaries. - `context_message_limit`: optional legacy upper bound for recent non-system messages. Cassady primarily budgets context from model metadata and trims along valid tool-call boundaries.
- `model_tool_result_limit`: optional max bytes of tool output sent back to the model. - `model_tool_result_limit`: optional max bytes of tool output sent back to the model.
@@ -85,14 +91,33 @@ Fields:
- `id`: required unique provider id. - `id`: required unique provider id.
- `name`: optional display name. - `name`: optional display name.
- `kind`: required provider kind. Currently only `"openai-compatible"` is supported. - `kind`: required provider kind. Supported values are `"openai-compatible"` and `"chatgpt-codex"`.
- `base_url`: required OpenAI-compatible API base URL. - `base_url`: required API base URL or endpoint. `chatgpt-codex` uses `https://chatgpt.com/backend-api/codex/responses`.
- `api_key`: required string. Use either a literal key or an environment-variable reference like `"$OPENAI_API_KEY"`. - `api_key`: required for `openai-compatible` providers. Use either a literal key or an environment-variable reference like `"$OPENAI_API_KEY"`. Omit it for `chatgpt-codex`; that provider reads local Codex auth instead.
- `default_model`: optional model id used when no default model is configured. - `default_model`: optional model id used when no default model is configured.
- `models`: optional list of model ids associated with this provider. - `models`: optional list of model ids associated with this provider.
Only strings that start with `$` are resolved as environment variables. Cassady does not expand partial strings or `${NAME}` syntax. Only strings that start with `$` are resolved as environment variables. Cassady does not expand partial strings or `${NAME}` syntax.
`ChatGPT Codex` example:
```json
{
"providers": [
{
"id": "chatgpt-codex",
"name": "ChatGPT Codex",
"kind": "chatgpt-codex",
"base_url": "https://chatgpt.com/backend-api/codex/responses",
"default_model": "gpt-5.5",
"models": ["gpt-5.5"]
}
]
}
```
Run `codex login` or sign in with the Codex app before using this provider. Cassady reads `$CODEX_HOME/auth.json` or `~/.codex/auth.json` and does not store the Codex access token in `~/.cass`.
## `models.json` ## `models.json`
Example: Example:
@@ -113,6 +138,9 @@ Example:
"required": false, "required": false,
"default_effort": "medium", "default_effort": "medium",
"request_format": "reasoning_effort" "request_format": "reasoning_effort"
},
"fast_mode": {
"supported": false
} }
} }
] ]
@@ -133,9 +161,13 @@ Fields:
- `required`: optional boolean, defaults to `false`. - `required`: optional boolean, defaults to `false`.
- `default_effort`: optional `off`, `low`, `medium`, or `high`; defaults to `medium`. Cannot effectively be `off` when `required` is `true`. - `default_effort`: optional `off`, `low`, `medium`, or `high`; defaults to `medium`. Cannot effectively be `off` when `required` is `true`.
- `request_format`: optional `reasoning_effort` or `reasoning_object`; defaults to `reasoning_effort`. - `request_format`: optional `reasoning_effort` or `reasoning_object`; defaults to `reasoning_effort`.
- `fast_mode`: optional object. Defaults to unsupported.
- `supported`: optional boolean, defaults to `false`. Cassady treats active `chatgpt-codex` provider models as fast-capable even if older metadata says otherwise; custom and OpenAI-compatible model entries default to unsupported.
Reasoning effort is a runtime per-turn setting. Press `Tab` to cycle it while idle. Provider-streamed reasoning is persisted and sent back in future model context using the provider's reasoning field, such as `reasoning_content` or `reasoning`. Reasoning effort is a runtime per-turn setting. Press `Tab` to cycle it while idle. Provider-streamed reasoning is persisted and sent back in future model context using the provider's reasoning field, such as `reasoning_content` or `reasoning`.
Fast mode is a persisted preference, not a guarantee. Use `/fast` to toggle it while idle. `/status` shows `enabled` only when the preference is on and the current provider/model can honor it; otherwise it reports `off` or `preferred, unavailable ...`. Fast-mode request shaping is implemented only for `chatgpt-codex`.
## Precedence ## Precedence
- CLI access-mode flags override `default_access_mode` for the current session. - CLI access-mode flags override `default_access_mode` for the current session.
@@ -154,7 +186,7 @@ Run:
cass check cass check
``` ```
This validates JSON syntax, expected schema, duplicate provider/model ids, model/provider references, active provider/model resolution, and API key environment-variable availability. Missing API keys for inactive providers are warnings; a missing active provider API key is an error. This validates JSON syntax, expected schema, duplicate provider/model ids, model/provider references, active provider/model resolution, and authentication availability. Missing API keys for inactive OpenAI-compatible providers are warnings; a missing active provider API key is an error. For `ChatGPT Codex`, missing or expired local Codex auth is an active-provider error.
When setup is incomplete, `cass check` prints actionable next steps such as: When setup is incomplete, `cass check` prints actionable next steps such as:
@@ -168,7 +200,8 @@ cass
1. Edit one file at a time. 1. Edit one file at a time.
2. Keep provider ids and model provider references in sync. 2. Keep provider ids and model provider references in sync.
3. Prefer API key env references over literal keys. 3. Prefer API key env references over literal keys for OpenAI-compatible providers; do not paste Codex tokens into Cassady config.
4. Run `cass check` before starting a chat. 4. Prefer `cass login` and `cass logout` for routine provider changes.
5. Run `cass check` before starting a chat.
Invalid JSON, unknown fields, duplicate ids, and missing provider/model links are reported by `cass check` with the file that failed. Invalid JSON, unknown fields, duplicate ids, and missing provider/model links are reported by `cass check` with the file that failed.
+98
View File
@@ -0,0 +1,98 @@
# Experimental Rust embedding API
Cassady v0.2.6 includes an experimental Rust API for running headless agent sessions from another Rust program. The API is intended for early integrations and may change before Cassady declares a stable library contract.
The embedding API uses the same provider configuration, global instructions, prompts, access modes, tools, and JSONL conversation storage as the `cass` terminal UI. By default it reads and writes under `~/.cass`, so run `cass setup` first or create compatible `config.json`, `providers.json`, and `models.json` files programmatically.
## Minimal example
```rust
use cassady::prelude::*;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let session = SessionBuilder::new()
.cwd(std::env::current_dir()?)
.access_mode(AccessMode::ReadOnly)
.build()
.await?;
let mut turn = session
.start_turn("Summarize this project in a few sentences.")
.await?;
while let Some(event) = turn.next_event().await? {
match event {
Event::AssistantChunk(text) => print!("{text}"),
Event::Finished => break,
_ => {}
}
}
let session = turn.finish().await?;
eprintln!("\nResume chat with: cass --resume {}", session.id());
Ok(())
}
```
Add Cassady from a git checkout or path dependency, and ensure your application runs on Tokio.
## Creating or resuming sessions
Use `SessionBuilder` to set host-controlled options:
```rust
let session = SessionBuilder::new()
.config_root("/tmp/my-cass-root")
.cwd("/path/to/workspace")
.access_mode(AccessMode::WorkspaceEdit)
.model("my-model")
.base_url("https://provider.example/v1")
.api_key_env("MY_PROVIDER_KEY")
.build()
.await?;
let resumed = SessionBuilder::new()
.cwd("/path/to/workspace")
.resume(session.id())
.await?;
```
`build()` is equivalent to `new_session()`. Resumed and new sessions use Cassady's normal `conversations/*.jsonl` files, so CLI and embedded sessions can interoperate.
## Events and approvals
`Session::start_turn` consumes the session and returns a `Turn`. This type design prevents overlapping turns for the same session. Call `turn.finish().await?` after receiving `Event::Finished` to recover the updated `Session`.
Important events include:
- `AssistantChunk` and `ReasoningChunk`
- `ToolCallStarted`, `ToolOutputChunk`, and `ToolResult`
- `ApprovalRequested` and `ApprovalResolved`
- `Status`
- `Finished`
When a tool needs approval, decide in host code:
```rust
while let Some(event) = turn.next_event().await? {
match event {
Event::ApprovalRequested(request) => {
eprintln!("approval needed for {}: {}", request.name, request.reason);
turn.deny(&request.request_id)?;
}
Event::Finished => break,
_ => {}
}
}
```
The approval policy is the same as the TUI: shell is unavailable in `read-only`, requires approval in `workspace-edit`, and runs directly in `full-access` unless destructive-operation confirmation is enabled.
## Cancellation
Dropping a `Turn` aborts the underlying task. Prefer `turn.cancel().await?` when you want Cassady to repair the conversation with cancellation records before returning the session.
## Current limitations
The v0.2.6 API is intentionally small and experimental. It does not include custom provider traits, custom tools, plugin loading, multi-agent orchestration, background daemons, task queues, or a synchronous/blocking wrapper.
+3 -1
View File
@@ -14,9 +14,11 @@
**Exact edit**: An `edit` tool replacement where each `old_text` must match exactly once in the original file before anything is written. **Exact edit**: An `edit` tool replacement where each `old_text` must match exactly once in the original file before anything is written.
**Fast mode**: A saved preference enabled with `/fast`. It is active only when the current provider/model advertises fast-mode support; otherwise Cassady keeps the preference but reports it as unavailable.
**Global instructions**: Optional text in `~/.cass/global.md` included in new chat system prompts. Cassady follows these instructions when they fit the active request, but they cannot override runtime safety constraints such as access modes, tool denials, approvals, or workspace boundaries. **Global instructions**: Optional text in `~/.cass/global.md` included in new chat system prompts. Cassady follows these instructions when they fit the active request, but they cannot override runtime safety constraints such as access modes, tool denials, approvals, or workspace boundaries.
**Model metadata**: The `models.json` entry describing a model id, owning provider, display name, context limits, tool/streaming support, and reasoning behavior. **Model metadata**: The `models.json` entry describing a model id, owning provider, display name, context limits, tool/streaming support, reasoning behavior, and fast-mode support.
**OpenAI-compatible provider**: A provider exposing an API compatible with the OpenAI-style chat/completions behavior Cassady uses. **OpenAI-compatible provider**: A provider exposing an API compatible with the OpenAI-style chat/completions behavior Cassady uses.
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

+15 -2
View File
@@ -52,9 +52,22 @@ That directory contains `config.json`, `providers.json`, `models.json`, `global.
## Non-interactive contexts ## Non-interactive contexts
- `cass check` is suitable for scripts and CI because it prints text and exits non-zero on errors. - `cass check` is suitable for scripts and CI because it prints text and exits non-zero on errors.
- `cass update --check` and `cass update --dry-run` are suitable for scripts that only need release status or an install plan.
- `cass update --yes` accepts default prompts for scripted updates, but still fails instead of escalating privileges when the install directory is not writable.
- `cass setup` requires an interactive terminal. - `cass setup` requires an interactive terminal.
- `cass` chat is an interactive terminal UI. - `cass` chat is an interactive terminal UI.
## Release artifacts ## Release artifacts and updates
When using release archives, each archive contains both `cass` and `cassady`. Put the extracted binaries somewhere on your `PATH` or run them by explicit path. Cassady itself does not install, update, or manage PATH entries. When using release archives, each archive contains both `cass` and `cassady`. Put the extracted binaries somewhere on your `PATH` or run them by explicit path.
`cass update` can update release-archive installs from official GitHub releases. It supports the same prebuilt targets as the release process:
- macOS Apple Silicon: `aarch64-apple-darwin`
- Linux x86_64: `x86_64-unknown-linux-gnu`
- Linux ARM64: `aarch64-unknown-linux-gnu`
- Windows x86_64: `x86_64-pc-windows-gnu`
On macOS and Linux, the updater replaces same-directory `cass` and `cassady` binaries with backups and rollback on failure. On Windows, replacing a running `.exe` is more constrained; if automatic replacement is unavailable, Cassady leaves staged files in place and reports manual copy guidance instead of partially modifying the install.
If Cassady is installed through a package manager in the future, prefer that package manager's update command instead of `cass update`.
+33 -8
View File
@@ -1,14 +1,15 @@
# Providers and models # Providers and models
Cassady currently supports OpenAI-compatible providers. A provider supplies the base URL and API key; a model entry supplies metadata for one model id used with that provider. Cassady supports OpenAI-compatible providers plus a built-in `ChatGPT Codex` provider preset. A provider supplies the endpoint and authentication source; a model entry supplies metadata for one model id used with that provider.
## Built-in setup catalog ## Built-in setup catalog
The setup wizard offers these provider templates: The setup wizard offers these provider templates:
| Provider | Provider id | Base URL | Suggested API key env var | | Provider | Provider id | Base URL / endpoint | Suggested auth source |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| OpenAI | `openai` | `https://api.openai.com/v1` | `OPENAI_API_KEY` | | OpenAI | `openai` | `https://api.openai.com/v1` | `OPENAI_API_KEY` |
| ChatGPT Codex | `chatgpt-codex` | `https://chatgpt.com/backend-api/codex/responses` | local Codex auth |
| xAI | `xai` | `https://api.x.ai/v1` | `XAI_API_KEY` | | xAI | `xai` | `https://api.x.ai/v1` | `XAI_API_KEY` |
| Fireworks | `fireworks` | `https://api.fireworks.ai/inference/v1` | `FIREWORKS_API_KEY` | | Fireworks | `fireworks` | `https://api.fireworks.ai/inference/v1` | `FIREWORKS_API_KEY` |
| Groq | `groq` | `https://api.groq.com/openai/v1` | `GROQ_API_KEY` | | Groq | `groq` | `https://api.groq.com/openai/v1` | `GROQ_API_KEY` |
@@ -21,9 +22,23 @@ The setup wizard offers these provider templates:
There is also a custom OpenAI-compatible option. Custom setup asks for provider name, provider id, base URL, API key environment variable, and first model id. There is also a custom OpenAI-compatible option. Custom setup asks for provider name, provider id, base URL, API key environment variable, and first model id.
## Login and logout
Use `cass login` to add or update provider configuration from the shell. Inside an idle chat, `/login` opens the same flow and reloads the active provider/model afterward.
Use `cass logout` or `/logout` to remove saved provider entries from Cassady config. Logout also removes model metadata entries associated with the removed providers and repairs active defaults when other providers remain. It does not delete environment variables, shell profile exports, API keys stored elsewhere, or external provider accounts.
## ChatGPT Codex preset
`ChatGPT Codex` is for users who have already signed in with Codex. Run `codex login` or sign in with the Codex app first, then select `ChatGPT Codex` in `cass login` or `cass setup`.
Cassady reads the bearer token from `$CODEX_HOME/auth.json` or `~/.codex/auth.json` at check/request time. It does not copy the access token or refresh token into `~/.cass`, and `cass check` redacts secret values. Setup prefers the `model` value from `$CODEX_HOME/config.toml` when present and otherwise offers a default/manual model id.
This preset uses `kind: "chatgpt-codex"` and posts to `https://chatgpt.com/backend-api/codex/responses`. That ChatGPT backend endpoint and Codex auth file format are outside Cassady's control, so users may need to update Cassady if they change.
## Model discovery ## Model discovery
When the selected API key environment variable is available, setup tries: For OpenAI-compatible providers, when the selected API key environment variable is available, setup tries:
```text ```text
GET {base_url}/models GET {base_url}/models
@@ -40,7 +55,7 @@ A custom provider should expose OpenAI-compatible chat completions behavior at t
- optional reasoning fields or reasoning request controls; - optional reasoning fields or reasoning request controls;
- optional `/models` discovery during setup. - optional `/models` discovery during setup.
Provider protocols that are not OpenAI-compatible are not currently supported. Provider protocols that are not OpenAI-compatible are supported only when Cassady has an explicit provider kind for them, such as `chatgpt-codex`.
## Provider vs model metadata ## Provider vs model metadata
@@ -48,7 +63,7 @@ Provider protocols that are not OpenAI-compatible are not currently supported.
- provider id; - provider id;
- base URL; - base URL;
- API key reference; - API key reference or local auth source;
- optional default model; - optional default model;
- optional list of associated model ids. - optional list of associated model ids.
@@ -59,7 +74,8 @@ Provider protocols that are not OpenAI-compatible are not currently supported.
- display name; - display name;
- context length and max output tokens; - context length and max output tokens;
- tool and streaming support; - tool and streaming support;
- reasoning support and request format. - reasoning support and request format;
- fast-mode support.
`config.json` selects active defaults, such as `default_provider`, `default_model`, and `default_access_mode`. `config.json` selects active defaults, such as `default_provider`, `default_model`, and `default_access_mode`.
@@ -75,6 +91,15 @@ Reasoning metadata controls how the runtime reasoning effort behaves:
Reasoning display is separate. `show_reasoning` controls whether provider-streamed reasoning is visible in the transcript; press `Ctrl-Shift-R` or `Ctrl-R` to toggle it at runtime. Reasoning display is separate. `show_reasoning` controls whether provider-streamed reasoning is visible in the transcript; press `Ctrl-Shift-R` or `Ctrl-R` to toggle it at runtime.
## Fast-mode metadata
Fast mode has two parts:
- `default_fast_mode` in `config.json`: the user's saved preference.
- `fast_mode.supported` in `models.json`: whether non-Codex provider/model metadata can honor that preference.
Cassady sends fast-mode requests only for `ChatGPT Codex`. Any active `chatgpt-codex` provider model, including `gpt-5.5`, is treated as fast-capable so older model metadata does not block the feature. OpenAI-compatible and custom model entries default to unsupported, so `/fast` can remember the preference without sending provider-specific fields.
## Switching models ## Switching models
Use one of these approaches: Use one of these approaches:
@@ -89,7 +114,7 @@ or inside a chat:
/model MODEL /model MODEL
``` ```
The in-chat model autocomplete lists entries from `~/.cass/models.json`. Switching the model also updates the default model and reasoning effort in `config.json` for future sessions. The in-chat model autocomplete lists entries from `~/.cass/models.json`. Switching the model also updates the default provider, default model, and reasoning effort in `config.json` for future sessions. If fast mode is preferred, Cassady recomputes whether it is active after the switch.
## Health checks ## Health checks
@@ -99,4 +124,4 @@ Run:
cass check cass check
``` ```
This confirms that the active provider and model resolve and that the active API key environment variable is set. Missing inactive-provider keys are warnings; missing active-provider keys are errors. This confirms that the active provider and model resolve. For OpenAI-compatible providers it checks API key environment variables; missing inactive-provider keys are warnings and missing active-provider keys are errors. For `ChatGPT Codex`, it checks that local Codex auth contains an access token and prints recovery steps if not.
+53 -5
View File
@@ -1,6 +1,6 @@
# Troubleshooting # Troubleshooting
Use `cass check` first for configuration problems. It validates files, provider/model references, and API key availability. Use `cass check` first for configuration problems. It validates files, provider/model references, and authentication availability.
## Missing active API key ## Missing active API key
@@ -24,6 +24,22 @@ cass check
cass cass
``` ```
## Missing or expired ChatGPT Codex auth
Symptom: `cass check` reports `Codex auth` errors, or chat startup says provider authentication is not available for `chatgpt-codex`.
Likely cause: `ChatGPT Codex` is active but `$CODEX_HOME/auth.json` or `~/.codex/auth.json` is missing, unreadable, lacks `tokens.access_token`, or contains an expired token.
Fix:
```sh
codex login
cass check
cass
```
You can also sign in with the Codex app if that is how your local Codex auth is managed. Cassady does not refresh or store ChatGPT/Codex tokens; it reads local Codex auth at check/request time and redacts secret values.
## Invalid API key reference ## Invalid API key reference
Symptom: the key is not resolved the way you expect. Symptom: the key is not resolved the way you expect.
@@ -45,9 +61,10 @@ Likely causes:
- wrong `base_url`; - wrong `base_url`;
- network or proxy problem; - network or proxy problem;
- provider outage; - provider outage;
- provider requires a different OpenAI-compatible path. - provider requires a different OpenAI-compatible path;
- for `ChatGPT Codex`, the private ChatGPT backend endpoint changed or the selected model is unavailable.
Fix: verify the base URL in `providers.json`, retry setup, or enter the model id manually if only `/models` discovery is failing. Fix: verify the base URL in `providers.json`, retry setup, or enter the model id manually if only `/models` discovery is failing. For `ChatGPT Codex`, verify that `base_url` is `https://chatgpt.com/backend-api/codex/responses`, rerun `codex login`, and try a current Codex model id.
## `/models` discovery fails ## `/models` discovery fails
@@ -75,9 +92,9 @@ Then verify with a small prompt.
Symptom: the assistant says the provider returned an error. Symptom: the assistant says the provider returned an error.
Likely cause: provider-side authentication, quota, billing, or rate limit. Likely cause: provider-side authentication, quota, billing, or rate limit. For `ChatGPT Codex`, this can also mean your ChatGPT subscription/account does not have the requested Codex model available or the local Codex token needs to be refreshed by Codex.
Fix: confirm the API key, provider account status, selected model, and provider dashboard. Cassady forwards provider failures into the chat but cannot resolve account-level issues. Fix: confirm the API key, provider account status, selected model, and provider dashboard. For `ChatGPT Codex`, rerun `codex login` or open Codex to refresh local auth. Cassady forwards provider failures into the chat but cannot resolve account-level issues.
## Invalid JSON or unknown config fields ## Invalid JSON or unknown config fields
@@ -143,6 +160,37 @@ Likely cause: Windows CRLF line endings or invisible whitespace differences.
Fix: re-read the exact target region and preserve the line endings in `old_text`, or use a smaller unique snippet. Fix: re-read the exact target region and preserve the line endings in `old_text`, or use a smaller unique snippet.
## Branch/restore file conflicts
Symptom: branch-plus-file restore reports conflicts or skips paths.
Likely cause: the file changed outside Cassady after the tracked `write`/`edit`, the file is unsupported for snapshots, or the change came from a shell command or manual editor rather than a Cassady file tool.
Fix: review the restore preview, inspect conflicted files manually, and rerun the menu with conversation-only branching if you only need to revisit the chat. Cassady will not overwrite unknown current content by default. Open the branch/restore menu again with double `Esc` or `/branch` to switch back to the original branch.
## Update command problems
Symptom: `cass update` cannot complete.
Likely causes and fixes:
- Network or GitHub API failure: retry later or verify proxy/firewall settings.
- No matching prebuilt archive: use `cass update --source` if you have Rust installed, or download the release archive manually for a supported target.
- SHA-256 mismatch: do not install the archive. Retry the update; if it repeats, check the GitHub release page before proceeding.
- Missing Rust toolchain in source mode: install Rust/Cargo yourself, then rerun `cass update --source`. Cassady does not install Rust automatically.
- Non-writable install directory: update through the original install method, move Cassady to a directory you own, or manually replace the binaries. Cassady does not run `sudo` for you.
- PATH conflict: `cass update` updates the current executable directory. Run `which cass` / `which cassady` on macOS/Linux or `Get-Command cass` in PowerShell to confirm which binary your shell starts.
- Windows replacement limitation: if Cassady reports that automatic replacement is unavailable, use the staged file paths it prints and copy them after the running process exits.
Useful checks:
```sh
cass update --check
cass update --dry-run
cass --version
cassady --version
```
## Terminal rendering problems ## Terminal rendering problems
Symptom: the UI appears garbled or keys do not behave as expected. Symptom: the UI appears garbled or keys do not behave as expected.
+54 -2
View File
@@ -57,6 +57,36 @@ Run the smallest relevant Rust test for this change, then summarize the result.
When the approval prompt appears, press `y` to approve or `n`/`Esc` to deny. Shell commands run with `sh -c` from the launch cwd and default to a 30-second timeout unless the model requests another timeout. When the approval prompt appears, press `y` to approve or `n`/`Esc` to deny. Shell commands run with `sh -c` from the launch cwd and default to a 30-second timeout unless the model requests another timeout.
## Manage provider login
Add or update provider configuration from the shell:
```sh
cass login
```
Inside an idle chat:
```text
/login
```
Remove saved provider configuration:
```sh
cass logout
```
Inside an idle chat:
```text
/logout
```
Logout removes selected providers from Cassady's config and removes their associated model entries. It does not delete environment variables, local Codex auth, or external provider accounts.
For `ChatGPT Codex`, run `codex login` or sign in with the Codex app before `cass login`. Cassady validates `~/.codex/auth.json` and uses that local token source instead of asking for an API-key environment variable.
## Switch model ## Switch model
Inside a chat: Inside a chat:
@@ -65,7 +95,7 @@ Inside a chat:
/model MODEL_ID /model MODEL_ID
``` ```
Autocomplete lists models from `~/.cass/models.json`. Switching models is allowed only when idle. Cassady persists the last used model and reasoning effort into `config.json`. Autocomplete lists models from `~/.cass/models.json`. Switching models is allowed only when idle. Cassady persists the last used provider, model, and reasoning effort into `config.json`.
You can also launch with a model override: You can also launch with a model override:
@@ -73,6 +103,18 @@ You can also launch with a model override:
cass --model MODEL_ID cass --model MODEL_ID
``` ```
## Prefer fast mode
Inside a chat:
```text
/fast
```
Use `/fast on`, `/fast off`, or `/fast status` when you want an explicit action. Cassady saves the preference in `config.json`, but fast mode is active only when the current provider/model supports it. ChatGPT Codex models, including `gpt-5.5`, are treated as fast-capable.
Switching to an unsupported provider/model keeps the preference but makes `/status` show fast mode as unavailable. Switching back to ChatGPT Codex enables it again.
## Resume a chat ## Resume a chat
List chats for the current directory: List chats for the current directory:
@@ -103,6 +145,16 @@ Inside the UI:
This creates a new chat for the same cwd and model while preserving your current configuration. This creates a new chat for the same cwd and model while preserving your current configuration.
## Branch or restore a conversation point
Press `Esc` twice while idle, or type:
```text
/branch
```
Use the menu to select a related branch or a checkpoint from a user message, assistant message, tool-call request, or tool result. Branching creates a new chat from that point and leaves the original chat available in the same menu. Choose conversation-only branching to leave files untouched, or choose branch-plus-files to restore Cassady-tracked `write`/`edit` snapshots with conflict checks.
## Check status ## Check status
```text ```text
@@ -128,4 +180,4 @@ Config files live under `~/.cass`, outside a normal project workspace. To inspec
cass check cass check
``` ```
Prefer `cass setup` for provider/model changes when possible. For OpenAI-compatible providers this checks API key environment variables. For `ChatGPT Codex` this checks local Codex auth and points you back to `codex login` if the token is missing or expired. Prefer `cass setup` or `cass login` for provider/model changes when possible.
+33
View File
@@ -0,0 +1,33 @@
use cassady::prelude::*;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let session = SessionBuilder::new()
.cwd(std::env::current_dir()?)
.access_mode(AccessMode::ReadOnly)
.build()
.await?;
let mut turn = session
.start_turn("Summarize this project in a few sentences.")
.await?;
while let Some(event) = turn.next_event().await? {
match event {
Event::AssistantChunk(text) => print!("{text}"),
Event::ApprovalRequested(request) => {
eprintln!(
"approval requested for {}: {}; denying in this example",
request.name, request.reason
);
turn.deny(&request.request_id)?;
}
Event::Finished => break,
_ => {}
}
}
let session = turn.finish().await?;
eprintln!("\nResume chat with: cass --resume {}", session.id());
Ok(())
}
+298
View File
@@ -0,0 +1,298 @@
# v0.2.6 Rust Embedding API Implementation Plan
## Goal
v0.2.6 adds the first intentional public Rust API for embedding Cassady in another Rust project. A developer should be able to add Cassady as a dependency, configure a workspace/model/access mode, start a headless agent session, send user messages, receive streamed agent events, and handle approval requests without launching the interactive TUI.
Success statement:
> A small Rust program can import `cassady`, start a new headless session in a workspace, stream assistant/tool events from a turn, optionally approve shell requests, and inspect the updated conversation state using documented experimental APIs.
## Scope
### In scope
- Add an experimental embedding API module with cohesive public types instead of requiring callers to wire together internal modules directly.
- Support starting a new headless agent session from Rust code.
- Support resuming an existing conversation by id when using Cassady's existing conversation storage.
- Support running one turn at a time and streaming typed events to the host application.
- Expose approval handling for tools that require host/user consent, especially shell in `workspace-edit` mode.
- Reuse the existing config, provider, prompt, security, conversation, and tool execution paths used by the CLI/TUI.
- Provide simple builder/options types for cwd, access mode, model/base URL/API key overrides, reasoning effort, and Cassady config root.
- Add a crate-level `prelude` or clearly documented imports for common embedding use.
- Add docs and examples that show a minimal headless integration.
- Add integration tests that exercise the public API without a terminal.
### Out of scope
- Declaring the Rust API stable for semver compatibility. The API should be explicitly marked experimental in v0.2.6.
- Replacing the CLI/TUI as the primary user interface.
- Multi-agent orchestration, task queues, background daemons, schedulers, or distributed workers.
- Custom model provider traits or non-OpenAI-compatible protocols.
- User-defined custom tools or plugin loading.
- A synchronous/blocking API. The first embedding surface can require Tokio.
- Exposing low-level terminal UI internals as supported public API.
- Publishing to crates.io as part of this release unless separately requested.
## Context and Current State
Cassady already builds a library crate:
- `Cargo.toml` defines `[lib] name = "cassady" path = "src/lib.rs"`.
- `src/lib.rs` currently re-exports many internal modules directly and exposes `run()` for the CLI/TUI path.
- `src/agent.rs` contains the core async turn loop:
- `AgentSettings`
- `AgentEvent`
- `AgentCommand`
- `run_turn(...)`
- `run_turn_with_commands(...)`
- `src/app.rs` owns interactive startup, TUI state, chat creation/resume, cancellation, approval UI, and local slash commands.
- `src/conversation.rs` persists conversations as JSONL and can create/load/list chats.
- `src/config.rs` loads providers, models, active defaults, API key references, access mode, tool limits, and docs paths.
- `src/security.rs` centralizes access-mode decisions.
- `src/tools/*` implements the same tools that headless sessions should use.
The current crate can technically be imported, but the supported path is unclear: callers must know which internal modules to combine, how to create base prompts, how to load config safely, how to route approval commands, and how to consume events. v0.2.6 should add a thin, intentional API layer over these internals.
## Design Principles
1. **Thin wrapper over proven internals.** Reuse the same agent loop and policy code as the CLI so embedded behavior matches interactive behavior.
2. **Explicitly experimental.** Make the new API useful without promising final naming or long-term stability yet.
3. **Headless first.** The API should not depend on `ratatui`, terminal setup, crossterm event loops, or slash-command UI state.
4. **Host owns presentation.** Embedded callers receive typed events and decide how to display assistant chunks, tool calls, approvals, and errors.
5. **Safe defaults.** Default to `read-only`, environment-variable API keys, existing Cassady config files, and workspace-rooted paths.
6. **Approval is part of the API.** Hosts must be able to approve or deny requests rather than having Cassady assume a TUI is present.
7. **Keep the first surface small.** Prefer one clear session builder and one turn-running method over exposing every internal knob.
## Design
### Module layout
Add a new module, for example:
```rust
pub mod embedding;
pub mod prelude;
```
`src/embedding.rs` should be the supported experimental API. Existing internal modules can remain public in v0.2.6 for compatibility, but docs should steer new users toward `cassady::embedding` or `cassady::prelude`.
Suggested public surface:
```rust
pub struct SessionBuilder { ... }
pub struct Session { ... }
pub struct SessionOptions { ... }
pub struct Turn { ... }
pub enum Event { ... }
pub enum Command { ... }
pub struct ConversationInfo { ... }
```
The exact names can change during implementation, but they should avoid leaking TUI-specific terms.
### Builder and options
Provide a builder that covers common embedding setup:
```rust
let mut session = cassady::embedding::SessionBuilder::new()
.cwd("/path/to/project")
.access_mode(AccessMode::WorkspaceEdit)
.model("accounts/fireworks/models/qwen3p7-plus")
.build()
.await?;
```
Builder responsibilities:
- Resolve and canonicalize `cwd` like CLI startup.
- Load config from the default Cassady root unless an explicit root/path is supplied.
- Apply model/base URL/API key env overrides without requiring a `Cli` value from callers.
- Resolve API key availability before starting a turn and return a useful error.
- Install or locate bundled docs as needed by `Config::load` behavior.
- Create the base system prompt with `~/.cass/global.md` when starting a new conversation.
- Default access mode to config/default, then builder override, then `read-only` if no config exists.
Avoid requiring callers to import or construct `cli::Cli`.
### New and resumed sessions
Support at least:
```rust
let session = SessionBuilder::new().cwd(".").new_session().await?;
let session = SessionBuilder::new().cwd(".").resume("chat-id").await?;
```
A `Session` should expose lightweight metadata:
```rust
session.id();
session.cwd();
session.model();
session.access_mode();
session.conversation_path();
```
The conversation should continue to be persisted in the same JSONL format so CLI and library sessions can interoperate.
### Running a turn
Provide a headless one-turn API that streams events:
```rust
let mut turn = session.start_turn("Explain the crate layout").await?;
while let Some(event) = turn.next_event().await? {
match event {
Event::AssistantChunk(text) => print!("{text}"),
Event::ApprovalRequested(request) => {
turn.approve(request.id).await?;
}
Event::Finished => break,
_ => {}
}
}
let session = turn.finish().await?;
```
Alternative designs are acceptable, such as returning `(EventStream, CommandSink)` plus a completion handle, as long as examples are simple and approval commands are supported.
The wrapper can map `agent::AgentEvent` and `agent::AgentCommand` into public embedding types. It should avoid exposing internal channel mechanics unless that is the cleanest Tokio-native API.
### Event model
Expose typed events that are stable enough for hosts to build UI/logging around:
- assistant text chunks
- reasoning chunks, when provider/model returns them
- tool call started
- tool output chunk
- tool result
- approval requested
- approval resolved
- status
- turn finished
- error or turn failure
The public event type can wrap or re-export `agent::AgentEvent` initially, but the plan should prefer a dedicated type if it prevents low-level internals from becoming accidental API.
### Approval behavior
Approval requests should include:
- request id
- tool call id
- tool name
- arguments
- human-readable reason
The host should be able to approve or deny by request id. If the host drops the turn or never responds, cancellation/drop behavior should be documented.
For v0.2.6, keep approval policy aligned with `security.rs`:
- `read-only`: shell unavailable.
- `workspace-edit`: shell asks.
- `full-access`: shell allowed.
### Cancellation and drop behavior
The TUI already cancels by aborting the agent task and repairing pending records. The embedding API should define a basic behavior:
- Dropping an active turn should abort the underlying task if possible.
- A simple explicit `cancel()` method is preferred if practical.
- Conversation repair for cancelled turns can be minimal in v0.2.6, but pending tool calls must not corrupt resumed conversations.
If full parity with the TUI cancellation path is too large, document the limitation and add tests for the supported behavior.
### Error handling
Use a public result alias such as:
```rust
pub type Result<T> = std::result::Result<T, Error>;
```
The first pass may wrap `anyhow::Error`, but public errors should include enough context for embedding callers to distinguish:
- config load errors
- missing API key
- provider request errors
- conversation load/create errors
- active turn already running
- approval request not found or already resolved
Do not panic for ordinary configuration or runtime failures.
### Examples
Add at least one compilable example under `examples/`, for example `examples/headless_agent.rs`:
```rust
use cassady::prelude::*;
#[tokio::main]
async fn main() -> cassady::embedding::Result<()> {
let mut session = SessionBuilder::new()
.cwd(std::env::current_dir()?)
.access_mode(AccessMode::ReadOnly)
.build()
.await?;
let mut turn = session.start_turn("Summarize this project.").await?;
while let Some(event) = turn.next_event().await? {
if let Event::AssistantChunk(text) = event {
print!("{text}");
}
}
turn.finish().await?;
Ok(())
}
```
The example should be honest about requiring configured providers and API keys.
## Implementation Steps
1. **Define the experimental API shape.** Add `src/embedding.rs` with builder, session, turn, event, command/approval, and result/error types.
2. **Add non-CLI config loading helpers.** Refactor or add helpers in `src/config.rs` so library callers can apply overrides without constructing `cli::Cli`.
3. **Extract chat creation/resume helpers.** Move reusable prompt/global/conversation setup out of `src/app.rs` into functions usable by both TUI and embedding API.
4. **Wrap the existing agent loop.** Use `agent::run_turn_with_commands` internally and provide a host-friendly event stream plus approval methods.
5. **Handle turn lifecycle.** Ensure a session cannot run overlapping turns unless explicitly supported; persist and return the updated conversation after a turn finishes.
6. **Add cancellation/drop handling.** Provide at least a documented `cancel()` path and avoid leaving pending tool-call records in a corrupted state.
7. **Add examples and docs.** Create a headless example and a bundled docs page for the experimental Rust API.
8. **Update README and crate exports.** Add `embedding`/`prelude` exports and a short README section pointing to the new docs.
9. **Test the public surface.** Add integration tests with a mock OpenAI-compatible server and temporary config/conversation roots.
## Tests
- Unit tests for builder option precedence: default config, explicit cwd, access mode, model, base URL, API key env, and config root.
- Integration test that starts a new session and runs a turn against `wiremock`, asserting assistant chunks and persisted conversation records.
- Integration test that resumes an existing conversation through the embedding API.
- Integration test for approval flow in `workspace-edit` mode using a mock tool call that requests shell approval.
- Test that read-only sessions do not expose write/edit/shell tools through the embedded turn.
- Test that starting a second turn while one is active returns an error or is impossible by type design.
- Example compilation through `cargo test --examples` or equivalent.
## Documentation
- Add `docs/rust-api.md` or `docs/embedding.md` describing the experimental API, setup requirements, minimal example, event loop, approval handling, and limitations.
- Link the new page from `docs/README.md` and the README.
- Document that the API is experimental in v0.2.6 and may change before a stable 1.0-style library contract.
- Include a note that embedded sessions use the same `~/.cass` config and conversation storage by default.
- Mention how hosts should run `cass setup` or provide config programmatically before using the API.
## Acceptance Criteria
- A Rust binary in `examples/` can import `cassady`, create a headless session, run a turn, and stream assistant output without launching the TUI.
- Embedded sessions use the same provider, prompt, security, tool, and conversation paths as the CLI.
- Approval requests can be approved or denied programmatically.
- New public API docs and README links clearly label the surface experimental.
- CLI/TUI behavior remains unchanged.
- `cargo fmt` and `cargo test --locked --all-targets` pass.
+390
View File
@@ -0,0 +1,390 @@
# v0.2.7 Self-Update Command Implementation Plan
## Goal
v0.2.7 adds a polished `cass update` command that can update Cassady from official GitHub releases without requiring users to manually download archives, verify checksums, unpack binaries, or rebuild from source.
Success statement:
> A user can run `cass update`, see the available release, choose the recommended prebuilt binary or a source build fallback, and finish with updated `cass` and `cassady` commands in the same install location.
## Scope
### In scope
- Add a `cass update` / `cassady update` subcommand.
- Query official Cassady GitHub releases from `owenqwenstarsky/cassady`.
- Compare the current binary version with the latest stable release.
- Download and install the matching prebuilt archive when available.
- Verify prebuilt archives with the shipped `.sha256` files before installing.
- Offer a source-build path that downloads release source for the selected tag and builds local binaries.
- Update both shipped binaries, `cass` and `cassady`, when possible.
- Use interactive prompts by default with clear summaries, confirmations, progress, success, and recovery messages.
- Provide non-interactive flags for check-only and yes-to-prompts usage.
- Keep `cass update` independent of model/provider setup so updates work even when `~/.cass` is missing or broken.
- Add tests for release parsing, target detection, asset selection, checksum validation, archive extraction safety, and install planning.
- Update README and bundled docs.
### Out of scope
- Publishing through Homebrew, apt, winget, Scoop, npm, or other package managers.
- Automatic background updates or prompts during normal chat startup.
- Updating Cassady when it was installed by an external package manager that should own the install directory.
- Privilege escalation, `sudo` automation, or administrator prompts.
- Code signing, notarization, or signature verification beyond existing SHA-256 files.
- Downgrading by default. Installing an older tag should require an explicit flag if supported.
- Cross-compiling in source mode. Source builds target the current host platform only.
## Context and Current State
Relevant files:
- `Cargo.toml`: package version and two binaries, `cass` and `cassady`.
- `src/cli.rs`: Clap command definitions currently include `check` and `setup`.
- `src/app.rs`: top-level command dispatch; update should run before setup/config loading.
- `src/main.rs` and `src/bin/cassady.rs`: both call `cassady::run()`.
- `README.md` and `docs/commands.md`: command documentation.
- `docs/platforms.md` and `docs/troubleshooting.md`: platform and recovery guidance.
- `AGENTS.md`: release artifacts use these names:
- `cassady-vX.Y.Z-aarch64-apple-darwin.tar.gz`
- `cassady-vX.Y.Z-x86_64-unknown-linux-gnu.tar.gz`
- `cassady-vX.Y.Z-aarch64-unknown-linux-gnu.tar.gz`
- `cassady-vX.Y.Z-x86_64-pc-windows-gnu.zip`
Current releases include both `cass` and `cassady` in each archive plus one `.sha256` file per archive. The update command should reuse that release contract instead of inventing a new distribution format.
## Design Principles
1. **Boring and recoverable.** Updating should be explicit, easy to understand, and safe to interrupt before installation starts.
2. **Use official release artifacts first.** Prefer prebuilt archives with SHA-256 verification; fall back to source builds when the user asks or no asset matches.
3. **No surprise setup coupling.** Users should not need a configured provider, model, or API key to update the CLI.
4. **Respect install ownership.** Do not auto-escalate privileges or overwrite package-manager-owned paths without clear user confirmation.
5. **Both command names stay aligned.** If the user has both `cass` and `cassady` in the install directory, update them together.
6. **Interactive by default, scriptable when requested.** The normal path should be friendly; flags should support CI/check scripts.
7. **Fail closed on integrity.** Missing or mismatched checksums for prebuilt artifacts must stop installation.
## User Experience
### Default interactive flow
```text
$ cass update
Cassady update
Current version: v0.2.6
Latest release: v0.2.7
Install path: /usr/local/bin
Recommended: prebuilt aarch64-apple-darwin archive
Update Cassady to v0.2.7? [Y/n]
```
If the user accepts, Cassady should show concise phases:
```text
Downloading cassady-v0.2.7-aarch64-apple-darwin.tar.gz ... 8.4 MB
Downloading cassady-v0.2.7-aarch64-apple-darwin.tar.gz.sha256 ... done
Verifying SHA-256 ... ok
Preparing cass and cassady ... ok
Installing to /usr/local/bin ... ok
Verifying installed version ... cass 0.2.7
Cassady is up to date.
```
If the current version is already latest:
```text
Cassady is already up to date.
Current version: v0.2.7
Latest release: v0.2.7
```
### Prebuilt or source selection
The default `auto` mode should choose the prebuilt release asset when a supported target is detected. If no matching prebuilt exists, prompt for source mode:
```text
No prebuilt archive is available for this platform.
Build Cassady v0.2.7 from source instead? [Y/n]
```
If both paths are available and the user asks for source mode:
```sh
cass update --source
```
Cassady should confirm prerequisites before building:
```text
Source build requires cargo, rustc, and a working C toolchain.
Build Cassady v0.2.7 from release source now? [Y/n]
```
### Useful flags
Add a command shape like:
```sh
cass update [OPTIONS]
```
Suggested options:
- `--check`: check GitHub for the latest release and print status without installing.
- `--yes`: accept default prompts for non-interactive use.
- `--prebuilt`: require a matching prebuilt archive; fail instead of falling back to source.
- `--source`: build from release source even when a prebuilt archive exists.
- `--to TAG`: install a specific release tag such as `v0.2.7`.
- `--dry-run`: resolve the release, target, assets, and install path without downloading or installing.
Optional later flags, only if implementation needs them:
- `--stable-only`: ignore prerelease tags during latest-release selection if Cassady later publishes both stable and prerelease channels.
- `--install-dir PATH`: install into an explicit directory. This should be advanced and carefully documented because it can conflict with PATH order.
Avoid adding a public `--repo` override unless needed for testing; tests can inject a mock client instead.
## Design
### Module layout
Add a focused update module:
```rust
pub mod update;
```
Suggested internal types:
```rust
pub struct UpdateOptions { ... }
pub enum UpdateMode { Auto, Prebuilt, Source }
pub struct ReleaseInfo { ... }
pub struct ReleaseAsset { ... }
pub struct PlatformTarget { ... }
pub struct UpdatePlan { ... }
pub enum InstallAction { Replace, AddCompanion, SkipMissingCompanion }
```
`src/cli.rs` should add an `Update` subcommand with parsed flags. `src/app.rs` should dispatch it before setup/config loading:
```rust
if let Some(Command::Update(args)) = cli.command {
return crate::update::run(args).await;
}
```
This keeps update usable even when `Config::load()` would fail.
### GitHub release discovery
Use the GitHub Releases API with an explicit user agent:
- Latest release: `GET https://api.github.com/repos/owenqwenstarsky/cassady/releases?per_page=30` and choose the highest semver non-draft tag, including prereleases because Cassady's current release process marks releases as prereleases.
- Specific tag: `GET https://api.github.com/repos/owenqwenstarsky/cassady/releases/tags/{tag}`
Parse:
- `tag_name`
- `name`
- `draft`
- `prerelease`
- `assets[].name`
- `assets[].browser_download_url`
- `assets[].size`
- `tarball_url` or `zipball_url` for source mode
Use `semver` to compare `env!("CARGO_PKG_VERSION")` with release tags after stripping a leading `v`. Draft releases should never be selected. Prereleases should be eligible by default while Cassady's official releases are marked as prereleases.
### Platform target mapping
Map the running platform to release asset targets:
| OS | Arch | Target | Archive |
| --- | --- | --- | --- |
| macOS | `aarch64` | `aarch64-apple-darwin` | `.tar.gz` |
| Linux | `x86_64` | `x86_64-unknown-linux-gnu` | `.tar.gz` |
| Linux | `aarch64` | `aarch64-unknown-linux-gnu` | `.tar.gz` |
| Windows | `x86_64` | `x86_64-pc-windows-gnu` | `.zip` |
Unsupported platforms should produce a clean message and offer source mode when possible.
### Prebuilt update path
For tag `vX.Y.Z` and target `TARGET`, find:
```text
cassady-vX.Y.Z-TARGET.tar.gz
cassady-vX.Y.Z-TARGET.tar.gz.sha256
```
or on Windows:
```text
cassady-vX.Y.Z-x86_64-pc-windows-gnu.zip
cassady-vX.Y.Z-x86_64-pc-windows-gnu.zip.sha256
```
Flow:
1. Download archive and checksum into a temporary staging directory.
2. Parse the `.sha256` file and verify that the checksum filename matches the downloaded archive name.
3. Compute SHA-256 of the archive and compare exactly.
4. Extract into staging using path traversal checks.
5. Require the expected binaries:
- Unix: `cass`, `cassady`
- Windows: `cass.exe`, `cassady.exe`
6. Run the staged `cass --version` or `cassady --version` when possible and confirm the expected version.
7. Build an install plan for the current executable directory.
8. Confirm the final plan with the user unless `--yes` was supplied.
9. Replace binaries with backups and rollback on failure.
10. Verify installed version after replacement when possible.
Archive extraction must reject absolute paths, `..` components, symlinks that escape staging, and unexpected top-level layouts.
### Source-build update path
Source mode should still be tied to a GitHub release tag, not an arbitrary branch.
Flow:
1. Resolve the selected release tag.
2. Download release source from `tarball_url` or `zipball_url` into staging.
3. Extract with the same path traversal protections as prebuilt archives.
4. Verify `Cargo.toml` version matches the selected tag.
5. Run:
```sh
cargo build --release --locked --bins
```
from the extracted source tree.
6. Locate built binaries under `target/release/`.
7. Run staged `--version` checks.
8. Install using the same installer path as prebuilt updates.
Before source mode starts, check for `cargo` and `rustc` on PATH and show a clear error if they are missing. Do not attempt to install Rust automatically.
### Install planning and replacement
Determine the current executable path with `std::env::current_exe()`, then derive the install directory. The install plan should include:
- current binary path
- sibling `cass` path
- sibling `cassady` path
- which binaries currently exist
- which binaries are writable
- whether companion binaries will be updated, added, skipped, or blocked
Recommended behavior:
- Always update the currently running binary name.
- If the sibling binary exists in the same directory, update it too.
- If the sibling binary is missing and the directory is writable, ask whether to install it.
- If a target path is not writable, stop with an actionable message. Do not invoke `sudo` or administrator prompts automatically.
- Use backups such as `.cass-update-backup-v0.2.6-<timestamp>` during replacement.
- If any replacement fails, restore backups before returning an error.
Unix can generally replace a running executable via atomic rename. Windows cannot reliably overwrite the running `.exe`; implement one of these approaches during coding:
1. Preferred: stage replacements and spawn a small PowerShell or `cmd` helper that waits for the current process to exit, moves files into place, and writes a log.
2. Fallback: stage replacements and print exact manual copy commands if helper launch is unavailable.
Document any Windows limitation honestly in `docs/platforms.md` and `docs/troubleshooting.md`.
### Output and error style
Keep output concise and user-facing:
- Show current version, target version, install directory, selected mode, and asset/source name before changing files.
- Show clear phase lines for download, verify, build, install, and final verification.
- On failure, say whether anything was changed and where staging/backups are located.
- If update cannot proceed because the install path is not writable, tell the user which path failed and suggest reinstalling through the same method they originally used.
Avoid dumping raw GitHub JSON, backtraces, or Cargo logs unless the source build fails; in that case, preserve the final relevant Cargo output and staging path.
## Dependencies
Likely additions to `Cargo.toml`:
- `semver` for version comparison.
- `sha2` for SHA-256 verification.
- `tar` and `flate2` for `.tar.gz` extraction.
- `zip` for Windows release archives and GitHub source zips if used.
Prefer small, well-maintained crates. Reuse existing `reqwest`, `tokio`, `serde`, and `serde_json`.
## Implementation Steps
1. Add CLI parsing for `cass update` and dispatch it before setup/config loading.
2. Add `src/update.rs` with release API types, version comparison, and target detection.
3. Implement GitHub release fetching with a testable client abstraction or injectable base URL for tests.
4. Implement asset selection for current platform and update mode.
5. Implement download, progress reporting, and checksum verification for prebuilt archives.
6. Implement safe archive extraction and staged binary validation.
7. Implement install planning from `current_exe()` and companion binary detection.
8. Implement Unix replacement with backups and rollback.
9. Implement Windows staged-helper replacement or a clearly documented manual fallback.
10. Implement source mode: source download, version validation, prerequisite checks, `cargo build --release --locked --bins`, and staged binary validation.
11. Polish interactive prompts and `--check`, `--dry-run`, `--yes`, `--prebuilt`, `--source`, and `--to` behavior.
12. Update docs and release notes template expectations if needed.
13. Add tests and run full verification.
## Tests
Add focused unit tests for:
- parsing `vX.Y.Z` tags and comparing against the current version shape
- ignoring drafts and prereleases where applicable
- mapping supported and unsupported platform targets
- matching asset and checksum filenames
- parsing `.sha256` lines generated by the release process
- rejecting checksum filename mismatches and digest mismatches
- rejecting archive path traversal entries
- planning installation when only `cass`, only `cassady`, or both binaries exist
- refusing non-writable install targets in planning or dry-run mode
- source mode validating that `Cargo.toml` version matches the selected tag
Add integration-style tests with a mock HTTP server for:
- already-up-to-date response
- latest prebuilt update plan
- missing prebuilt with source fallback prompt path, where build execution can be mocked
- download checksum mismatch failure
- successful staged install into a temporary directory using fake binaries
Manual checks:
```sh
cargo fmt
cargo test --locked --all-targets
cargo run -- update --check
cargo run -- update --dry-run --to v0.2.7
```
For a real release candidate, test from a temporary install directory before using `cass update` on the developer's normal binary.
## Documentation
Update:
- `README.md`: mention `cass update` in install/update and everyday command sections.
- `docs/commands.md`: full command reference, flags, interactivity, examples, and exit behavior.
- `docs/platforms.md`: platform-specific update support and Windows replacement notes.
- `docs/troubleshooting.md`: network failures, checksum mismatch, no matching prebuilt, missing Rust toolchain, non-writable install directory, PATH conflicts, and rollback recovery.
- `docs/README.md`: add any new update-related links or summaries.
Document that users should prefer the package manager's update mechanism if Cassady was installed through a package manager in the future.
## Acceptance Criteria
- `cass update --check` reports the current/latest release without reading provider config.
- `cass update --dry-run` shows the selected release, mode, asset/source, and install plan without modifying files.
- On supported release targets, `cass update` can download the matching official archive, verify SHA-256, stage both binaries, and update the current install directory.
- `cass update --source` can download release source, build with `cargo build --release --locked --bins`, and install the resulting local binaries.
- Checksum mismatch, missing assets, unsupported platforms, missing Rust toolchain, and non-writable install paths fail with clear messages and no partial install.
- Existing `cass` and `cassady` sibling binaries remain version-aligned after a successful update.
- README and bundled docs explain the command accurately.
- `cargo fmt` and `cargo test --locked --all-targets` pass.
@@ -0,0 +1,373 @@
# v0.2.8 Conversation Branch and Restore Implementation Plan
## Goal
v0.2.8 adds an in-chat branch and restore menu opened by pressing `Esc` twice while Cassady is idle. Users should be able to browse the current conversation timeline, choose a checkpoint at a user message, assistant message, or tool call, and branch from that point without destroying the original conversation. They can optionally restore Cassady-tracked file edits to match the selected checkpoint, or branch the conversation only.
Success statement:
> A user can press `Esc` twice, select an earlier message or tool call, create a new branch from that point, optionally restore tracked file edits, and later open the same menu from either branch to switch or branch again from the related conversation history.
## Scope
### In scope
- Add a double-`Esc` idle shortcut that opens a branch/restore menu, similar in feel to the double-`Ctrl-C` exit affordance.
- Keep the existing busy `Esc` behavior for turn cancellation and approval denial.
- Add a branch-aware conversation model that creates a new conversation file when restoring to a checkpoint instead of truncating or overwriting the original chat.
- Let users browse checkpoints for:
- user messages,
- assistant messages,
- assistant tool-call requests,
- completed tool results.
- Preserve valid model conversation structure when branching at or around tool calls.
- Track file mutations made by Cassady's `write` and `edit` tools with enough before/after data to restore workspace files backward or forward between tracked checkpoints.
- Offer restore actions that clearly separate conversation-only branching from conversation-plus-file restoration.
- Allow users to return to the original conversation or other related branches by opening the menu again.
- Add tests for branch metadata, checkpoint extraction, valid tool-call repair, file-edit journaling, workspace restore planning, conflict detection, and keybinding behavior where practical.
- Update README and bundled docs for the new shortcut, branch semantics, file-restore limitations, and safety prompts.
### Out of scope
- Rewriting arbitrary filesystem changes made by shell commands, editors, package managers, test runners, or the user outside Cassady's `write`/`edit` tools.
- Git integration, commits, worktrees, or automatic VCS operations.
- A visual diff editor for every file restore. v0.2.8 should show a concise restore plan and rely on safe conflict checks.
- Merging branches or replaying assistant responses across branches.
- Branching while an agent turn is running.
- Changing provider message semantics beyond the minimum repair needed for valid branched conversations.
## Context and Current State
Relevant files and behavior:
- `src/app.rs` owns the TUI event loop, current conversation, transcript blocks, double-`Ctrl-C` exit behavior, busy `Esc` cancellation, local `/new` and `/resume` commands, and turn spawning.
- `src/conversation.rs` stores conversations as append-only JSONL with `Meta`, `System`, `User`, `Assistant`, and `Tool` records. There is no branch metadata, checkpoint API, or rewrite/create-from-prefix helper yet.
- `src/agent.rs` appends user, assistant, and tool records during a turn. Assistant records can contain multiple tool calls, while each tool result is a separate `Record::Tool`.
- `src/tools/edit.rs` and `src/tools/write.rs` perform atomic writes and return user-visible summaries/diffs, but they do not persist before/after snapshots that can be used for later restore.
- `src/ui/render.rs` renders the main chat. A branch menu should be integrated as an in-TUI modal or state, not by dropping into the setup/update prompt menu in `src/menu.rs`.
The key design constraint is that restore must not mean destructive truncation. Selecting an old point creates a new branch conversation and leaves the source conversation available.
## Design Principles
1. **Branch, do not erase.** Restoring conversation state always creates or switches to a conversation branch; the original JSONL file remains intact.
2. **Make file restore explicit.** Conversation branching is safe and default. File restoration is a separate confirmation because it changes the workspace.
3. **Keep model history valid.** Branches created at tool boundaries must not leave assistant tool calls without corresponding tool records.
4. **Track only what Cassady can prove.** File restore uses durable snapshots from `write`/`edit`; unsupported shell/user changes are detected or warned about, not guessed.
5. **Recoverable navigation.** Every branch keeps parent/checkpoint metadata so the menu can show the related branch family and let users switch or branch again.
6. **Small, testable modules.** Put checkpoint extraction, branch creation, and file restore planning in dedicated modules rather than expanding the TUI loop with business logic.
## User Experience
### Shortcut behavior
- While idle, first `Esc` sets status text:
```text
press Esc again within 1.5s to branch or restore
```
- A second `Esc` within the same window opens the branch/restore menu.
- If the input box is non-empty, do not discard it silently. The first `Esc` should keep the input and show the same status; opening the menu should preserve the draft input if the user cancels.
- While an agent turn is running, keep the current behavior: `Esc` cancels the active turn. Do not open the branch menu while busy.
- During approval prompts, keep `Esc` as denial for the approval request.
### Main branch menu
The menu should show the current branch family, not only the current JSONL prefix:
```text
Branch / Restore
Current chat: 2026-06-25-101533-abcd
Branches
• current branch
• original chat from before restore
• earlier branch: "try without refactor"
Timeline
1. user Add tests for config loading
2. assistant Proposed plan
3. tool read src/config.rs ✓
4. assistant Found config parser
5. tool edit src/config.rs ✓ file: src/config.rs
6. user Make it cleaner
```
Keyboard controls should be consistent with the main TUI: up/down or `j`/`k` move, Enter selects, `Esc` cancels, and an optional `/` filter can be deferred unless cheap.
### Checkpoint actions
After selecting a checkpoint, show an action menu:
```text
Branch from checkpoint
Selected: tool edit src/config.rs at 10:24:11
1. Branch conversation only
2. Branch conversation and restore tracked file edits
3. Preview tracked file restore plan
4. Cancel
```
Default should be conversation-only. The branch should get a fresh chat id, copy records through the selected checkpoint, and append branch metadata. The status should make the branch explicit:
```text
branched 2026-06-25-110212-wxyz from 2026-06-25-101533-abcd at tool edit src/config.rs
```
### Switching among related branches
Opening the menu from a branch should show its ancestors and descendants. Users can switch back to an existing branch without creating another branch:
```text
Switch to branch
original 2026-06-25-101533-abcd 18 records
current 2026-06-25-110212-wxyz branched at tool edit src/config.rs
```
Switching branch changes the active conversation/transcript only. It should not change files unless the user explicitly chooses a file restore action.
### File restore safety
When the user chooses file restoration, show a concise plan before writing:
```text
Restore tracked file edits to selected checkpoint?
Will update:
src/config.rs current hash matches Cassady snapshot
src/app.rs current hash differs; requires confirmation or skip
Will delete:
src/generated.rs created after the checkpoint by Cassady write
Not tracked:
shell command outputs and manual edits cannot be restored automatically
Proceed? [y/N]
```
Rules:
- If the current file hash matches the expected tracked hash, restore automatically after confirmation.
- If the file changed outside Cassady since the relevant snapshot, mark it as a conflict and default to skipping or cancelling the whole restore.
- For files that did not exist at the target checkpoint, delete only if the current content hash matches the tracked created-file hash.
- Never overwrite unknown current content without an explicit conflict confirmation.
## Design
### Conversation branch metadata
Extend the conversation metadata in a backward-compatible way. One acceptable shape is adding optional fields to `Record::Meta` with `#[serde(default)]` and `skip_serializing_if`:
```rust
Record::Meta {
chat_id: String,
created_at: String,
model: String,
cwd: String,
parent_chat_id: Option<String>,
branch_from: Option<BranchPoint>,
}
struct BranchPoint {
chat_id: String,
record_index: usize,
tool_call_id: Option<String>,
checkpoint_label: String,
}
```
Older conversations load with no parent. Descendants can be discovered by scanning `config.conversations_dir()` for `Meta.parent_chat_id` references.
Add a `conversation::create_branch(...)` helper that:
1. loads the source conversation,
2. computes a valid record prefix for the selected checkpoint,
3. writes a new JSONL file with a fresh chat id and branch metadata,
4. preserves the original `System` prompt and source metadata needed for branch navigation,
5. returns the new `Conversation` for the TUI to load immediately.
Do not truncate or rewrite the source conversation.
### Checkpoint extraction
Add a focused module such as `src/branch.rs` or `src/conversation_branch.rs` with types like:
```rust
struct Checkpoint {
id: String,
chat_id: String,
record_index: usize,
tool_call_id: Option<String>,
kind: CheckpointKind,
label: String,
detail: String,
ts: Option<String>,
}
enum CheckpointKind {
User,
Assistant,
ToolCall,
ToolResult,
}
```
Checkpoint rules:
- A user checkpoint means the branch includes that user record.
- An assistant checkpoint means the branch includes that assistant record. If the assistant requested tools, the branch helper must repair or omit incomplete tool-call state before the next provider turn.
- A tool-result checkpoint means the branch includes records through that tool result.
- A tool-call checkpoint without a completed result should branch to the state immediately before executing that tool call, represented by an assistant record plus synthetic denied/cancelled tool records for any required missing calls.
Because OpenAI-compatible providers require every assistant tool call to receive a tool message before the next user message, branch creation must repair partial tool-call groups. Reuse or generalize the existing cancellation repair behavior in `src/app.rs` (`finalize_cancelled_turn` and pending tool-call handling) so branched conversations remain valid.
### File edit journal
Add a durable edit journal separate from model-visible conversation records, for example:
```text
~/.cass/file-edits/<chat_id>.jsonl
~/.cass/file-snapshots/<chat_id>/<tool_call_id>/<hash>.bin
```
Journal entries should be written only for successful `write` and `edit` tool calls:
```rust
struct FileEditJournalEntry {
chat_id: String,
record_index: usize,
tool_call_id: String,
tool_name: String, // write | edit
path: PathBuf,
existed_before: bool,
existed_after: bool,
before_hash: Option<String>,
after_hash: Option<String>,
before_snapshot: Option<PathBuf>,
after_snapshot: Option<PathBuf>,
ts: String,
}
```
Implementation approach:
- Add a `file_edits` module that can capture before/after bytes, hash them, store snapshots, append journal entries, and build restore plans.
- Pass chat id / record index / tool call id into tool execution context, or wrap `write`/`edit` execution in `agent.rs` so the agent captures before/after around successful file tools.
- Store full bytes, not just unified diffs, so restore works both backward and forward.
- Limit snapshots to regular files. If a path is a directory, symlink, binary too large, or otherwise unsafe, skip journaling and note that restore will not cover it.
The first implementation can treat text and binary bytes uniformly for snapshot storage, while still using existing `write`/`edit` tools for text operations.
### Restore planning
File restore should compute a target workspace state from the selected checkpoint and branch lineage:
1. Determine the selected checkpoint's branch lineage back to the root conversation.
2. Load file-edit journal entries along that lineage up to the checkpoint.
3. For every path touched by tracked edits in the relevant branch family, compute the desired state at the checkpoint:
- absent if no tracked edit existed before the checkpoint and the file was created later,
- the last `after_snapshot` at or before the checkpoint,
- the `before_snapshot` for paths whose first tracked edit happened after the checkpoint.
4. Compare the current workspace file hash to the journal's expected current hash when possible.
5. Produce a restore plan with actions: write snapshot, delete file, skip unsupported, conflict.
6. Apply only after explicit confirmation.
For v0.2.8, if cross-branch target-state computation becomes too large, keep the algorithm conservative: support full restore for the current branch's lineage and show a clear unsupported/conflict message for unrelated sibling states. The branch metadata should still be designed so broader cross-branch restore can be added later without changing saved data.
### TUI integration
Add branch-menu state to `run_tui` rather than invoking `src/menu.rs` inside the alternate-screen UI. Suggested approach:
- Add an enum such as `OverlayState::BranchMenu(BranchMenuState)` in `src/app.rs` or a new `src/ui/branch_menu.rs`.
- Extend `render::RenderState` to include an optional overlay.
- Render a centered modal with title, help text, visible items, selected row, and preview/detail panel.
- Route key events to the overlay first while it is open.
- On confirmed branch/switch/restore, update:
- `conversation`,
- `chat_id`,
- `transcript = transcript_from_loaded(...)`,
- active assistant/tool state,
- scroll/stick-to-bottom/status.
Keep the TUI loop readable by moving branch operations into functions such as:
```rust
open_branch_menu(...)
handle_branch_menu_key(...)
apply_branch_action(...)
```
### Slash command fallback
Optionally add a discoverable slash command such as `/branch` or `/restore` that opens the same menu. This is useful for users whose terminals send unusual `Esc` sequences. If added, document it as an alias for the menu rather than a separate workflow.
## Implementation Steps
1. **Add branch metadata and helpers.** Extend `Record::Meta` compatibly, add branch point types, implement branch-family scanning and `create_branch` from a record prefix.
2. **Build checkpoint extraction.** Convert conversations into user/assistant/tool checkpoints with labels, previews, timestamps, and valid prefix calculations.
3. **Repair tool-call prefixes.** Generalize pending-tool-call repair so branches created around tool calls are valid for future provider requests.
4. **Add edit journaling.** Capture successful `write`/`edit` before/after snapshots, append a file-edit journal entry, and keep this separate from model-visible JSONL records.
5. **Implement restore planning.** Load journal entries, compute target states, detect conflicts by hash, and apply writes/deletes safely with existing atomic-write behavior.
6. **Add the in-TUI menu.** Implement double-`Esc` idle detection, overlay state, rendering, keyboard navigation, action confirmation, and branch/switch application.
7. **Wire status and recovery messages.** Make every branch, switch, restore, skip, and conflict result visible in the transcript or status line.
8. **Document the feature.** Update README and bundled docs with shortcut behavior, branch semantics, file restore coverage, and limitations around shell/manual edits.
9. **Test and polish.** Add unit/integration tests, run formatting, and verify the TUI manually in a small repository.
## Tests
- `conversation` tests:
- old JSONL conversations without branch metadata still load,
- new branch metadata serializes/deserializes,
- `create_branch` leaves the source file unchanged,
- branch-family scanning finds ancestors and descendants.
- Checkpoint tests:
- user, assistant, tool-call, and tool-result checkpoints are extracted with stable labels,
- branching at a tool result keeps valid assistant/tool ordering,
- branching in the middle of multi-tool assistant output repairs missing tool results.
- File journal tests:
- `write` records absent-to-present and present-to-present snapshots,
- `edit` records before/after bytes for successful edits only,
- failed or denied tools do not create journal entries.
- Restore-plan tests:
- restore to an earlier checkpoint rewrites tracked files to prior content,
- restore to a later checkpoint can reapply tracked content from snapshots,
- created files are deleted only when hashes match,
- external modifications are reported as conflicts.
- TUI/key tests where practical:
- first idle `Esc` sets double-press status,
- second idle `Esc` opens the branch menu,
- busy `Esc` still cancels a turn,
- approval `Esc` still denies approval.
Manual checks:
- Start a chat, make a `write` edit, branch conversation-only from before the edit, confirm the original remains available.
- Open the menu from the branch and switch back to the original chat.
- Branch with file restore and verify the workspace file content matches the chosen checkpoint.
- Trigger a conflict by manually editing a tracked file before restore and confirm Cassady refuses to overwrite it by default.
## Documentation
Update:
- `README.md`: everyday workflow section for branching/restoring and a short safety note.
- `docs/commands.md` or the relevant TUI guide: double-`Esc`, optional `/branch`, and menu controls.
- `docs/troubleshooting.md`: conflicts, unsupported shell/manual edits, and how to switch back to the original branch.
- Any keyboard shortcut table maintained in bundled docs.
## Acceptance Criteria
- Pressing `Esc` twice while idle opens a branch/restore menu.
- Selecting a user, assistant, or tool checkpoint creates a new branch conversation without modifying the source conversation.
- The branch menu can be opened from the new branch to switch back to the original or create another branch.
- Users can choose conversation-only branching or branch-plus-file restore.
- File restore covers successful Cassady `write`/`edit` mutations with before/after snapshots and refuses unsafe overwrites by default.
- Branches created around tool calls produce valid future model requests.
- Existing conversations remain loadable.
- `cargo fmt` and `cargo test --locked --all-targets` pass.
@@ -0,0 +1,135 @@
# v0.2.9 Provider Login Management Implementation Plan
## Goal
This release focuses on making provider configuration available from both the shell and an active Cassady chat. Users should be able to run `cass login` or type `/login` to configure one or more OpenAI-compatible providers, and use `cass logout` or `/logout` to remove saved providers and their model entries without hand-editing JSON files.
Success statement:
> A user can add, switch, and remove provider/model configuration from Cassady's normal command surfaces, then continue chatting with a valid active provider.
## Scope
### In scope
- Add `cass login` as an alias-style command for the existing setup wizard.
- Add `/login` inside the TUI, available only while idle.
- Add `cass logout` with an interactive provider removal menu.
- Add `/logout` inside the TUI, available only while idle.
- Remove provider definitions and their associated `models.json` entries together.
- Update `config.json` active defaults after removal so they do not point at missing providers or models.
- Reload active config after login/logout inside the TUI.
- Document the new commands in bundled command/config docs.
- Add focused unit tests for provider removal and local command parsing/autocomplete.
### Out of scope
- Browser OAuth or provider-hosted account login flows.
- Storing literal API keys from the wizard by default.
- Non-OpenAI-compatible provider protocols.
- Deleting shell environment variables or secrets outside `~/.cass`.
- Publishing, tagging, or preparing release artifacts.
## Context
Cassady already has most provider setup primitives:
- `src/setup.rs` contains the interactive provider/model setup wizard, provider catalog, model discovery, and JSON upsert helpers.
- `src/config.rs` owns `config.json`, `providers.json`, `models.json`, active provider/model resolution, and validation.
- `src/app.rs` owns top-level CLI dispatch plus in-chat slash command parsing and execution.
- `docs/commands.md`, `docs/configuration.md`, and `docs/workflows.md` document the existing `cass setup`, `cass check`, and `/model` behavior.
The existing setup wizard writes provider connection definitions to `providers.json`, model metadata to `models.json`, and active defaults to `config.json`. The new login command can reuse that flow. Logout needs a new inverse operation that edits all three files consistently.
## Design Principles
1. Reuse setup behavior instead of creating a second provider configuration path.
2. Keep removal explicit and reversible by avoiding broad file deletion and by preserving unrelated providers/models.
3. Never remove API keys from the user's shell or keychain; Cassady only edits its own config files.
4. Keep in-chat provider management idle-only, because active turns depend on a stable provider config.
## Design
### CLI commands
Add these subcommands:
```text
cass login
cass logout
```
`cass login` runs the same interactive wizard as `cass setup`, with text that frames the action as adding or updating provider login configuration. It may start a chat afterward when invoked from an otherwise normal chat startup path only if the existing setup outcome says it should; direct `cass login` should save config and exit.
`cass logout` opens a multi-select menu of saved providers:
```text
Remove saved providers
[ ] OpenAI openai · gpt-4.1
[ ] Groq groq · llama-3.3-70b-versatile
```
After confirmation, Cassady removes the selected providers from `providers.json` and removes `models.json` entries whose `provider` matches a removed provider id. If the active provider was removed, Cassady selects the first remaining provider and one of its models. If no providers remain, `default_provider`, `default_model`, and `default_reasoning_effort` are cleared so the next `cass` run offers setup.
### In-chat commands
Add slash commands:
```text
/login
/logout
```
Both commands are idle-only. Because the TUI uses the alternate screen and raw input mode, command execution should temporarily leave the TUI, run the existing menu-driven flow in the normal terminal, reload config, then re-enter the TUI and append a status block.
After `/login`, reload `Config` from disk and keep the current conversation open. If the active provider/model changed, future turns use the new provider and model. The status block should show the active provider and model.
After `/logout`, reload `Config` when a provider remains. If no provider remains or config cannot resolve, keep the chat open but append a clear status/error telling the user to run `/login` before sending another turn.
### Provider/model removal helper
Add reusable setup/config helpers:
- `configured_providers(root) -> Vec<ProviderLogoutCandidate>`
- `remove_providers(root, provider_ids) -> LogoutResult`
`LogoutResult` should include removed provider ids, removed model count, remaining provider count, and the new active provider/model when one exists. This keeps CLI output, TUI status, and tests deterministic.
## Implementation Steps
1. Add the v0.2.9 roadmap entry and this plan.
2. Add `Login` and `Logout` CLI variants and dispatch them from `app::run`.
3. Refactor setup mode text as needed so `cass login` can share the setup wizard.
4. Implement provider removal helpers in `src/setup.rs` using existing config structs.
5. Add menu-driven `setup::logout(root)` for CLI and TUI use.
6. Add `/login` and `/logout` to local command parsing, autocomplete, and idle command handling.
7. Add a small terminal leave/re-enter helper around blocking login/logout menus inside the TUI.
8. Update command/config/workflow docs.
9. Add focused tests for removal behavior and command parsing/autocomplete.
## Tests
- Removing one provider preserves unrelated providers and models.
- Removing the active provider chooses a valid remaining provider/model.
- Removing all providers clears active defaults.
- Removing an unknown provider id is rejected.
- `/login` and `/logout` parse only with no arguments.
- Command autocomplete lists `/login` and `/logout`.
- `cargo fmt` passes.
- `cargo test --locked --all-targets` passes when practical.
## Documentation
- Update `docs/commands.md` with `cass login`, `cass logout`, `/login`, and `/logout`.
- Update `docs/configuration.md` to point users toward login/logout for managed provider edits.
- Update `docs/workflows.md` with login/logout examples near model/provider workflows.
## Acceptance Criteria
- `cass login` opens the provider setup wizard and exits after saving direct login changes.
- `cass logout` removes selected providers and their models with confirmation.
- `/login` and `/logout` work from an idle chat and reload active provider config afterward.
- Removing the active provider never leaves `config.json` pointing at a missing provider/model.
- Existing `cass setup`, first-run setup, `cass check`, and `/model` behavior still work.
- `cargo fmt` and `cargo test --locked --all-targets` pass.
+234
View File
@@ -0,0 +1,234 @@
# v0.3.0 ChatGPT Codex Provider Implementation Plan
## Goal
This release adds a first-class `ChatGPT Codex` provider preset so users who are already signed in to Codex with a ChatGPT subscription can run Cassady without creating a separate API-key environment variable. The preset should call `https://chatgpt.com/backend-api/codex/responses` and resolve its bearer token from the local Codex auth config by default.
Success statement:
> A user who has already run `codex login` or signed in through the Codex app can select `ChatGPT Codex` in `cass login`, pass `cass check`, and send Cassady turns through their Codex subscription without copying tokens into Cassady config.
## Scope
### In scope
- Add `ChatGPT Codex` as a built-in provider preset in the setup/login catalog.
- Add a provider kind/client for the ChatGPT Codex responses endpoint rather than forcing it through `/chat/completions` URL construction.
- Read the default access token from the local Codex auth file, normally `$CODEX_HOME/auth.json` or `~/.codex/auth.json`.
- Support the observed Codex auth shape with `tokens.access_token`, while keeping token values out of Cassady config, logs, check output, and error text.
- Prefer the Codex-configured model from `$CODEX_HOME/config.toml` when available, with a safe manual model fallback.
- Teach `cass check` to validate that local Codex auth is present and usable for the active `ChatGPT Codex` provider.
- Add docs explaining prerequisites, setup flow, token-source behavior, expiration troubleshooting, and the distinction between ChatGPT subscription access and API-key providers.
- Add focused tests with temporary Codex-home fixtures and mocked streaming responses.
### Out of scope
- Implementing Cassady's own browser OAuth/device-login flow for ChatGPT.
- Storing or refreshing ChatGPT/Codex tokens in Cassady-owned config files.
- Reverse engineering unrelated ChatGPT backend endpoints beyond the requested Codex responses endpoint.
- Guaranteeing compatibility if the private ChatGPT backend endpoint or Codex auth file format changes.
- Replacing OpenAI-compatible provider support or changing existing provider presets.
- Release tagging, packaging, or GitHub release creation.
## Context or Current State
Cassady's provider stack is currently centered on OpenAI-compatible chat completions:
- `src/setup.rs` owns the built-in provider catalog, setup/login prompts, model discovery via `GET {base_url}/models`, and writes to `providers.json`/`models.json`/`config.json`.
- `src/config.rs` defines `ProviderDefinition`, validates provider registries, resolves `api_key` values from literals or environment-variable references, and currently accepts only `kind = "openai-compatible"`.
- `src/agent.rs` constructs `OpenAiCompatibleProvider` directly from resolved config.
- `src/providers/openai_compatible.rs` appends `/chat/completions`, sends OpenAI-compatible chat payloads, and parses OpenAI-compatible streaming deltas.
- `docs/providers.md`, `docs/configuration.md`, `docs/commands.md`, `docs/workflows.md`, and `README.md` describe provider setup as API-key/environment-variable based.
The new preset differs in two important ways:
1. Authentication should come from Codex's local login state, not from a Cassady environment-variable API key.
2. The endpoint is a Codex-specific responses endpoint (`https://chatgpt.com/backend-api/codex/responses`), so Cassady needs an endpoint-specific provider client or a more general provider dispatch layer.
Local Codex auth is expected to live under Codex home, normally `~/.codex/auth.json`, with a shape like:
```json
{
"auth_mode": "chatgpt",
"tokens": {
"access_token": "...",
"refresh_token": "...",
"account_id": "..."
},
"last_refresh": "..."
}
```
Cassady should treat this file as sensitive input: read it only when resolving the active provider token, never copy the access token into Cassady-owned JSON, and never print token contents.
## Design Principles
1. **Use Codex login state, do not own ChatGPT auth.** Cassady should integrate with an existing Codex login and tell users to run `codex login` or sign in to Codex when auth is missing or expired.
2. **Keep provider protocols explicit.** Do not pretend the ChatGPT Codex endpoint is OpenAI-compatible if it needs different URL construction, request shape, or stream parsing.
3. **Avoid token leakage.** Token values must not be stored in `~/.cass`, included in transcripts, surfaced in `cass check`, or embedded in test snapshots.
4. **Keep existing setup stable.** Existing providers should continue to use environment-variable API keys and `/models` discovery without extra Codex dependencies.
5. **Fail with clear recovery steps.** Missing Codex auth should produce actionable messages, not generic provider errors.
## Design
### Provider catalog and setup UX
Add a built-in catalog entry:
| Provider | Provider id | Kind | Endpoint | Token source |
| --- | --- | --- | --- | --- |
| ChatGPT Codex | `chatgpt-codex` | `chatgpt-codex` | `https://chatgpt.com/backend-api/codex/responses` | Local Codex auth |
In `cass login`/`cass setup`, selecting this provider should skip the normal `API key environment variable` prompt and instead show a prerequisite check:
```text
ChatGPT Codex uses your local Codex login.
✓ Found Codex auth at ~/.codex/auth.json
```
If the file or access token is missing:
```text
ChatGPT Codex needs a local Codex login.
Run `codex login` or sign in with the Codex app, then run `cass login` again.
```
Model selection should prefer, in order:
1. The `model` value from `$CODEX_HOME/config.toml` when present.
2. A known default Codex model constant only if the project already has a current default available.
3. Manual model id entry.
Do not call `GET /models` for `chatgpt-codex` unless a verified endpoint is added later; model discovery remains an OpenAI-compatible setup behavior.
### Provider configuration shape
Extend provider config without breaking existing files. One possible JSON shape is:
```json
{
"id": "chatgpt-codex",
"name": "ChatGPT Codex",
"kind": "chatgpt-codex",
"base_url": "https://chatgpt.com/backend-api/codex/responses",
"auth": { "type": "codex_local" },
"default_model": "gpt-5.5",
"models": ["gpt-5.5"]
}
```
Implementation may choose an equivalent internal representation, but it should preserve these properties:
- Existing `api_key` string behavior remains valid for OpenAI-compatible providers.
- `chatgpt-codex` providers can omit environment-variable API keys.
- `cass check` can distinguish missing local Codex auth from missing API-key env vars.
- Serialized config does not contain the Codex access token.
### Codex auth resolution
Add a small resolver module, for example `src/codex_auth.rs`, with helpers like:
- `codex_home() -> PathBuf`: `$CODEX_HOME` when set, otherwise `~/.codex`.
- `codex_auth_path() -> PathBuf`: `$CODEX_AUTH_FILE` for tests/overrides when set, otherwise `{codex_home}/auth.json`.
- `load_codex_access_token() -> Result<CodexAccessToken>`: parse `tokens.access_token` and return a redacted/display-safe token wrapper.
- `check_codex_auth() -> CodexAuthStatus`: report path found, auth mode, access-token presence, optional JWT expiration, and recovery hints.
If the access token looks like a JWT, parse the `exp` claim without validating the signature so Cassady can warn or fail early when the token is expired. Token refresh itself should stay out of scope unless Codex exposes a stable documented local refresh interface.
Read the token at request time rather than caching it during setup. This allows a separate Codex process to refresh `auth.json` between Cassady turns.
### Provider dispatch
Refactor provider construction so `src/agent.rs` does not instantiate only `OpenAiCompatibleProvider`. A simple first step is an enum:
```rust
enum ProviderClient {
OpenAiCompatible(OpenAiCompatibleProvider),
ChatGptCodex(ChatGptCodexProvider),
}
```
Both variants should expose a common `complete(messages, tools, tx)` async method returning the existing `CompletionResult`. This preserves the current agent loop, tool execution, conversation storage, and TUI behavior.
### ChatGPT Codex responses client
Add a new provider module, for example `src/providers/chatgpt_codex.rs`, that:
- Posts to the exact configured endpoint, defaulting to `https://chatgpt.com/backend-api/codex/responses`.
- Sends `Authorization: Bearer <local Codex access token>`.
- Includes the active model and converted message/tool context in the endpoint's expected responses format.
- Streams assistant text into `AgentEvent::AssistantChunk`.
- Streams reasoning summaries into `AgentEvent::ReasoningChunk` only when the endpoint provides a safe reasoning summary field.
- Converts function/tool call deltas into Cassady `StoredToolCall` values.
- Converts Cassady tool results back into the endpoint's function-call-output input shape on the next turn.
- Redacts authentication details from non-success response errors.
The exact request/stream schema should be verified against the endpoint during implementation and captured in mocked fixtures. If the endpoint rejects a field used by OpenAI-compatible providers, keep the Codex payload minimal rather than adding compatibility shims that risk breaking the flow.
### Check and troubleshooting behavior
For active `chatgpt-codex` providers, `cass check` should report status like:
```text
✓ active provider: chatgpt-codex
✓ endpoint: https://chatgpt.com/backend-api/codex/responses
✓ Codex auth: ~/.codex/auth.json contains an access token
```
Failure should point to recovery:
```text
✗ Codex auth: no access token found in ~/.codex/auth.json
Run `codex login` or sign in with the Codex app, then rerun `cass check`.
```
Do not print the token, account id, refresh token, or full auth JSON.
## Implementation Steps
1. Add the v0.3.0 roadmap entry and this implementation plan.
2. Extend provider config types/validation to support `kind = "chatgpt-codex"` and a non-env local Codex auth source while preserving existing OpenAI-compatible files.
3. Add `src/codex_auth.rs` for Codex home discovery, auth-file parsing, redacted status reporting, and optional JWT expiration checks.
4. Add `ChatGPT Codex` to `src/setup.rs` provider catalog and branch setup behavior so it skips API-key env prompts and `/models` discovery.
5. Refactor provider construction in `src/agent.rs` behind a small provider dispatch enum or trait.
6. Implement `src/providers/chatgpt_codex.rs` with endpoint-specific request conversion, streaming parsing, tool-call conversion, and redacted errors.
7. Update `cass check` so active and inactive provider checks understand Codex-local auth separately from environment-variable API keys.
8. Update README and bundled docs for the new preset, prerequisites, config example, troubleshooting, and known endpoint/auth caveats.
9. Add unit tests for config parsing/validation, Codex auth fixtures, setup catalog behavior, and provider dispatch.
10. Add mocked streaming tests for the ChatGPT Codex client, including text, tool calls, tool outputs, auth failures, and redaction.
## Tests
- `providers.json` with existing OpenAI-compatible providers still parses and validates.
- A `chatgpt-codex` provider with local Codex auth validates without `api_key`/env-var availability.
- Missing `~/.codex/auth.json` produces a clear `cass check` error for an active `chatgpt-codex` provider.
- A fixture `auth.json` with `tokens.access_token` resolves a token but redacts it in display and errors.
- Expired JWT-like access tokens are detected when possible and produce a recovery hint.
- Setup/login catalog includes `ChatGPT Codex` and skips the API-key env-var prompt for that provider.
- Model selection uses `$CODEX_HOME/config.toml` `model` when available, with manual fallback.
- Provider dispatch selects `ChatGptCodexProvider` only for `kind = "chatgpt-codex"`.
- Mocked Codex streaming responses produce assistant chunks and final `CompletionResult.content`.
- Mocked Codex function-call streams produce Cassady `StoredToolCall` values and accept subsequent tool output messages.
- Provider error messages never include access tokens, refresh tokens, or raw auth JSON.
- `cargo fmt` passes.
- `cargo test --locked --all-targets` passes when practical.
## Documentation
- Update `README.md` setup/provider sections with `ChatGPT Codex` as a subscription-backed option.
- Update `docs/providers.md` with the new preset, endpoint, token-source behavior, and private-endpoint caveat.
- Update `docs/configuration.md` with the extended provider schema and a safe example that uses local Codex auth.
- Update `docs/commands.md` and `docs/workflows.md` for `cass login`, `cass check`, and troubleshooting steps.
- Update `docs/troubleshooting.md` with missing/expired Codex auth, unsupported model, and backend endpoint failure guidance.
## Acceptance Criteria
- `cass login` offers `ChatGPT Codex` as a provider preset.
- Selecting `ChatGPT Codex` does not ask for an API-key environment variable by default.
- Cassady reads the access token from local Codex auth at request/check time and never stores that token under `~/.cass`.
- Active `chatgpt-codex` sessions call `https://chatgpt.com/backend-api/codex/responses` instead of appending `/chat/completions`.
- Normal OpenAI-compatible providers continue to work unchanged.
- `cass check` gives clear success/failure output for local Codex auth without leaking secrets.
- README and bundled docs explain the prerequisite of signing in to Codex first.
- `cargo fmt` and `cargo test --locked --all-targets` pass.
+285
View File
@@ -0,0 +1,285 @@
# v0.3.2 Fast Mode Implementation Plan
## Goal
v0.3.2 adds a `/fast` command that lets users opt into faster provider inference when the active provider/model supports it. The setting should feel like a user preference, but the runtime state should be capability-aware: fast mode is shown as enabled only when the current provider/model can actually honor it.
Success statement:
> A ChatGPT Codex user can type `/fast`, see fast mode enabled for Codex models that support it, switch to an unsupported provider/model and see fast mode become unavailable, then switch back and have the preference apply again.
## Scope
### In scope
- Add an idle-only `/fast` local command that toggles the user's fast-mode preference.
- Persist the preference in Cassady config so it survives new chats and restarts.
- Add provider/model capability metadata that determines whether fast mode is currently active.
- Implement fast-mode request support for `ChatGPT Codex` first.
- Keep unsupported providers/models explicit: the preference can remain on, but the UI/status should say fast mode is unavailable rather than enabled.
- Update `/status`, the bottom/status line, command autocomplete/help, README, and bundled docs.
- Add focused tests for command parsing, persistence, capability gating, provider request shaping, and model switching.
### Out of scope
- Adding fast-mode support for OpenAI-compatible providers in v0.3.2.
- Guessing provider-specific fast-mode request fields without verified behavior.
- Adding latency benchmarking, automatic mode selection, or per-turn speed/quality controls beyond the `/fast` toggle.
- Changing the default model selection flow except to record fast-mode capability for known built-in presets.
- Treating fast mode as a quality guarantee; providers may still vary in latency and output behavior.
## Context or Current State
Cassady already has several runtime preferences and model/provider capability paths that should guide this work:
- `src/app.rs` parses local slash commands such as `/model`, `/login`, `/logout`, and `/status`, and already restricts provider/model changes to idle state.
- `src/config.rs` persists default model and reasoning effort in `config.json` and stores model metadata in `models.json`.
- `ModelDefinition` already includes capability-like metadata such as `supports_tools`, `supports_streaming`, and `reasoning`.
- `ProviderClient::from_config` in `src/providers/mod.rs` dispatches by provider kind to `OpenAiCompatibleProvider` or `ChatGptCodexProvider`.
- `src/providers/chatgpt_codex.rs` is the first provider where fast mode should affect the outgoing request.
- `/model` already reloads model metadata and resets reasoning effort based on the new model.
- `/status` currently reports chat id, model, mode, cwd, records, and current status.
The important product behavior is that "fast mode preference" and "fast mode active" are different states:
- Preference: whether the user wants fast mode when possible.
- Active: whether the current provider/model supports fast mode and the preference is enabled.
## Design Principles
1. **Preference stays stable, capability controls activation.** Switching to an unsupported provider/model should not erase the user's preference; it should only make fast mode inactive until support is available again.
2. **Provider-specific request details stay behind provider clients.** The agent loop should pass a normalized fast-mode flag; each provider decides whether and how to encode it.
3. **UI wording must distinguish enabled from unavailable.** Avoid showing "fast mode enabled" when Cassady cannot send a fast-mode request for the active provider/model.
4. **Extend metadata, do not hardcode every check in the TUI.** Use provider/model capability helpers so future providers can add fast mode without rewriting command handling.
5. **Keep unsupported behavior quiet and compatible.** Existing OpenAI-compatible providers should continue working unchanged and should not receive unknown request fields.
## Design
### User model
Add a user preference to `config.json`:
```json
{
"default_fast_mode": true
}
```
Suggested behavior:
- Missing `default_fast_mode` defaults to `false`.
- `/fast` toggles the preference while idle.
- `/fast on` and `/fast off` may be supported if easy, but the minimum required command is the toggle form.
- The preference is persisted immediately, similar to last-used model/reasoning persistence.
- The active state is recomputed whenever config, provider, model, or model metadata changes.
Status examples:
```text
fast mode: enabled
fast mode: unavailable for provider fireworks
fast mode: off
```
If the user toggles fast mode on while using an unsupported provider:
```text
fast mode preference on; unavailable for this provider/model
```
If the user later switches to a supported Codex model, the UI should show:
```text
fast mode enabled
```
### Capability model
Add a small capability representation, preferably on model metadata with provider-kind fallback:
```json
{
"id": "gpt-5.5",
"provider": "chatgpt-codex",
"fast_mode": {
"supported": true
}
}
```
Rules:
- `fast_mode.supported` defaults to `false` unless a provider-specific built-in preset intentionally marks it true.
- For the `ChatGPT Codex` built-in setup path, saved Codex model metadata should mark fast mode as supported when the implementation can send the fast-mode request for that provider.
- Manual custom providers and discovered OpenAI-compatible models should default to unsupported.
- If a provider supports fast mode for all models but model metadata is missing, provider-specific capability fallback may return supported. Keep that fallback in config/provider capability helpers, not in UI string matching.
Add helper APIs along these lines:
```rust
pub struct FastModeState {
pub preferred: bool,
pub supported: bool,
pub active: bool,
pub unavailable_reason: Option<String>,
}
impl Config {
pub fn fast_mode_state(&self) -> FastModeState;
}
```
`active` should be exactly `preferred && supported`.
### Provider request behavior
Thread the active fast-mode boolean through the provider settings:
```rust
ProviderClient::from_config(&config, reasoning_effort, fast_mode_active)
```
or include it in a runtime options struct if that is cleaner:
```rust
pub struct ProviderRuntimeOptions {
pub reasoning_effort: ReasoningEffort,
pub fast_mode: bool,
}
```
`ChatGptCodexProvider` should encode fast mode using the verified Codex responses request shape. During implementation, verify the exact field against the current Codex behavior and capture the resulting request body in tests. The plan intentionally does not prescribe a speculative field name.
OpenAI-compatible providers should ignore the setting until support is explicitly added. They must not receive experimental Codex-only fields.
### UI and command behavior
Add `LocalCommand::Fast(FastModeCommand)` in `src/app.rs`.
Minimum command behavior:
```text
/fast
```
Recommended optional forms:
```text
/fast on
/fast off
/fast status
```
Command handling:
- Only allow changes while idle.
- Persist the preference to `config.json`.
- Recompute active state from the current provider/model after toggling.
- Append or show a concise status message.
- Include `/fast` in autocomplete/local command help.
Update `/status` to include both preference and active state, for example:
```text
fast: enabled
```
or:
```text
fast: preferred, unavailable for provider fireworks
```
The bottom/status line should include a compact signal only when useful:
- `fast` when active.
- No `fast` label when off.
- Optional `fast unavailable` only immediately after toggling or in `/status`, to avoid clutter.
### Model and provider switching
When `/model` changes the active model:
- Reload `config.model_metadata` as today.
- Recompute reasoning effort as today.
- Recompute fast-mode state.
- Show the model status with fast-mode state when the preference is on.
Expected examples:
```text
model: gpt-5.5 · fast enabled
model: accounts/fireworks/models/qwen3p7-plus · fast unavailable
```
When `/login` or `/logout` updates provider config:
- Reload config as today.
- Preserve `default_fast_mode`.
- Recompute fast-mode state for the new active provider/model.
### Configuration and docs
Update docs to describe:
- `default_fast_mode` in `config.json`.
- `fast_mode.supported` in `models.json`.
- `/fast` command behavior.
- Provider support status: v0.3.2 supports fast mode only for `ChatGPT Codex`.
- The distinction between fast-mode preference and active fast-mode support.
## Implementation Steps
1. Extend config types in `src/config.rs`:
- Add `default_fast_mode: Option<bool>` to the config file representation.
- Add `fast_mode` metadata to model definitions.
- Add a `FastModeState` helper that computes preferred/supported/active.
2. Add persistence helpers:
- Save fast-mode preference without disturbing unrelated config fields.
- Ensure existing `save_last_used` behavior preserves the new field.
3. Mark built-in `ChatGPT Codex` model metadata as fast-mode capable during setup/login when the provider implementation supports it.
4. Add provider runtime options and pass `fast_mode_state.active` into `ProviderClient` construction from `src/agent.rs`.
5. Implement Codex request support in `src/providers/chatgpt_codex.rs` using the verified fast-mode request shape.
6. Keep `OpenAiCompatibleProvider` behavior unchanged and add tests proving it does not receive fast-mode fields.
7. Add `/fast` parsing and idle command handling in `src/app.rs`, including optional `on`, `off`, and `status` forms if the implementation remains small.
8. Update `/status`, status-line rendering, autocomplete/help text, and model-switch status messages.
9. Update `README.md`, `docs/commands.md`, `docs/configuration.md`, `docs/providers.md`, `docs/workflows.md`, and `docs/glossary.md`.
10. Add focused tests and run `cargo fmt` plus `cargo test --locked --all-targets`.
## Tests
- `config.json` without `default_fast_mode` defaults to fast mode off.
- `default_fast_mode: true` loads and persists without losing existing config fields.
- `models.json` parses `fast_mode.supported`.
- Unsupported or missing fast-mode metadata produces `FastModeState { preferred: true, supported: false, active: false }`.
- A supported ChatGPT Codex model produces `active: true` when preference is on.
- `/fast` parses as a local command and rejects unexpected arguments unless explicit `on`/`off`/`status` forms are implemented.
- `/fast` cannot change preference during an active turn.
- Toggling `/fast` while on an unsupported provider stores the preference but reports unavailable.
- Switching from a supported Codex model to an unsupported model hides the active fast-mode signal without clearing the preference.
- Switching back to a supported Codex model restores active fast mode.
- `ChatGptCodexProvider` includes the verified fast-mode request field only when active.
- `OpenAiCompatibleProvider` request bodies are unchanged when fast-mode preference is on but unsupported.
- `/status` includes fast-mode state.
- README and bundled docs mention `/fast` and provider-specific support.
- `cargo fmt` passes.
- `cargo test --locked --all-targets` passes when practical.
## Documentation
- README command list and provider setup notes.
- `docs/commands.md` for `/fast` syntax and idle-only behavior.
- `docs/configuration.md` for `default_fast_mode` and `models.json` fast-mode capability metadata.
- `docs/providers.md` for the initial ChatGPT Codex-only support.
- `docs/workflows.md` for switching models/providers with fast-mode preference preserved.
- `docs/glossary.md` for "Fast mode" as a preference plus provider/model capability.
## Acceptance Criteria
- `/fast` toggles a persisted fast-mode preference.
- Fast mode is shown as enabled only when the active provider/model supports it.
- Unsupported providers/models do not show fast mode enabled and do not receive fast-mode request fields.
- ChatGPT Codex requests include the verified fast-mode option when the preference is on and the active Codex model supports it.
- Switching models/providers recomputes fast-mode active state without clearing the user's preference.
- `/status`, autocomplete/help, README, and bundled docs describe the feature accurately.
- `cargo fmt` and `cargo test --locked --all-targets` pass before implementation handoff.
@@ -0,0 +1,175 @@
# v0.3.4 Tool Output Context Reliability Implementation Plan
## Goal
v0.3.4 makes Cassady more reliable after broad tool output has been truncated, compacted, or superseded in the model context. The assistant should be able to tell when details are missing, understand which file range or command produced them, and quickly recover by using narrower reads or searches instead of stalling or making unsafe edits from incomplete context.
Success statement:
> After a large read or command output is compacted out of the request context, the assistant receives concise recovery guidance with enough provenance to inspect the exact missing area again before editing.
## Scope
### In scope
- Improve model-facing compaction notes for large tool outputs.
- Preserve useful provenance for compacted `read`, `grep`, and `shell` outputs.
- Add focused guidance that nudges the assistant toward smaller line ranges and search-first workflows.
- Keep existing provider message structure valid when tool outputs are compacted or earlier records are omitted.
- Align UI summaries, stored records, and model-facing transformed output so truncation/compaction is understandable without changing the full conversation history.
- Add regression tests for broad-output recovery and context-budget trimming.
- Update README and bundled docs where they describe context management, tool output limits, and recommended inspection workflows.
### Out of scope
- Implementing semantic summarization with an additional model call.
- Replacing Cassady's approximate token estimator with provider-specific tokenizers.
- Adding a full retrieval index over prior tool outputs or repository contents.
- Changing the JSONL conversation storage format in a way that makes existing chats unreadable.
- Changing UI collapsed-tool behavior except where labels or summaries need to expose truncation/compaction status.
- Automatically editing files based on compacted output without reinspection.
## Context or Current State
Relevant current behavior:
- `src/agent.rs` converts conversation records into provider messages, supersedes older repeated read outputs, compacts older tool outputs with `compact_tool_outputs`, and trims records with `trim_to_context_budget` and `trim_to_message_limit`.
- `compact_text` currently emits a generic head/tail note: `Cass compacted this tool output from ... chars to fit the model context`.
- `superseded_read_note` already preserves file path and line range when a later read covers an earlier read range.
- `src/tools/read.rs` returns headers like `--- path lines start-end ---`, followed by numbered lines. This is good provenance, but compaction can obscure the most useful middle section.
- `src/tools/grep.rs` already recommends narrowing when `max_matches` is reached.
- `src/tools/shell.rs` returns complete stdout/stderr/exit-code text to the agent loop; if the output is large, current compaction does not know the original command or suggest a narrower command.
- `src/ui/render.rs` has separate collapsed/full tool-output presentation. That display choice must remain UI-only and must not affect the stored record or model-facing context.
The main reliability gap is that once a broad output has been compacted, the assistant may see only a generic excerpt and lose the clue needed to make the next targeted tool call.
## Design Principles
1. **Never hide incompleteness.** If Cassady compacts or truncates output before sending it to the model, the transformed content must say so plainly.
2. **Recovery beats summarization.** Prefer actionable provenance and follow-up instructions over trying to summarize omitted content heuristically.
3. **Keep guidance compact.** The fix must not consume enough context to make context pressure worse.
4. **Preserve valid provider conversations.** Tool result messages must still match their assistant tool calls after compaction and trimming.
5. **Do not mutate history for UI convenience.** JSONL records should retain original tool outputs unless a future storage migration explicitly changes that contract.
## Design
### Model-facing compaction notes
Replace the generic `compact_text(content, target_chars)` path with a metadata-aware formatter, for example:
```rust
struct ToolOutputCompactionHint {
tool_name: Option<String>,
original_chars: usize,
retained_head_chars: usize,
retained_tail_chars: usize,
provenance: ToolOutputProvenance,
}
enum ToolOutputProvenance {
Read { sections: Vec<ReadOutputSection> },
Grep { stopped_after: Option<usize> },
Shell { command: Option<String> },
Unknown,
}
```
The first implementation can infer provenance from the tool result text and nearby conversation/tool-call data rather than changing stored record schemas.
Example compacted read result:
```text
[Cass compacted this read output from 48,212 chars to fit the model context. The omitted content came from src/app.rs lines 1-1820. Use read with a narrower line range, or grep for a symbol before reading, before relying on omitted details.]
--- retained head excerpt ---
...
--- omitted middle ---
--- retained tail excerpt ---
...
```
Example compacted shell result:
```text
[Cass compacted this shell output from 81,004 chars to fit the model context. Rerun a narrower command, pipe through grep/head/tail, or inspect the specific files named in the excerpt before making edits based on omitted lines.]
```
Keep notes deterministic and short; avoid per-line summaries of omitted content.
### Read-output provenance
Reuse and extend the existing `ReadOutputSection` parsing in `src/agent.rs`:
- Detect every `--- path lines start-end ---` section before compaction.
- Preserve observed line coverage from numbered lines when available.
- Include one compact range summary in compaction notes:
- Single section: `path lines 35-220`.
- Multiple sections: `3 read sections including path_a lines 1-120 and path_b lines 40-90`.
- When a later read supersedes an earlier range, continue using the current superseded-read note and ensure tests cover interaction with compaction.
### Grep and shell guidance
For `grep` output:
- Preserve existing `… stopped after N matches` text.
- If compacted, add a note suggesting a narrower query, smaller path scope, lower `max_matches`, or a focused `read` around matching lines.
For `shell` output:
- If the tool-call arguments are available in the message conversion path, include a sanitized command preview in the note when reasonably short.
- Suggest command narrowing patterns without prescribing platform-specific syntax unless the command itself is already shell-specific, e.g. `grep`, `head`, `tail`, or a more targeted subcommand.
- Do not rerun shell commands automatically.
### Prompt and tool descriptions
Update the base prompt and tool descriptions only enough to reinforce reliable behavior:
- Prefer `grep` before broad `read` when the target location is unknown.
- Read smaller line ranges when files are large or when previous output says it was compacted.
- Treat compacted/truncated output as incomplete evidence; reinspect before editing.
Avoid bloating `src/prompt.rs`; keep additions short and test expected key phrases rather than full prompt text.
### UI and storage alignment
- Stored JSONL should keep the original tool result content.
- Model-facing transformed messages may contain compacted/superseded notes.
- UI collapsed mode should keep using summaries, but summaries should not imply the model saw the full output when it did not.
- If practical, make collapsed tool summaries include a compact `compacted` or `truncated` marker only when the stored/result text itself says that Cassady truncated or stopped output.
## Implementation Steps
1. Inspect provider-message conversion in `src/agent.rs` and identify where tool-call names/arguments are still available when compacting tool results.
2. Refactor `compact_text` into metadata-aware helpers that can produce deterministic compaction notes for read, grep, shell, and unknown outputs.
3. Reuse existing read-section parsing to build concise read range summaries for compacted read outputs.
4. Add shell and grep-specific recovery guidance based on tool name and output markers.
5. Preserve the newest tool result behavior unless tests show that the newest result can still exceed practical context limits; if changed, document the tradeoff explicitly.
6. Update `src/tools/read.rs`, `src/tools/grep.rs`, and `src/prompt.rs` descriptions with concise search-first and narrow-range guidance.
7. Add or update UI summary helpers in `src/ui/render.rs` only if needed to expose stored truncation/compaction markers consistently.
8. Update README and bundled docs for context reliability, broad-output recovery, and recommended inspection workflow.
9. Run `cargo fmt` and `cargo test --locked --all-targets`.
## Tests
- Large read output compacts to a note that includes original size, path, line range, and a narrower-read/search suggestion.
- Multi-file read output compacts to a concise multi-section provenance summary.
- Superseded read output still produces the superseded note and does not lose provider-message validity after context trimming.
- Large grep output compaction preserves or adds narrowing guidance.
- Large shell output compaction suggests rerunning a narrower command and does not include unsafe automatic actions.
- Context-budget trimming does not leave orphaned tool results or assistant tool calls.
- Stored conversation records retain original tool output while model-facing messages can be compacted.
- Prompt/tool spec tests verify the presence of concise search-first and reinspection guidance.
## Documentation
- Update `README.md` where tool output/context behavior is described.
- Update `docs/workflows.md` with recommended search-first and narrow-read workflows.
- Update `docs/troubleshooting.md` with recovery steps for compacted or truncated output.
- Update `docs/glossary.md` if terms such as compacted output, superseded read, or model-facing context need clarification.
## Acceptance Criteria
- Compacted tool outputs include actionable provenance and recovery guidance.
- Broad read and command-output workflows have regression coverage demonstrating safe reinspection before edits.
- Existing conversations remain loadable and resumable.
- Provider message conversion remains valid for tool-call/tool-result pairs after compaction and trimming.
- `cargo fmt` and `cargo test --locked --all-targets` pass.
+28 -21
View File
@@ -2,8 +2,8 @@ use crate::access::AccessMode;
use crate::config::{Config, ReasoningEffort}; use crate::config::{Config, ReasoningEffort};
use crate::conversation::{now_ts, Conversation, Record, StoredToolCall}; use crate::conversation::{now_ts, Conversation, Record, StoredToolCall};
use crate::prompt; use crate::prompt;
use crate::providers::openai_compatible::{OpenAiCompatibleProvider, OpenAiCompatibleSettings};
use crate::providers::types::ModelMessage; use crate::providers::types::ModelMessage;
use crate::providers::{ProviderClient, ProviderRuntimeOptions};
use crate::security::PolicyDecision; use crate::security::PolicyDecision;
use crate::tools::{self, ToolContext, ToolRuntimeEvent}; use crate::tools::{self, ToolContext, ToolRuntimeEvent};
use anyhow::Result; use anyhow::Result;
@@ -85,34 +85,27 @@ pub async fn run_turn_with_commands(
ts: now_ts(), ts: now_ts(),
})?; })?;
let api_key = match settings.config.resolved_api_key() { let reasoning_effort = settings
Ok(api_key) => api_key, .reasoning_effort
.clamp_for_model(settings.config.model_metadata.as_ref());
let provider = match ProviderClient::from_config(
&settings.config,
ProviderRuntimeOptions {
reasoning_effort,
fast_mode: settings.config.fast_mode_state().active,
},
) {
Ok(provider) => provider,
Err(err) => { Err(err) => {
append_visible_assistant( append_visible_assistant(
&mut conversation, &mut conversation,
&tx, &tx,
format!("I couldn't start the turn because the API key is not available: {err}"), format!("I couldn't start the turn because provider authentication is not available: {err}"),
)?; )?;
let _ = tx.send(AgentEvent::TurnFinished); let _ = tx.send(AgentEvent::TurnFinished);
return Ok(conversation); return Ok(conversation);
} }
}; };
let reasoning_request_format = settings
.config
.model_metadata
.as_ref()
.map(|model| model.reasoning.request_format)
.unwrap_or_default();
let reasoning_effort = settings
.reasoning_effort
.clamp_for_model(settings.config.model_metadata.as_ref());
let provider = OpenAiCompatibleProvider::new(OpenAiCompatibleSettings {
model: settings.config.model.clone(),
base_url: settings.config.active_provider.base_url.clone(),
api_key,
reasoning_effort,
reasoning_request_format,
});
let docs_dir = settings.config.docs_dir(); let docs_dir = settings.config.docs_dir();
let tool_ctx = ToolContext { let tool_ctx = ToolContext {
@@ -304,10 +297,19 @@ pub async fn run_turn_with_commands(
let (runtime_tx, mut runtime_rx) = mpsc::unbounded_channel::<ToolRuntimeEvent>(); let (runtime_tx, mut runtime_rx) = mpsc::unbounded_channel::<ToolRuntimeEvent>();
let mut call_tool_ctx = tool_ctx.clone(); let mut call_tool_ctx = tool_ctx.clone();
call_tool_ctx.runtime_tx = Some(runtime_tx); call_tool_ctx.runtime_tx = Some(runtime_tx);
let file_edit_snapshot = crate::file_edits::begin_tool_edit(
&settings.config.root,
&conversation.id,
conversation.records.len(),
&call_id,
&call_name,
&call_arguments,
&call_tool_ctx,
);
let output = { let output = {
let execute = tools::execute_with_approval( let execute = tools::execute_with_approval(
&call_name, &call_name,
call_arguments, call_arguments.clone(),
&call_tool_ctx, &call_tool_ctx,
approved, approved,
); );
@@ -325,6 +327,11 @@ pub async fn run_turn_with_commands(
} }
output output
}; };
if output.ok {
if let Some(snapshot) = file_edit_snapshot {
let _ = crate::file_edits::finish_tool_edit(&settings.config.root, snapshot);
}
}
let _ = tx.send(AgentEvent::ToolResult { let _ = tx.send(AgentEvent::ToolResult {
id: call_id.clone(), id: call_id.clone(),
name: call_name.clone(), name: call_name.clone(),
+940 -17
View File
File diff suppressed because it is too large Load Diff
+435
View File
@@ -0,0 +1,435 @@
use crate::conversation::{self, BranchPoint, Conversation, Record, StoredToolCall};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::Path;
const TOOL_CANCELLED_MESSAGE: &str = "Tool execution cancelled by user.";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckpointKind {
User,
Assistant,
ToolCall,
ToolResult,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checkpoint {
pub id: String,
pub chat_id: String,
pub record_index: usize,
pub tool_call_id: Option<String>,
pub kind: CheckpointKind,
pub label: String,
pub detail: String,
pub ts: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchSummary {
pub id: String,
pub created_at: String,
pub parent_chat_id: Option<String>,
pub branch_label: Option<String>,
pub record_count: usize,
pub current: bool,
}
#[derive(Debug, Clone)]
pub struct BranchFamily {
pub branches: Vec<BranchSummary>,
pub checkpoints: Vec<Checkpoint>,
}
pub fn checkpoint_records(records: &[Record], chat_id: &str) -> Vec<Checkpoint> {
let mut checkpoints = Vec::new();
for (idx, record) in records.iter().enumerate() {
match record {
Record::User { content, ts } => checkpoints.push(Checkpoint {
id: format!("{chat_id}:{idx}:user"),
chat_id: chat_id.to_string(),
record_index: idx,
tool_call_id: None,
kind: CheckpointKind::User,
label: "user".into(),
detail: preview(content),
ts: Some(ts.clone()),
}),
Record::Assistant {
content,
reasoning,
tool_calls,
ts,
..
} => {
let detail = if content.trim().is_empty() {
preview(reasoning)
} else {
preview(content)
};
checkpoints.push(Checkpoint {
id: format!("{chat_id}:{idx}:assistant"),
chat_id: chat_id.to_string(),
record_index: idx,
tool_call_id: None,
kind: CheckpointKind::Assistant,
label: "assistant".into(),
detail,
ts: Some(ts.clone()),
});
for call in tool_calls {
checkpoints.push(Checkpoint {
id: format!("{chat_id}:{idx}:tool_call:{}", call.id),
chat_id: chat_id.to_string(),
record_index: idx,
tool_call_id: Some(call.id.clone()),
kind: CheckpointKind::ToolCall,
label: format!("tool call {}", call.name),
detail: tool_call_detail(call),
ts: Some(ts.clone()),
});
}
}
Record::Tool {
tool_call_id,
name,
ok,
content,
ts,
} => checkpoints.push(Checkpoint {
id: format!("{chat_id}:{idx}:tool_result:{tool_call_id}"),
chat_id: chat_id.to_string(),
record_index: idx,
tool_call_id: Some(tool_call_id.clone()),
kind: CheckpointKind::ToolResult,
label: format!("tool {name} {}", if *ok { "✓" } else { "✗" }),
detail: preview(content),
ts: Some(ts.clone()),
}),
_ => {}
}
}
checkpoints
}
pub fn load_family(conversations_dir: &Path, current: &Conversation) -> Result<BranchFamily> {
let metas = load_all_metas(conversations_dir)?;
let root = root_for(&current.id, &metas);
let mut ids = BTreeSet::new();
for id in metas.keys() {
if root_for(id, &metas) == root {
ids.insert(id.clone());
}
}
ids.insert(current.id.clone());
let mut branches = Vec::new();
let mut checkpoints = Vec::new();
for id in ids {
let Ok((conversation, _)) = Conversation::load(conversations_dir, &id) else {
continue;
};
let meta = conversation.meta();
branches.push(BranchSummary {
id: conversation.id.clone(),
created_at: meta
.as_ref()
.map(|m| m.created_at.clone())
.unwrap_or_default(),
parent_chat_id: meta.as_ref().and_then(|m| m.parent_chat_id.clone()),
branch_label: meta
.as_ref()
.and_then(|m| m.branch_from.as_ref().map(|p| p.checkpoint_label.clone())),
record_count: conversation.records.len(),
current: conversation.id == current.id,
});
checkpoints.extend(checkpoint_records(&conversation.records, &conversation.id));
}
branches.sort_by(|a, b| b.created_at.cmp(&a.created_at));
checkpoints.sort_by(|a, b| {
a.chat_id
.cmp(&b.chat_id)
.then(a.record_index.cmp(&b.record_index))
.then(a.id.cmp(&b.id))
});
Ok(BranchFamily {
branches,
checkpoints,
})
}
pub fn create_branch(
conversations_dir: &Path,
source: &Conversation,
checkpoint: &Checkpoint,
) -> Result<Conversation> {
if source.id != checkpoint.chat_id {
bail!(
"checkpoint {} belongs to {}, not {}",
checkpoint.id,
checkpoint.chat_id,
source.id
);
}
if checkpoint.record_index >= source.records.len() {
bail!("checkpoint record index is out of range");
}
fs::create_dir_all(conversations_dir)?;
let id = conversation::new_chat_id();
let path = conversations_dir.join(format!("{id}.jsonl"));
let mut records = Vec::new();
let meta = source
.meta()
.context("source conversation is missing metadata")?;
records.push(Record::Meta {
chat_id: id.clone(),
created_at: conversation::now_ts(),
model: meta.model,
cwd: meta.cwd,
parent_chat_id: Some(source.id.clone()),
branch_from: Some(BranchPoint {
chat_id: source.id.clone(),
record_index: checkpoint.record_index,
tool_call_id: checkpoint.tool_call_id.clone(),
checkpoint_label: checkpoint_title(checkpoint),
}),
});
let prefix = valid_prefix(source, checkpoint)?;
records.extend(prefix);
repair_pending_tool_calls(&mut records);
let mut file = OpenOptions::new()
.create_new(true)
.write(true)
.open(&path)
.with_context(|| format!("creating branch conversation {}", path.display()))?;
for record in &records {
writeln!(file, "{}", serde_json::to_string(record)?)?;
}
file.flush()?;
Ok(Conversation { id, path, records })
}
fn valid_prefix(source: &Conversation, checkpoint: &Checkpoint) -> Result<Vec<Record>> {
let mut end = checkpoint.record_index + 1;
if matches!(checkpoint.kind, CheckpointKind::ToolCall) {
end = checkpoint.record_index + 1;
}
let mut prefix = source.records[..end].to_vec();
// Drop the source meta; the branch writes its own meta record.
if matches!(prefix.first(), Some(Record::Meta { .. })) {
prefix.remove(0);
}
// For a tool-call checkpoint, keep the assistant turn but do not copy any
// later tool result. The repair step below writes cancelled tool results so
// the next provider request remains valid.
Ok(prefix)
}
pub fn repair_pending_tool_calls(records: &mut Vec<Record>) {
let mut pending: Vec<(String, String)> = Vec::new();
for record in records.iter() {
match record {
Record::Assistant { tool_calls, .. } => {
pending = tool_calls
.iter()
.map(|call| (call.id.clone(), call.name.clone()))
.collect();
}
Record::Tool { tool_call_id, .. } => pending.retain(|(id, _)| id != tool_call_id),
Record::User { .. } => pending.clear(),
_ => {}
}
}
let seen: HashSet<String> = records
.iter()
.filter_map(|record| match record {
Record::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
_ => None,
})
.collect();
for (id, name) in pending {
if seen.contains(&id) {
continue;
}
records.push(Record::Tool {
tool_call_id: id,
name,
ok: false,
content: TOOL_CANCELLED_MESSAGE.to_string(),
ts: conversation::now_ts(),
});
}
}
fn load_all_metas(conversations_dir: &Path) -> Result<BTreeMap<String, (Option<String>, String)>> {
let mut out = BTreeMap::new();
if !conversations_dir.exists() {
return Ok(out);
}
for entry in fs::read_dir(conversations_dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("jsonl") {
continue;
}
let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if let Ok(Some((parent, cwd))) = read_meta_parent_cwd(&path) {
out.insert(id.to_string(), (parent, cwd));
}
}
Ok(out)
}
fn read_meta_parent_cwd(path: &Path) -> Result<Option<(Option<String>, String)>> {
let file = File::open(path)?;
for line in BufReader::new(file).lines().take(10) {
let line = line?;
if line.trim().is_empty() {
continue;
}
let record: Record = serde_json::from_str(&line)?;
if let Record::Meta {
parent_chat_id,
cwd,
..
} = record
{
return Ok(Some((parent_chat_id, cwd)));
}
}
Ok(None)
}
fn root_for(id: &str, metas: &BTreeMap<String, (Option<String>, String)>) -> String {
let mut current = id.to_string();
let mut seen = HashSet::new();
while seen.insert(current.clone()) {
let Some((Some(parent), _)) = metas.get(&current) else {
break;
};
current = parent.clone();
}
current
}
pub fn checkpoint_title(checkpoint: &Checkpoint) -> String {
if checkpoint.detail.is_empty() {
checkpoint.label.clone()
} else {
format!("{}: {}", checkpoint.label, checkpoint.detail)
}
}
fn tool_call_detail(call: &StoredToolCall) -> String {
let mut detail = String::new();
if let Some(path) = call.arguments.get("path").and_then(|v| v.as_str()) {
detail = format!("file: {path}");
} else if let Some(command) = call.arguments.get("command").and_then(|v| v.as_str()) {
detail = command.to_string();
}
if detail.is_empty() {
preview(&call.arguments.to_string())
} else {
preview(&detail)
}
}
fn preview(content: &str) -> String {
content
.lines()
.find(|line| !line.trim().is_empty())
.unwrap_or("")
.chars()
.take(96)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use tempfile::tempdir;
fn base_records(id: &str) -> Vec<Record> {
vec![
Record::Meta {
chat_id: id.into(),
created_at: "now".into(),
model: "m".into(),
cwd: "/tmp".into(),
parent_chat_id: None,
branch_from: None,
},
Record::System {
content: "s".into(),
},
Record::User {
content: "u".into(),
ts: "t".into(),
},
Record::Assistant {
content: "a".into(),
reasoning: String::new(),
reasoning_field: None,
tool_calls: vec![StoredToolCall {
id: "call1".into(),
name: "read".into(),
arguments: json!({"path":"x"}),
}],
ts: "t".into(),
},
]
}
#[test]
fn checkpoints_include_tool_calls() {
let checkpoints = checkpoint_records(&base_records("c"), "c");
assert!(checkpoints.iter().any(|c| c.kind == CheckpointKind::User));
assert!(checkpoints
.iter()
.any(|c| c.kind == CheckpointKind::Assistant));
assert!(checkpoints
.iter()
.any(|c| c.kind == CheckpointKind::ToolCall));
}
#[test]
fn create_branch_does_not_modify_source_and_repairs_pending_tools() {
let dir = tempdir().unwrap();
let source = Conversation {
id: "source".into(),
path: dir.path().join("source.jsonl"),
records: base_records("source"),
};
let checkpoint = checkpoint_records(&source.records, &source.id)
.into_iter()
.find(|c| c.kind == CheckpointKind::Assistant)
.unwrap();
let branch = create_branch(dir.path(), &source, &checkpoint).unwrap();
assert_ne!(branch.id, source.id);
assert!(
source
.records
.iter()
.filter(|r| matches!(r, Record::Tool { .. }))
.count()
== 0
);
assert!(branch
.records
.iter()
.any(|r| matches!(r, Record::Tool { ok: false, .. })));
}
}
+65 -4
View File
@@ -1,5 +1,9 @@
use crate::cli::Cli; use crate::cli::Cli;
use crate::config::{self, ApiKeyReference, Config, ModelsFile, ProvidersFile}; use crate::codex_auth;
use crate::config::{
self, ApiKeyReference, Config, ModelsFile, ProvidersFile, CHATGPT_CODEX_PROVIDER_KIND,
DEFAULT_PROVIDER_KIND,
};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -72,6 +76,9 @@ impl CheckReport {
"cass".into(), "cass".into(),
]; ];
} }
if error.contains("Codex auth") {
return vec!["codex login".into(), "cass check".into(), "cass".into()];
}
} }
vec!["cass setup".into()] vec!["cass setup".into()]
} }
@@ -191,29 +198,83 @@ fn check_active_config(report: &mut CheckReport, cfg: &Config, providers: &Provi
report report
.successes .successes
.push(format!("active provider: {}", cfg.provider_id)); .push(format!("active provider: {}", cfg.provider_id));
let endpoint_label = if cfg.active_provider.kind == CHATGPT_CODEX_PROVIDER_KIND {
"active provider endpoint"
} else {
"active provider base URL"
};
report.successes.push(format!( report.successes.push(format!(
"active provider base URL: {}", "{endpoint_label}: {}",
cfg.active_provider.base_url cfg.active_provider.base_url
)); ));
report report
.successes .successes
.push(format!("active model: {}", cfg.model)); .push(format!("active model: {}", cfg.model));
check_api_key(report, "api key", &cfg.active_provider.api_key, true); check_provider_auth(
report,
"api key",
&cfg.active_provider.kind,
&cfg.active_provider.api_key,
true,
);
for provider in &providers.providers { for provider in &providers.providers {
if provider.id == cfg.provider_id { if provider.id == cfg.provider_id {
continue; continue;
} }
check_api_key( check_provider_auth(
report, report,
&format!("provider `{}` api key", provider.id), &format!("provider `{}` api key", provider.id),
&provider.kind,
&provider.api_key, &provider.api_key,
false, false,
); );
} }
} }
fn check_provider_auth(
report: &mut CheckReport,
label: &str,
kind: &str,
api_key: &str,
active: bool,
) {
match kind {
DEFAULT_PROVIDER_KIND => check_api_key(report, label, api_key, active),
CHATGPT_CODEX_PROVIDER_KIND => check_codex_auth(report, active),
_ if active => report
.errors
.push(format!("provider kind `{kind}` is unsupported")),
_ => report
.warnings
.push(format!("provider kind `{kind}` is unsupported")),
}
}
fn check_codex_auth(report: &mut CheckReport, active: bool) {
let status = codex_auth::check_codex_auth();
if status.is_usable() {
if active {
report
.successes
.push(format!("Codex auth: {}", status.summary()));
}
} else if active {
report.errors.push(format!(
"Codex auth: {}. {}",
status.summary(),
status.recovery_hint()
));
} else {
report.warnings.push(format!(
"Codex auth: {}. {}",
status.summary(),
status.recovery_hint()
));
}
}
fn check_api_key(report: &mut CheckReport, label: &str, spec: &str, active: bool) { fn check_api_key(report: &mut CheckReport, label: &str, spec: &str, active: bool) {
match config::api_key_reference(spec) { match config::api_key_reference(spec) {
Ok(ApiKeyReference::Env(name)) => match std::env::var(&name) { Ok(ApiKeyReference::Env(name)) => match std::env::var(&name) {
+34 -1
View File
@@ -1,4 +1,4 @@
use clap::{Parser, Subcommand}; use clap::{Args, Parser, Subcommand};
use std::path::PathBuf; use std::path::PathBuf;
#[derive(Debug, Parser, Clone)] #[derive(Debug, Parser, Clone)]
@@ -44,8 +44,41 @@ pub struct Cli {
pub enum Command { pub enum Command {
/// Validate Cass config files. /// Validate Cass config files.
Check, Check,
/// Configure or update OpenAI-compatible provider login settings.
Login,
/// Remove saved providers and their models.
Logout,
/// Configure an OpenAI-compatible provider and first model. /// Configure an OpenAI-compatible provider and first model.
Setup, Setup,
/// Update Cassady from official GitHub releases.
Update(UpdateArgs),
}
#[derive(Debug, Args, Clone, PartialEq, Eq)]
pub struct UpdateArgs {
/// Check the latest release without installing.
#[arg(long)]
pub check: bool,
/// Show what would be updated without downloading or installing.
#[arg(long)]
pub dry_run: bool,
/// Accept default prompts for non-interactive use.
#[arg(long, short = 'y')]
pub yes: bool,
/// Require a matching prebuilt archive and do not fall back to source.
#[arg(long, conflicts_with = "source")]
pub prebuilt: bool,
/// Build from release source even when a prebuilt archive exists.
#[arg(long, conflicts_with = "prebuilt")]
pub source: bool,
/// Install a specific release tag, such as v0.2.7.
#[arg(long, value_name = "TAG")]
pub to: Option<String>,
} }
pub fn parse() -> Cli { pub fn parse() -> Cli {
+311
View File
@@ -0,0 +1,311 @@
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use serde_json::Value;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone)]
pub struct CodexAccessToken {
value: String,
}
impl CodexAccessToken {
pub fn new(value: String) -> Result<Self> {
if value.trim().is_empty() {
bail!("Codex access token is empty");
}
Ok(Self { value })
}
pub fn as_secret(&self) -> &str {
&self.value
}
pub fn redacted(&self) -> &'static str {
"<Codex access token>"
}
}
impl std::fmt::Display for CodexAccessToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.redacted())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodexAuthStatus {
pub path: PathBuf,
pub auth_mode: Option<String>,
pub has_access_token: bool,
pub expires_at: Option<i64>,
pub expired: bool,
pub error: Option<String>,
}
impl CodexAuthStatus {
pub fn is_usable(&self) -> bool {
self.error.is_none() && self.has_access_token && !self.expired
}
pub fn recovery_hint(&self) -> &'static str {
"Run `codex login` or sign in with the Codex app, then rerun `cass check`."
}
pub fn summary(&self) -> String {
if self.is_usable() {
if let Some(auth_mode) = &self.auth_mode {
format!(
"{} contains an access token (auth mode: {auth_mode})",
pretty_path(&self.path)
)
} else {
format!("{} contains an access token", pretty_path(&self.path))
}
} else if let Some(error) = &self.error {
format!("{}: {error}", pretty_path(&self.path))
} else if self.expired {
format!(
"{} contains an expired access token",
pretty_path(&self.path)
)
} else {
format!(
"{} does not contain an access token",
pretty_path(&self.path)
)
}
}
}
#[derive(Debug, Deserialize)]
struct CodexAuthFile {
auth_mode: Option<String>,
tokens: Option<CodexTokens>,
}
#[derive(Debug, Deserialize)]
struct CodexTokens {
access_token: Option<String>,
}
pub fn codex_home() -> PathBuf {
std::env::var_os("CODEX_HOME")
.map(PathBuf::from)
.or_else(|| dirs::home_dir().map(|home| home.join(".codex")))
.unwrap_or_else(|| PathBuf::from(".codex"))
}
pub fn codex_auth_path() -> PathBuf {
std::env::var_os("CODEX_AUTH_FILE")
.map(PathBuf::from)
.unwrap_or_else(|| codex_home().join("auth.json"))
}
pub fn codex_config_path() -> PathBuf {
std::env::var_os("CODEX_CONFIG_FILE")
.map(PathBuf::from)
.unwrap_or_else(|| codex_home().join("config.toml"))
}
pub fn load_codex_access_token() -> Result<CodexAccessToken> {
load_codex_access_token_from_path(&codex_auth_path())
}
pub fn load_codex_access_token_from_path(path: &Path) -> Result<CodexAccessToken> {
let text = fs::read_to_string(path).with_context(|| {
format!(
"Codex auth not found at {}; run `codex login` or sign in with the Codex app",
pretty_path(path)
)
})?;
let parsed: CodexAuthFile = serde_json::from_str(&text)
.with_context(|| format!("parsing Codex auth at {}", pretty_path(path)))?;
let token = parsed
.tokens
.and_then(|tokens| tokens.access_token)
.filter(|token| !token.trim().is_empty())
.with_context(|| {
format!(
"no access token found in {}; run `codex login` or sign in with the Codex app",
pretty_path(path)
)
})?;
if jwt_is_expired(&token) == Some(true) {
bail!(
"Codex access token in {} is expired; run `codex login` or sign in with the Codex app",
pretty_path(path)
);
}
CodexAccessToken::new(token)
}
pub fn check_codex_auth() -> CodexAuthStatus {
check_codex_auth_at(&codex_auth_path())
}
pub fn check_codex_auth_at(path: &Path) -> CodexAuthStatus {
let mut status = CodexAuthStatus {
path: path.to_path_buf(),
auth_mode: None,
has_access_token: false,
expires_at: None,
expired: false,
error: None,
};
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(err) => {
status.error = Some(format!("not readable ({err})"));
return status;
}
};
let parsed: CodexAuthFile = match serde_json::from_str(&text) {
Ok(parsed) => parsed,
Err(err) => {
status.error = Some(format!("invalid JSON ({err})"));
return status;
}
};
status.auth_mode = parsed.auth_mode;
let token = parsed
.tokens
.and_then(|tokens| tokens.access_token)
.filter(|token| !token.trim().is_empty());
if let Some(token) = token {
status.has_access_token = true;
status.expires_at = jwt_expiration(&token);
status.expired = jwt_is_expired(&token).unwrap_or(false);
}
status
}
pub fn read_codex_default_model() -> Option<String> {
read_codex_default_model_from_path(&codex_config_path())
}
pub fn read_codex_default_model_from_path(path: &Path) -> Option<String> {
let text = fs::read_to_string(path).ok()?;
for line in text.lines() {
let line = line.trim();
if line.starts_with('#') || !line.starts_with("model") {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
if key.trim() != "model" {
continue;
}
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
.unwrap_or(value)
.trim();
if !value.is_empty() {
return Some(value.to_string());
}
}
None
}
fn jwt_is_expired(token: &str) -> Option<bool> {
let exp = jwt_expiration(token)?;
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() as i64;
Some(exp <= now)
}
fn jwt_expiration(token: &str) -> Option<i64> {
let mut parts = token.split('.');
let _header = parts.next()?;
let payload = parts.next()?;
let bytes = base64_url_decode(payload).ok()?;
let json: Value = serde_json::from_slice(&bytes).ok()?;
json.get("exp")?.as_i64()
}
fn base64_url_decode(input: &str) -> Result<Vec<u8>, String> {
let mut bits = 0u32;
let mut bit_count = 0u8;
let mut out = Vec::new();
for byte in input.bytes() {
let value = match byte {
b'A'..=b'Z' => byte - b'A',
b'a'..=b'z' => byte - b'a' + 26,
b'0'..=b'9' => byte - b'0' + 52,
b'-' | b'+' => 62,
b'_' | b'/' => 63,
b'=' => break,
_ => return Err("invalid base64 character".into()),
} as u32;
bits = (bits << 6) | value;
bit_count += 6;
if bit_count >= 8 {
bit_count -= 8;
out.push(((bits >> bit_count) & 0xff) as u8);
}
}
Ok(out)
}
pub fn pretty_path(path: &Path) -> String {
if let Some(home) = dirs::home_dir() {
if let Ok(rest) = path.strip_prefix(&home) {
return format!("~/{}", rest.display());
}
}
path.display().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn reads_access_token_without_displaying_it() {
let dir = tempdir().unwrap();
let path = dir.path().join("auth.json");
fs::write(
&path,
r#"{"auth_mode":"chatgpt","tokens":{"access_token":"secret-token"}}"#,
)
.unwrap();
let token = load_codex_access_token_from_path(&path).unwrap();
assert_eq!(token.as_secret(), "secret-token");
assert_eq!(token.to_string(), "<Codex access token>");
}
#[test]
fn check_reports_missing_token_without_secret_fields() {
let dir = tempdir().unwrap();
let path = dir.path().join("auth.json");
fs::write(
&path,
r#"{"tokens":{"refresh_token":"refresh-secret","account_id":"acct"}}"#,
)
.unwrap();
let status = check_codex_auth_at(&path);
assert!(!status.is_usable());
let summary = status.summary();
assert!(!summary.contains("refresh-secret"));
assert!(!summary.contains("acct"));
}
#[test]
fn reads_model_from_codex_config() {
let dir = tempdir().unwrap();
let path = dir.path().join("config.toml");
fs::write(&path, "model = \"gpt-test\"\n").unwrap();
assert_eq!(
read_codex_default_model_from_path(&path).as_deref(),
Some("gpt-test")
);
}
}
+174 -25
View File
@@ -9,6 +9,11 @@ use std::path::{Path, PathBuf};
pub const DEFAULT_PROVIDER_ID: &str = "fireworks"; pub const DEFAULT_PROVIDER_ID: &str = "fireworks";
pub const DEFAULT_PROVIDER_NAME: &str = "Fireworks"; pub const DEFAULT_PROVIDER_NAME: &str = "Fireworks";
pub const DEFAULT_PROVIDER_KIND: &str = "openai-compatible"; pub const DEFAULT_PROVIDER_KIND: &str = "openai-compatible";
pub const CHATGPT_CODEX_PROVIDER_ID: &str = "chatgpt-codex";
pub const CHATGPT_CODEX_PROVIDER_NAME: &str = "ChatGPT Codex";
pub const CHATGPT_CODEX_PROVIDER_KIND: &str = "chatgpt-codex";
pub const CHATGPT_CODEX_RESPONSES_URL: &str = "https://chatgpt.com/backend-api/codex/responses";
pub const CHATGPT_CODEX_DEFAULT_MODEL: &str = "gpt-5.5";
pub const DEFAULT_MODEL: &str = "accounts/fireworks/models/qwen3p7-plus"; pub const DEFAULT_MODEL: &str = "accounts/fireworks/models/qwen3p7-plus";
pub const DEFAULT_BASE_URL: &str = "https://api.fireworks.ai/inference/v1"; pub const DEFAULT_BASE_URL: &str = "https://api.fireworks.ai/inference/v1";
pub const DEFAULT_API_KEY_ENV: &str = "FIREWORKS_API_KEY"; pub const DEFAULT_API_KEY_ENV: &str = "FIREWORKS_API_KEY";
@@ -22,6 +27,8 @@ pub struct ConfigFile {
pub default_model: Option<String>, pub default_model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub default_reasoning_effort: Option<ReasoningEffort>, pub default_reasoning_effort: Option<ReasoningEffort>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_fast_mode: Option<bool>,
// Deprecated compatibility fields accepted from older config.json files. // Deprecated compatibility fields accepted from older config.json files.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -61,6 +68,7 @@ pub struct ProviderDefinition {
pub name: Option<String>, pub name: Option<String>,
pub kind: String, pub kind: String,
pub base_url: String, pub base_url: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub api_key: String, pub api_key: String,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub default_model: Option<String>, pub default_model: Option<String>,
@@ -91,6 +99,8 @@ pub struct ModelDefinition {
pub supports_streaming: bool, pub supports_streaming: bool,
#[serde(default)] #[serde(default)]
pub reasoning: ReasoningMetadata, pub reasoning: ReasoningMetadata,
#[serde(default)]
pub fast_mode: FastModeMetadata,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -106,6 +116,13 @@ pub struct ReasoningMetadata {
pub request_format: ReasoningRequestFormat, pub request_format: ReasoningRequestFormat,
} }
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FastModeMetadata {
#[serde(default)]
pub supported: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum ReasoningEffort { pub enum ReasoningEffort {
@@ -128,7 +145,7 @@ pub struct ResolvedProviderConfig {
pub name: Option<String>, pub name: Option<String>,
pub kind: String, pub kind: String,
pub base_url: String, pub base_url: String,
/// Either a literal API key or an env-var reference like "$FIREWORKS_API_KEY". /// Either a literal API key, an env-var reference like "$FIREWORKS_API_KEY", or empty for provider kinds that use external local auth.
pub api_key: String, pub api_key: String,
pub default_model: Option<String>, pub default_model: Option<String>,
pub models: Vec<String>, pub models: Vec<String>,
@@ -139,6 +156,7 @@ pub struct Config {
pub provider_id: String, pub provider_id: String,
pub model: String, pub model: String,
pub reasoning_effort: ReasoningEffort, pub reasoning_effort: ReasoningEffort,
pub default_fast_mode: bool,
pub active_provider: ResolvedProviderConfig, pub active_provider: ResolvedProviderConfig,
pub model_metadata: Option<ModelDefinition>, pub model_metadata: Option<ModelDefinition>,
pub default_access_mode: AccessMode, pub default_access_mode: AccessMode,
@@ -151,6 +169,42 @@ pub struct Config {
pub docs_dir: PathBuf, pub docs_dir: PathBuf,
} }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FastModeState {
pub preferred: bool,
pub supported: bool,
pub active: bool,
pub unavailable_reason: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct ConfigOverrides {
pub model: Option<String>,
pub base_url: Option<String>,
pub api_key_env: Option<String>,
pub access_mode: Option<AccessMode>,
}
impl ConfigOverrides {
pub fn from_cli(cli: &Cli) -> Self {
let access_mode = if cli.readonly {
Some(AccessMode::ReadOnly)
} else if cli.workspace_edit {
Some(AccessMode::WorkspaceEdit)
} else if cli.full_access {
Some(AccessMode::FullAccess)
} else {
None
};
Self {
model: cli.model.clone(),
base_url: cli.base_url.clone(),
api_key_env: cli.api_key_env.clone(),
access_mode,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApiKeyReference { pub enum ApiKeyReference {
Env(String), Env(String),
@@ -168,6 +222,12 @@ impl Default for ReasoningMetadata {
} }
} }
impl Default for FastModeMetadata {
fn default() -> Self {
Self { supported: false }
}
}
impl Default for ReasoningRequestFormat { impl Default for ReasoningRequestFormat {
fn default() -> Self { fn default() -> Self {
Self::ReasoningEffort Self::ReasoningEffort
@@ -253,6 +313,7 @@ impl Default for Config {
provider_id: DEFAULT_PROVIDER_ID.to_string(), provider_id: DEFAULT_PROVIDER_ID.to_string(),
model: DEFAULT_MODEL.to_string(), model: DEFAULT_MODEL.to_string(),
reasoning_effort: ReasoningEffort::Medium, reasoning_effort: ReasoningEffort::Medium,
default_fast_mode: false,
active_provider, active_provider,
model_metadata: Some(default_model_definition()), model_metadata: Some(default_model_definition()),
default_access_mode: AccessMode::ReadOnly, default_access_mode: AccessMode::ReadOnly,
@@ -287,17 +348,29 @@ pub fn models_path(root: &Path) -> PathBuf {
impl Config { impl Config {
pub fn load(cli: &Cli) -> Result<Self> { pub fn load(cli: &Cli) -> Result<Self> {
Self::load_from_root(cass_root(), cli) Self::load_with_overrides(cass_root(), ConfigOverrides::from_cli(cli))
} }
pub fn load_from_root(root: PathBuf, cli: &Cli) -> Result<Self> { pub fn load_with_overrides(root: PathBuf, overrides: ConfigOverrides) -> Result<Self> {
fs::create_dir_all(root.join("conversations")) fs::create_dir_all(root.join("conversations"))
.with_context(|| format!("creating {}", root.join("conversations").display()))?; .with_context(|| format!("creating {}", root.join("conversations").display()))?;
let docs_dir = crate::docs::install(&root)?; let docs_dir = crate::docs::install(&root)?;
Self::load_from_root_with_docs(root, docs_dir, cli) Self::load_from_root_with_docs_and_overrides(root, docs_dir, overrides)
}
pub fn load_from_root(root: PathBuf, cli: &Cli) -> Result<Self> {
Self::load_with_overrides(root, ConfigOverrides::from_cli(cli))
} }
pub fn load_from_root_with_docs(root: PathBuf, docs_dir: PathBuf, cli: &Cli) -> Result<Self> { pub fn load_from_root_with_docs(root: PathBuf, docs_dir: PathBuf, cli: &Cli) -> Result<Self> {
Self::load_from_root_with_docs_and_overrides(root, docs_dir, ConfigOverrides::from_cli(cli))
}
pub fn load_from_root_with_docs_and_overrides(
root: PathBuf,
docs_dir: PathBuf,
overrides: ConfigOverrides,
) -> Result<Self> {
fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?;
let providers = load_or_create_default_provider_registry(&root)?; let providers = load_or_create_default_provider_registry(&root)?;
let models = load_or_create_default_model_registry(&root)?; let models = load_or_create_default_model_registry(&root)?;
@@ -328,21 +401,18 @@ impl Config {
if let Some(v) = file.confirm_destructive_operations { if let Some(v) = file.confirm_destructive_operations {
cfg.confirm_destructive_operations = v; cfg.confirm_destructive_operations = v;
} }
if let Some(v) = file.default_fast_mode {
cfg.default_fast_mode = v;
}
} }
if cli.readonly { if let Some(access_mode) = overrides.access_mode {
cfg.default_access_mode = AccessMode::ReadOnly; cfg.default_access_mode = access_mode;
}
if cli.workspace_edit {
cfg.default_access_mode = AccessMode::WorkspaceEdit;
}
if cli.full_access {
cfg.default_access_mode = AccessMode::FullAccess;
} }
let requested_model = requested_model(file.as_ref(), cli); let requested_model = requested_model(file.as_ref(), &overrides);
let provider_id_from_config = requested_provider_id(file.as_ref(), &providers); let provider_id_from_config = requested_provider_id(file.as_ref(), &providers);
let legacy = legacy_provider_override(file.as_ref(), cli); let legacy = legacy_provider_override(file.as_ref(), &overrides);
let mut provider = resolve_provider( let mut provider = resolve_provider(
requested_model.as_deref().unwrap_or(DEFAULT_MODEL), requested_model.as_deref().unwrap_or(DEFAULT_MODEL),
@@ -353,10 +423,10 @@ impl Config {
&models, &models,
)?; )?;
if let Some(base_url) = &cli.base_url { if let Some(base_url) = &overrides.base_url {
provider.base_url = base_url.clone(); provider.base_url = base_url.clone();
} }
if let Some(api_key_env) = &cli.api_key_env { if let Some(api_key_env) = &overrides.api_key_env {
provider.api_key = format!("${api_key_env}"); provider.api_key = format!("${api_key_env}");
} }
@@ -395,6 +465,49 @@ impl Config {
pub fn resolved_api_key(&self) -> Result<String> { pub fn resolved_api_key(&self) -> Result<String> {
resolve_api_key(&self.active_provider.api_key) resolve_api_key(&self.active_provider.api_key)
} }
pub fn ensure_provider_auth(&self) -> Result<()> {
match self.active_provider.kind.as_str() {
DEFAULT_PROVIDER_KIND => self.resolved_api_key().map(|_| ()),
CHATGPT_CODEX_PROVIDER_KIND => crate::codex_auth::load_codex_access_token().map(|_| ()),
kind => bail!("unsupported provider kind `{kind}`"),
}
}
pub fn fast_mode_state(&self) -> FastModeState {
let preferred = self.default_fast_mode;
let supported = self.fast_mode_supported();
let active = preferred && supported;
let unavailable_reason = if preferred && !supported {
Some(self.fast_mode_unavailable_reason())
} else {
None
};
FastModeState {
preferred,
supported,
active,
unavailable_reason,
}
}
fn fast_mode_supported(&self) -> bool {
if self.active_provider.kind == CHATGPT_CODEX_PROVIDER_KIND {
return true;
}
self.model_metadata
.as_ref()
.is_some_and(|model| model.fast_mode.supported)
}
fn fast_mode_unavailable_reason(&self) -> String {
if self.active_provider.kind != CHATGPT_CODEX_PROVIDER_KIND {
format!("provider {}", self.provider_id)
} else {
format!("model {}", self.model)
}
}
} }
impl ProviderDefinition { impl ProviderDefinition {
@@ -435,6 +548,28 @@ pub fn save_last_used(root: &Path, model: &str, reasoning_effort: ReasoningEffor
file.default_reasoning_effort = Some(reasoning_effort); file.default_reasoning_effort = Some(reasoning_effort);
write_json_pretty(&path, &file) write_json_pretty(&path, &file)
} }
pub fn save_last_used_provider(
root: &Path,
provider_id: &str,
model: &str,
reasoning_effort: ReasoningEffort,
) -> Result<()> {
let path = config_path(root);
let mut file = load_config_file(root)?.unwrap_or_default();
file.default_provider = Some(provider_id.to_string());
file.default_model = Some(model.to_string());
file.default_reasoning_effort = Some(reasoning_effort);
write_json_pretty(&path, &file)
}
pub fn save_fast_mode_preference(root: &Path, enabled: bool) -> Result<()> {
let path = config_path(root);
let mut file = load_config_file(root)?.unwrap_or_default();
file.default_fast_mode = Some(enabled);
write_json_pretty(&path, &file)
}
pub fn load_or_create_default_provider_registry(root: &Path) -> Result<ProvidersFile> { pub fn load_or_create_default_provider_registry(root: &Path) -> Result<ProvidersFile> {
fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?; fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
let path = providers_path(root); let path = providers_path(root);
@@ -485,6 +620,7 @@ pub fn default_model_definition() -> ModelDefinition {
supports_tools: true, supports_tools: true,
supports_streaming: true, supports_streaming: true,
reasoning: ReasoningMetadata::default(), reasoning: ReasoningMetadata::default(),
fast_mode: FastModeMetadata::default(),
} }
} }
@@ -501,6 +637,10 @@ pub fn api_key_reference(spec: &str) -> Result<ApiKeyReference> {
Ok(ApiKeyReference::Literal) Ok(ApiKeyReference::Literal)
} }
pub fn is_supported_provider_kind(kind: &str) -> bool {
matches!(kind, DEFAULT_PROVIDER_KIND | CHATGPT_CODEX_PROVIDER_KIND)
}
pub fn resolve_api_key(spec: &str) -> Result<String> { pub fn resolve_api_key(spec: &str) -> Result<String> {
match api_key_reference(spec)? { match api_key_reference(spec)? {
ApiKeyReference::Env(name) => { ApiKeyReference::Env(name) => {
@@ -542,7 +682,7 @@ pub fn validate_registries(
"providers.json: provider `{}` kind must not be empty", "providers.json: provider `{}` kind must not be empty",
provider.id provider.id
)); ));
} else if provider.kind != DEFAULT_PROVIDER_KIND { } else if !is_supported_provider_kind(&provider.kind) {
out.errors.push(format!( out.errors.push(format!(
"providers.json: provider `{}` uses unsupported kind `{}`", "providers.json: provider `{}` uses unsupported kind `{}`",
provider.id, provider.kind provider.id, provider.kind
@@ -559,9 +699,18 @@ pub fn validate_registries(
provider.id provider.id
)); ));
} }
if let Err(err) = api_key_reference(&provider.api_key) { if provider.kind == DEFAULT_PROVIDER_KIND {
out.errors.push(format!( if let Err(err) = api_key_reference(&provider.api_key) {
"providers.json: provider `{}` has invalid api_key: {err}", out.errors.push(format!(
"providers.json: provider `{}` has invalid api_key: {err}",
provider.id
));
}
} else if provider.kind == CHATGPT_CODEX_PROVIDER_KIND
&& !provider.api_key.trim().is_empty()
{
out.warnings.push(format!(
"providers.json: provider `{}` ignores api_key because ChatGPT Codex uses local Codex auth",
provider.id provider.id
)); ));
} }
@@ -706,8 +855,8 @@ pub fn find_model_for_provider<'a>(
.find(|m| m.provider == provider_id && m.id == model_id) .find(|m| m.provider == provider_id && m.id == model_id)
} }
fn requested_model(file: Option<&ConfigFile>, cli: &Cli) -> Option<String> { fn requested_model(file: Option<&ConfigFile>, overrides: &ConfigOverrides) -> Option<String> {
cli.model.clone().or_else(|| { overrides.model.clone().or_else(|| {
file.and_then(|f| { file.and_then(|f| {
f.default_model f.default_model
.clone() .clone()
@@ -738,13 +887,13 @@ struct LegacyProviderOverride {
fn legacy_provider_override( fn legacy_provider_override(
file: Option<&ConfigFile>, file: Option<&ConfigFile>,
cli: &Cli, overrides: &ConfigOverrides,
) -> Option<LegacyProviderOverride> { ) -> Option<LegacyProviderOverride> {
let base_url = cli let base_url = overrides
.base_url .base_url
.clone() .clone()
.or_else(|| file.and_then(|f| f.base_url.clone())); .or_else(|| file.and_then(|f| f.base_url.clone()));
let api_key = cli let api_key = overrides
.api_key_env .api_key_env
.as_ref() .as_ref()
.map(|env| format!("${env}")) .map(|env| format!("${env}"))
+46
View File
@@ -14,6 +14,10 @@ pub enum Record {
created_at: String, created_at: String,
model: String, model: String,
cwd: String, cwd: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
parent_chat_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
branch_from: Option<BranchPoint>,
}, },
System { System {
content: String, content: String,
@@ -40,6 +44,15 @@ pub enum Record {
}, },
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BranchPoint {
pub chat_id: String,
pub record_index: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_call_id: Option<String>,
pub checkpoint_label: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StoredToolCall { pub struct StoredToolCall {
pub id: String, pub id: String,
@@ -92,6 +105,8 @@ impl Conversation {
created_at: now_ts(), created_at: now_ts(),
model: model.to_string(), model: model.to_string(),
cwd: cwd.display().to_string(), cwd: cwd.display().to_string(),
parent_chat_id: None,
branch_from: None,
})?; })?;
convo.append(Record::System { convo.append(Record::System {
content: base_system, content: base_system,
@@ -161,6 +176,37 @@ impl Conversation {
_ => None, _ => None,
}) })
} }
pub fn meta(&self) -> Option<ConversationMeta> {
self.records.iter().find_map(|r| match r {
Record::Meta {
chat_id,
created_at,
model,
cwd,
parent_chat_id,
branch_from,
} => Some(ConversationMeta {
chat_id: chat_id.clone(),
created_at: created_at.clone(),
model: model.clone(),
cwd: cwd.clone(),
parent_chat_id: parent_chat_id.clone(),
branch_from: branch_from.clone(),
}),
_ => None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversationMeta {
pub chat_id: String,
pub created_at: String,
pub model: String,
pub cwd: String,
pub parent_chat_id: Option<String>,
pub branch_from: Option<BranchPoint>,
} }
pub fn list_chats(conversations_dir: &Path, cwd: &Path) -> Result<Vec<ChatSummary>> { pub fn list_chats(conversations_dir: &Path, cwd: &Path) -> Result<Vec<ChatSummary>> {
+563
View File
@@ -0,0 +1,563 @@
//! Experimental Rust embedding API for running Cassady without the TUI.
//!
//! This module provides the first Rust-native surface for embedding Cassady in
//! another application. It reuses Cassady's existing runtime behavior while
//! giving the host application control over event presentation, turn lifecycle,
//! and approval decisions.
use crate::access::AccessMode;
use crate::agent::{self, AgentCommand, AgentEvent, AgentSettings};
use crate::config::{Config, ConfigOverrides, ReasoningEffort};
use crate::conversation::{self, Conversation, Record};
use crate::prompt;
use serde_json::Value;
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
const TURN_CANCELLED_MESSAGE: &str = "Turn cancelled by host.";
const TOOL_CANCELLED_MESSAGE: &str = "Tool execution cancelled by host.";
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
pub enum Error {
#[error("configuration error: {0}")]
Config(#[source] anyhow::Error),
#[error("conversation error: {0}")]
Conversation(#[source] anyhow::Error),
#[error("agent error: {0}")]
Agent(#[source] anyhow::Error),
#[error("agent task failed: {0}")]
Join(#[source] tokio::task::JoinError),
#[error("turn is already closed")]
TurnClosed,
#[error("approval request `{0}` is not pending")]
ApprovalNotPending(String),
#[error("turn session state is unavailable")]
MissingSession,
}
impl Error {
fn config(err: anyhow::Error) -> Self {
Self::Config(err)
}
fn conversation(err: anyhow::Error) -> Self {
Self::Conversation(err)
}
fn agent(err: anyhow::Error) -> Self {
Self::Agent(err)
}
}
#[derive(Debug, Clone, Default)]
pub struct SessionBuilder {
config_root: Option<PathBuf>,
cwd: Option<PathBuf>,
access_mode: Option<AccessMode>,
model: Option<String>,
base_url: Option<String>,
api_key_env: Option<String>,
reasoning_effort: Option<ReasoningEffort>,
}
impl SessionBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn config_root(mut self, root: impl Into<PathBuf>) -> Self {
self.config_root = Some(root.into());
self
}
pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
pub fn access_mode(mut self, mode: AccessMode) -> Self {
self.access_mode = Some(mode);
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
pub fn api_key_env(mut self, api_key_env: impl Into<String>) -> Self {
self.api_key_env = Some(api_key_env.into());
self
}
pub fn reasoning_effort(mut self, effort: ReasoningEffort) -> Self {
self.reasoning_effort = Some(effort);
self
}
pub async fn build(self) -> Result<Session> {
self.new_session().await
}
pub async fn new_session(self) -> Result<Session> {
let PreparedSession {
config,
cwd,
mode,
reasoning_effort,
} = self.prepare().await?;
let conversation = create_new_conversation(&config, &cwd)?;
Ok(Session {
config,
cwd,
mode,
reasoning_effort,
conversation,
resume_warning: None,
})
}
pub async fn resume(self, chat_id: impl AsRef<str>) -> Result<Session> {
let PreparedSession {
config,
cwd,
mode,
reasoning_effort,
} = self.prepare().await?;
let (conversation, warning) =
Conversation::load(&config.conversations_dir(), chat_id.as_ref())
.map_err(Error::conversation)?;
Ok(Session {
config,
cwd,
mode,
reasoning_effort,
conversation,
resume_warning: warning,
})
}
async fn prepare(self) -> Result<PreparedSession> {
let root = self.config_root.unwrap_or_else(crate::config::cass_root);
let overrides = ConfigOverrides {
model: self.model,
base_url: self.base_url,
api_key_env: self.api_key_env,
access_mode: self.access_mode,
};
let config = Config::load_with_overrides(root, overrides).map_err(Error::config)?;
config.ensure_provider_auth().map_err(Error::config)?;
let cwd = resolve_cwd(self.cwd).map_err(Error::config)?;
let mode = config.default_access_mode;
let reasoning_effort = self
.reasoning_effort
.unwrap_or(config.reasoning_effort)
.clamp_for_model(config.model_metadata.as_ref());
Ok(PreparedSession {
config,
cwd,
mode,
reasoning_effort,
})
}
}
struct PreparedSession {
config: Config,
cwd: PathBuf,
mode: AccessMode,
reasoning_effort: ReasoningEffort,
}
#[derive(Debug)]
pub struct Session {
config: Config,
cwd: PathBuf,
mode: AccessMode,
reasoning_effort: ReasoningEffort,
conversation: Conversation,
resume_warning: Option<String>,
}
impl Session {
pub fn id(&self) -> &str {
&self.conversation.id
}
pub fn cwd(&self) -> &Path {
&self.cwd
}
pub fn model(&self) -> &str {
&self.config.model
}
pub fn access_mode(&self) -> AccessMode {
self.mode
}
pub fn reasoning_effort(&self) -> ReasoningEffort {
self.reasoning_effort
}
pub fn conversation_path(&self) -> &Path {
&self.conversation.path
}
pub fn records(&self) -> &[Record] {
&self.conversation.records
}
pub fn resume_warning(&self) -> Option<&str> {
self.resume_warning.as_deref()
}
pub fn info(&self) -> ConversationInfo {
ConversationInfo {
id: self.conversation.id.clone(),
cwd: self.cwd.clone(),
model: self.config.model.clone(),
access_mode: self.mode,
reasoning_effort: self.reasoning_effort,
path: self.conversation.path.clone(),
record_count: self.conversation.records.len(),
}
}
pub async fn start_turn(self, user_message: impl Into<String>) -> Result<Turn> {
let message = user_message.into();
let turn_start_len = self.conversation.records.len();
let (event_tx, event_rx) = mpsc::unbounded_channel::<AgentEvent>();
let (command_tx, command_rx) = mpsc::unbounded_channel::<AgentCommand>();
let settings = AgentSettings {
config: self.config.clone(),
cwd: self.cwd.clone(),
mode: self.mode,
reasoning_effort: self.reasoning_effort,
};
let conversation = self.conversation.clone();
let task_message = message.clone();
let handle = tokio::spawn(agent::run_turn_with_commands(
conversation,
task_message,
settings,
event_tx,
command_rx,
));
Ok(Turn {
session: Some(self),
handle: Some(handle),
event_rx,
command_tx: Some(command_tx),
pending_approvals: BTreeSet::new(),
turn_start_len,
user_message: message,
})
}
}
#[derive(Debug, Clone)]
pub struct ConversationInfo {
pub id: String,
pub cwd: PathBuf,
pub model: String,
pub access_mode: AccessMode,
pub reasoning_effort: ReasoningEffort,
pub path: PathBuf,
pub record_count: usize,
}
#[derive(Debug)]
pub struct Turn {
session: Option<Session>,
handle: Option<JoinHandle<anyhow::Result<Conversation>>>,
event_rx: mpsc::UnboundedReceiver<AgentEvent>,
command_tx: Option<mpsc::UnboundedSender<AgentCommand>>,
pending_approvals: BTreeSet<String>,
turn_start_len: usize,
user_message: String,
}
impl Turn {
pub async fn next_event(&mut self) -> Result<Option<Event>> {
match self.event_rx.recv().await {
Some(event) => {
let event = Event::from_agent(event);
match &event {
Event::ApprovalRequested(request) => {
self.pending_approvals.insert(request.request_id.clone());
}
Event::ApprovalResolved { request_id, .. } => {
self.pending_approvals.remove(request_id);
}
_ => {}
}
Ok(Some(event))
}
None => Ok(None),
}
}
pub fn approve(&mut self, request_id: impl AsRef<str>) -> Result<()> {
self.resolve_approval(request_id.as_ref(), true)
}
pub fn deny(&mut self, request_id: impl AsRef<str>) -> Result<()> {
self.resolve_approval(request_id.as_ref(), false)
}
pub async fn finish(mut self) -> Result<Session> {
let handle = self.handle.take().ok_or(Error::TurnClosed)?;
let conversation = match handle.await.map_err(Error::Join)? {
Ok(conversation) => conversation,
Err(err) => return Err(Error::agent(err)),
};
let mut session = self.session.take().ok_or(Error::MissingSession)?;
session.conversation = conversation;
self.command_tx = None;
Ok(session)
}
pub async fn cancel(mut self) -> Result<Session> {
if let Some(handle) = &self.handle {
handle.abort();
}
if let Some(handle) = self.handle.take() {
match handle.await {
Ok(Ok(conversation)) => {
let mut session = self.session.take().ok_or(Error::MissingSession)?;
session.conversation = conversation;
self.command_tx = None;
return Ok(session);
}
Ok(Err(err)) => return Err(Error::agent(err)),
Err(err) if err.is_cancelled() => {}
Err(err) => return Err(Error::Join(err)),
}
}
let mut session = self.session.take().ok_or(Error::MissingSession)?;
session.conversation = finalize_cancelled_turn(
&session.config,
&session.conversation.id,
self.turn_start_len,
&self.user_message,
)?;
self.command_tx = None;
Ok(session)
}
fn resolve_approval(&mut self, request_id: &str, approved: bool) -> Result<()> {
if !self.pending_approvals.remove(request_id) {
return Err(Error::ApprovalNotPending(request_id.to_string()));
}
let tx = self.command_tx.as_ref().ok_or(Error::TurnClosed)?;
tx.send(AgentCommand::ApprovalDecision {
request_id: request_id.to_string(),
approved,
})
.map_err(|_| Error::TurnClosed)
}
}
impl Drop for Turn {
fn drop(&mut self) {
if let Some(handle) = &self.handle {
handle.abort();
}
}
}
#[derive(Debug, Clone)]
pub enum Event {
AssistantChunk(String),
ReasoningChunk(String),
ToolCallStarted {
id: String,
name: String,
arguments: Value,
},
ToolOutputChunk {
id: String,
name: String,
stream: String,
content: String,
},
ToolResult {
id: String,
name: String,
ok: bool,
content: String,
},
ApprovalRequested(ApprovalRequest),
ApprovalResolved {
request_id: String,
approved: bool,
},
Status(String),
Finished,
}
impl Event {
fn from_agent(event: AgentEvent) -> Self {
match event {
AgentEvent::AssistantChunk(text) => Self::AssistantChunk(text),
AgentEvent::ReasoningChunk(text) => Self::ReasoningChunk(text),
AgentEvent::ToolCallStarted {
id,
name,
arguments,
} => Self::ToolCallStarted {
id,
name,
arguments,
},
AgentEvent::ToolOutputChunk {
id,
name,
stream,
content,
} => Self::ToolOutputChunk {
id,
name,
stream,
content,
},
AgentEvent::ToolResult {
id,
name,
ok,
content,
} => Self::ToolResult {
id,
name,
ok,
content,
},
AgentEvent::ApprovalRequested {
request_id,
tool_call_id,
name,
arguments,
reason,
} => Self::ApprovalRequested(ApprovalRequest {
request_id,
tool_call_id,
name,
arguments,
reason,
}),
AgentEvent::ApprovalResolved {
request_id,
approved,
} => Self::ApprovalResolved {
request_id,
approved,
},
AgentEvent::Status(status) => Self::Status(status),
AgentEvent::TurnFinished => Self::Finished,
}
}
}
#[derive(Debug, Clone)]
pub struct ApprovalRequest {
pub request_id: String,
pub tool_call_id: String,
pub name: String,
pub arguments: Value,
pub reason: String,
}
fn resolve_cwd(cwd: Option<PathBuf>) -> anyhow::Result<PathBuf> {
let cwd = cwd.unwrap_or(std::env::current_dir()?);
cwd.canonicalize()
.map_err(anyhow::Error::from)
.map_err(|err| anyhow::anyhow!("resolving cwd {}: {err}", cwd.display()))
}
fn create_new_conversation(config: &Config, cwd: &Path) -> Result<Conversation> {
let global = fs::read_to_string(config.global_path()).ok();
let base = prompt::build_base_system_prompt(global.as_deref());
Conversation::create(&config.conversations_dir(), &config.model, cwd, base)
.map_err(Error::conversation)
}
fn finalize_cancelled_turn(
config: &Config,
chat_id: &str,
turn_start_len: usize,
turn_message: &str,
) -> Result<Conversation> {
let (mut conversation, _) =
Conversation::load(&config.conversations_dir(), chat_id).map_err(Error::conversation)?;
if conversation.records.len() <= turn_start_len {
conversation
.append(Record::User {
content: turn_message.to_string(),
ts: conversation::now_ts(),
})
.map_err(Error::conversation)?;
}
for (id, name) in pending_tool_calls(&conversation.records) {
conversation
.append(Record::Tool {
tool_call_id: id,
name,
ok: false,
content: TOOL_CANCELLED_MESSAGE.to_string(),
ts: conversation::now_ts(),
})
.map_err(Error::conversation)?;
}
if !matches!(
conversation.records.last(),
Some(Record::Assistant { content, tool_calls, .. })
if content == TURN_CANCELLED_MESSAGE && tool_calls.is_empty()
) {
conversation
.append(Record::Assistant {
content: TURN_CANCELLED_MESSAGE.to_string(),
reasoning: String::new(),
reasoning_field: None,
tool_calls: Vec::new(),
ts: conversation::now_ts(),
})
.map_err(Error::conversation)?;
}
Ok(conversation)
}
fn pending_tool_calls(records: &[Record]) -> Vec<(String, String)> {
let mut pending = Vec::new();
for record in records {
match record {
Record::Assistant { tool_calls, .. } => {
pending = tool_calls
.iter()
.map(|call| (call.id.clone(), call.name.clone()))
.collect();
}
Record::Tool { tool_call_id, .. } => {
pending.retain(|(id, _)| id != tool_call_id);
}
Record::User { .. } => pending.clear(),
_ => {}
}
}
pending
}
+470
View File
@@ -0,0 +1,470 @@
use crate::tools::{self, ToolContext};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
const MAX_SNAPSHOT_BYTES: u64 = 10 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileEditJournalEntry {
pub chat_id: String,
pub record_index: usize,
pub tool_call_id: String,
pub tool_name: String,
pub path: PathBuf,
pub existed_before: bool,
pub existed_after: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub before_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub before_snapshot: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after_snapshot: Option<PathBuf>,
pub ts: String,
}
#[derive(Debug, Clone)]
pub struct PendingFileEditSnapshot {
pub chat_id: String,
pub record_index: usize,
pub tool_call_id: String,
pub tool_name: String,
pub path: PathBuf,
before: SnapshotState,
}
#[derive(Debug, Clone)]
enum SnapshotState {
Missing,
File { bytes: Vec<u8>, hash: String },
Unsupported,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestorePlan {
pub actions: Vec<RestoreAction>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RestoreAction {
Write {
path: PathBuf,
snapshot: PathBuf,
desired_hash: String,
expected_current_hash: Option<String>,
conflict: bool,
},
Delete {
path: PathBuf,
expected_current_hash: Option<String>,
conflict: bool,
},
Skip {
path: PathBuf,
reason: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestoreOutcome {
pub applied: usize,
pub skipped: usize,
pub conflicts: usize,
}
pub fn begin_tool_edit(
cass_root: &Path,
chat_id: &str,
record_index: usize,
tool_call_id: &str,
tool_name: &str,
args: &Value,
ctx: &ToolContext,
) -> Option<PendingFileEditSnapshot> {
if !matches!(tool_name, "write" | "edit") {
return None;
}
let path_arg = args.get("path")?.as_str()?;
let path =
tools::path::resolve_for_write(path_arg, &ctx.cwd, ctx.mode, &ctx.blocked_write_roots)
.ok()?;
let before = snapshot_state(&path).unwrap_or(SnapshotState::Unsupported);
// Ensure journal directories are creatable before executing, but do not fail
// the tool if Cassady cannot journal; restore will simply be unavailable.
let _ = fs::create_dir_all(cass_root.join("file-edits"));
let _ = fs::create_dir_all(cass_root.join("file-snapshots"));
Some(PendingFileEditSnapshot {
chat_id: chat_id.to_string(),
record_index,
tool_call_id: tool_call_id.to_string(),
tool_name: tool_name.to_string(),
path,
before,
})
}
pub fn finish_tool_edit(cass_root: &Path, pending: PendingFileEditSnapshot) -> Result<()> {
let after = snapshot_state(&pending.path).unwrap_or(SnapshotState::Unsupported);
if matches!(pending.before, SnapshotState::Unsupported)
|| matches!(after, SnapshotState::Unsupported)
{
return Ok(());
}
if same_state(&pending.before, &after) {
return Ok(());
}
let (existed_before, before_hash, before_snapshot) = store_snapshot(
cass_root,
&pending.chat_id,
&pending.tool_call_id,
"before",
&pending.before,
)?;
let (existed_after, after_hash, after_snapshot) = store_snapshot(
cass_root,
&pending.chat_id,
&pending.tool_call_id,
"after",
&after,
)?;
let entry = FileEditJournalEntry {
chat_id: pending.chat_id.clone(),
record_index: pending.record_index,
tool_call_id: pending.tool_call_id,
tool_name: pending.tool_name,
path: pending.path,
existed_before,
existed_after,
before_hash,
after_hash,
before_snapshot,
after_snapshot,
ts: crate::conversation::now_ts(),
};
append_journal(cass_root, &pending.chat_id, &entry)
}
pub fn load_journal(cass_root: &Path, chat_id: &str) -> Result<Vec<FileEditJournalEntry>> {
let path = journal_path(cass_root, chat_id);
if !path.exists() {
return Ok(Vec::new());
}
let content =
fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
let mut out = Vec::new();
for (idx, line) in content.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let entry: FileEditJournalEntry = serde_json::from_str(line)
.with_context(|| format!("parsing {} line {}", path.display(), idx + 1))?;
out.push(entry);
}
out.sort_by_key(|entry| entry.record_index);
Ok(out)
}
pub fn plan_restore(
cass_root: &Path,
chat_id: &str,
target_record_index: usize,
) -> Result<RestorePlan> {
let entries = load_journal(cass_root, chat_id)?;
let mut by_path: BTreeMap<PathBuf, Vec<FileEditJournalEntry>> = BTreeMap::new();
for entry in entries {
by_path.entry(entry.path.clone()).or_default().push(entry);
}
let mut actions = Vec::new();
for (path, mut entries) in by_path {
entries.sort_by_key(|entry| entry.record_index);
let latest = entries.last().cloned();
let desired = entries
.iter()
.rev()
.find(|entry| entry.record_index <= target_record_index)
.cloned();
let first_after = entries
.iter()
.find(|entry| entry.record_index > target_record_index)
.cloned();
let (want_exists, want_hash, want_snapshot) = if let Some(entry) = desired {
(entry.existed_after, entry.after_hash, entry.after_snapshot)
} else if let Some(entry) = first_after {
(
entry.existed_before,
entry.before_hash,
entry.before_snapshot,
)
} else {
continue;
};
let expected_current_hash = latest.and_then(|entry| entry.after_hash);
let current_hash = hash_existing_file(&path)?;
let conflict = expected_current_hash.is_some()
&& current_hash.is_some()
&& expected_current_hash != current_hash;
if want_exists {
match (want_hash, want_snapshot) {
(Some(desired_hash), Some(snapshot)) => actions.push(RestoreAction::Write {
path,
snapshot,
desired_hash,
expected_current_hash,
conflict,
}),
_ => actions.push(RestoreAction::Skip {
path,
reason: "missing desired snapshot".into(),
}),
}
} else {
let conflict = conflict
|| (current_hash.is_some()
&& expected_current_hash.is_none()
&& current_hash != expected_current_hash);
actions.push(RestoreAction::Delete {
path,
expected_current_hash,
conflict,
});
}
}
Ok(RestorePlan { actions })
}
pub fn apply_restore_plan(plan: &RestorePlan) -> Result<RestoreOutcome> {
let mut outcome = RestoreOutcome {
applied: 0,
skipped: 0,
conflicts: 0,
};
for action in &plan.actions {
match action {
RestoreAction::Write {
path,
snapshot,
conflict,
..
} => {
if *conflict {
outcome.conflicts += 1;
continue;
}
let bytes = fs::read(snapshot)
.with_context(|| format!("reading snapshot {}", snapshot.display()))?;
crate::tools::write::atomic_write(path, &bytes)
.with_context(|| format!("restoring {}", path.display()))?;
outcome.applied += 1;
}
RestoreAction::Delete { path, conflict, .. } => {
if *conflict {
outcome.conflicts += 1;
continue;
}
if path.exists() {
fs::remove_file(path)
.with_context(|| format!("deleting {}", path.display()))?;
outcome.applied += 1;
} else {
outcome.skipped += 1;
}
}
RestoreAction::Skip { .. } => outcome.skipped += 1,
}
}
Ok(outcome)
}
pub fn summarize_plan(plan: &RestorePlan) -> String {
if plan.actions.is_empty() {
return "No tracked file edits need restoration for this checkpoint.".into();
}
let mut lines = Vec::new();
for action in &plan.actions {
match action {
RestoreAction::Write { path, conflict, .. } => lines.push(format!(
"{} update {}",
if *conflict { "CONFLICT" } else { "will" },
path.display()
)),
RestoreAction::Delete { path, conflict, .. } => lines.push(format!(
"{} delete {}",
if *conflict { "CONFLICT" } else { "will" },
path.display()
)),
RestoreAction::Skip { path, reason } => {
lines.push(format!("skip {}: {reason}", path.display()))
}
}
}
lines.join("\n")
}
fn snapshot_state(path: &Path) -> Result<SnapshotState> {
match fs::metadata(path) {
Ok(metadata) => {
if !metadata.is_file() || metadata.len() > MAX_SNAPSHOT_BYTES {
return Ok(SnapshotState::Unsupported);
}
let bytes = fs::read(path)?;
let hash = sha256_hex(&bytes);
Ok(SnapshotState::File { bytes, hash })
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(SnapshotState::Missing),
Err(err) => Err(err.into()),
}
}
fn same_state(a: &SnapshotState, b: &SnapshotState) -> bool {
match (a, b) {
(SnapshotState::Missing, SnapshotState::Missing) => true,
(SnapshotState::File { hash: a, .. }, SnapshotState::File { hash: b, .. }) => a == b,
_ => false,
}
}
fn store_snapshot(
cass_root: &Path,
chat_id: &str,
tool_call_id: &str,
side: &str,
state: &SnapshotState,
) -> Result<(bool, Option<String>, Option<PathBuf>)> {
match state {
SnapshotState::Missing => Ok((false, None, None)),
SnapshotState::Unsupported => Ok((false, None, None)),
SnapshotState::File { bytes, hash } => {
let dir = cass_root
.join("file-snapshots")
.join(chat_id)
.join(tool_call_id);
fs::create_dir_all(&dir)?;
let path = dir.join(format!("{side}-{hash}.bin"));
if !path.exists() {
fs::write(&path, bytes)?;
}
Ok((true, Some(hash.clone()), Some(path)))
}
}
}
fn append_journal(cass_root: &Path, chat_id: &str, entry: &FileEditJournalEntry) -> Result<()> {
let path = journal_path(cass_root, chat_id);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let mut file = OpenOptions::new().create(true).append(true).open(&path)?;
writeln!(file, "{}", serde_json::to_string(entry)?)?;
file.flush()?;
Ok(())
}
fn journal_path(cass_root: &Path, chat_id: &str) -> PathBuf {
cass_root
.join("file-edits")
.join(format!("{chat_id}.jsonl"))
}
fn hash_existing_file(path: &Path) -> Result<Option<String>> {
match fs::metadata(path) {
Ok(metadata) => {
if !metadata.is_file() || metadata.len() > MAX_SNAPSHOT_BYTES {
return Ok(None);
}
Ok(Some(sha256_hex(&fs::read(path)?)))
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
}
fn sha256_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
digest.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::access::AccessMode;
use tempfile::tempdir;
fn tool_ctx(cwd: &Path) -> ToolContext {
ToolContext {
mode: AccessMode::WorkspaceEdit,
cwd: cwd.to_path_buf(),
read_roots: vec![cwd.to_path_buf()],
blocked_write_roots: Vec::new(),
model_result_limit: 1000,
runtime_tx: None,
}
}
#[test]
fn journal_and_restore_rewinds_write() {
let root = tempdir().unwrap();
let work = tempdir().unwrap();
let path = work.path().join("a.txt");
fs::write(&path, "old").unwrap();
let ctx = tool_ctx(work.path());
let pending = begin_tool_edit(
root.path(),
"chat",
3,
"call",
"write",
&serde_json::json!({"path":"a.txt"}),
&ctx,
)
.unwrap();
fs::write(&path, "new").unwrap();
finish_tool_edit(root.path(), pending).unwrap();
let plan = plan_restore(root.path(), "chat", 2).unwrap();
assert_eq!(plan.actions.len(), 1);
let outcome = apply_restore_plan(&plan).unwrap();
assert_eq!(outcome.applied, 1);
assert_eq!(fs::read_to_string(&path).unwrap(), "old");
}
#[test]
fn restore_detects_external_conflict() {
let root = tempdir().unwrap();
let work = tempdir().unwrap();
let path = work.path().join("a.txt");
fs::write(&path, "old").unwrap();
let ctx = tool_ctx(work.path());
let pending = begin_tool_edit(
root.path(),
"chat",
3,
"call",
"write",
&serde_json::json!({"path":"a.txt"}),
&ctx,
)
.unwrap();
fs::write(&path, "new").unwrap();
finish_tool_edit(root.path(), pending).unwrap();
fs::write(&path, "manual").unwrap();
let plan = plan_restore(root.path(), "chat", 2).unwrap();
assert!(matches!(
&plan.actions[0],
RestoreAction::Write { conflict: true, .. }
));
}
}
+6
View File
@@ -1,19 +1,25 @@
pub mod access; pub mod access;
pub mod agent; pub mod agent;
pub mod app; pub mod app;
pub mod branch;
pub mod check; pub mod check;
pub mod cli; pub mod cli;
pub mod codex_auth;
pub mod config; pub mod config;
pub mod conversation; pub mod conversation;
pub mod docs; pub mod docs;
pub mod embedding;
pub mod error; pub mod error;
pub mod file_edits;
pub mod menu; pub mod menu;
pub mod prelude;
pub mod prompt; pub mod prompt;
pub mod providers; pub mod providers;
pub mod security; pub mod security;
pub mod setup; pub mod setup;
pub mod tools; pub mod tools;
pub mod ui; pub mod ui;
pub mod update;
pub async fn run() -> anyhow::Result<()> { pub async fn run() -> anyhow::Result<()> {
app::run().await app::run().await
+7
View File
@@ -0,0 +1,7 @@
//! Common imports for Cassady's experimental Rust embedding API.
pub use crate::access::AccessMode;
pub use crate::config::ReasoningEffort;
pub use crate::embedding::{
ApprovalRequest, ConversationInfo, Event, Session, SessionBuilder, Turn,
};
+544
View File
@@ -0,0 +1,544 @@
use super::types::{CompletionResult, ModelMessage};
use crate::agent::AgentEvent;
use crate::codex_auth::load_codex_access_token;
use crate::config::{ReasoningEffort, CHATGPT_CODEX_RESPONSES_URL};
use crate::conversation::StoredToolCall;
use crate::tools::ToolSpec;
use anyhow::{bail, Result};
use futures_util::StreamExt;
use reqwest::Client;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use tokio::sync::mpsc;
#[derive(Debug, Clone)]
pub struct ChatGptCodexProvider {
client: Client,
model: String,
endpoint: String,
reasoning_effort: ReasoningEffort,
fast_mode: bool,
}
#[derive(Debug, Clone)]
pub struct ChatGptCodexSettings {
pub model: String,
pub endpoint: String,
pub reasoning_effort: ReasoningEffort,
pub fast_mode: bool,
}
#[derive(Debug, Default, Clone)]
struct PartialFunctionCall {
call_id: Option<String>,
name: Option<String>,
arguments: String,
}
impl ChatGptCodexProvider {
pub fn new(settings: ChatGptCodexSettings) -> Self {
Self {
client: Client::new(),
model: settings.model,
endpoint: normalize_endpoint(&settings.endpoint),
reasoning_effort: settings.reasoning_effort,
fast_mode: settings.fast_mode,
}
}
pub async fn complete(
&self,
messages: Vec<ModelMessage>,
tools: Vec<ToolSpec>,
tx: &mpsc::UnboundedSender<AgentEvent>,
) -> Result<CompletionResult> {
let token = load_codex_access_token()?;
let secret = token.as_secret().to_string();
let body = responses_body(
&self.model,
messages,
tools,
self.reasoning_effort,
self.fast_mode,
);
let resp = self
.client
.post(&self.endpoint)
.bearer_auth(token.as_secret())
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
bail!(
"ChatGPT Codex returned {status}: {}",
redact_secret(&text, &secret)
);
}
let mut state = StreamState::default();
let mut buf = String::new();
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
let chunk_text = String::from_utf8_lossy(&chunk).replace("\r\n", "\n");
buf.push_str(&chunk_text);
while let Some(pos) = buf.find("\n\n") {
let frame = buf[..pos].to_string();
buf = buf[pos + 2..].to_string();
process_frame(&frame, &mut state, tx)?;
}
}
if !buf.trim().is_empty() {
process_frame(&buf, &mut state, tx)?;
}
Ok(state.finish())
}
}
#[derive(Debug, Default)]
struct StreamState {
content: String,
reasoning: String,
reasoning_field: Option<String>,
partials: BTreeMap<String, PartialFunctionCall>,
}
impl StreamState {
fn finish(self) -> CompletionResult {
let tool_calls = self
.partials
.into_iter()
.filter_map(|(key, partial)| {
let name = partial.name?;
let id = partial.call_id.unwrap_or(key);
let arguments = serde_json::from_str(&partial.arguments)
.unwrap_or_else(|_| json!({"_raw": partial.arguments}));
Some(StoredToolCall {
id,
name,
arguments,
})
})
.collect();
CompletionResult {
content: self.content,
reasoning: self.reasoning,
reasoning_field: self.reasoning_field,
tool_calls,
}
}
}
fn responses_body(
model: &str,
messages: Vec<ModelMessage>,
tools: Vec<ToolSpec>,
reasoning_effort: ReasoningEffort,
fast_mode: bool,
) -> Value {
let mut instructions = Vec::new();
let mut input = Vec::new();
for message in messages {
match message {
ModelMessage::System { content } => instructions.push(content),
ModelMessage::User { content } => input.push(json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": content}]
})),
ModelMessage::Assistant {
content,
reasoning: _,
reasoning_field: _,
tool_calls,
} => {
if !content.is_empty() {
input.push(json!({
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": content}]
}));
}
for call in tool_calls {
input.push(json!({
"type": "function_call",
"call_id": call.id,
"name": call.name,
"arguments": call.arguments.to_string()
}));
}
}
ModelMessage::Tool {
tool_call_id,
name: _,
content,
} => input.push(json!({
"type": "function_call_output",
"call_id": tool_call_id,
"output": content
})),
}
}
let mut body = json!({
"model": model,
"input": input,
"tools": tools_to_responses(tools),
"stream": true,
"store": false
});
if !instructions.is_empty() {
body["instructions"] = Value::String(instructions.join("\n\n"));
}
if fast_mode {
body["reasoning"] = json!({"effort": "minimal", "summary": "auto"});
} else if let Some(effort) = reasoning_effort.request_value() {
body["reasoning"] = json!({"effort": effort, "summary": "auto"});
} else if reasoning_effort == ReasoningEffort::Off {
body["reasoning"] = json!({"effort": "none", "summary": "auto"});
}
body
}
fn tools_to_responses(tools: Vec<ToolSpec>) -> Vec<Value> {
tools
.into_iter()
.map(|tool| {
json!({
"type": "function",
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters
})
})
.collect()
}
fn process_frame(
frame: &str,
state: &mut StreamState,
tx: &mpsc::UnboundedSender<AgentEvent>,
) -> Result<()> {
for line in frame.lines() {
let line = line.trim();
if !line.starts_with("data:") {
continue;
}
let data = line.trim_start_matches("data:").trim();
if data == "[DONE]" || data.is_empty() {
continue;
}
let value: Value = serde_json::from_str(data)?;
handle_event(&value, state, tx)?;
}
Ok(())
}
fn handle_event(
value: &Value,
state: &mut StreamState,
tx: &mpsc::UnboundedSender<AgentEvent>,
) -> Result<()> {
let event_type = value
.get("type")
.and_then(Value::as_str)
.unwrap_or_default();
match event_type {
"response.output_text.delta" | "response.message.delta" | "output_text.delta" => {
if let Some(delta) = string_field(value, &["delta", "text"]) {
push_content(state, tx, delta);
}
}
"response.reasoning_summary_text.delta"
| "response.reasoning_text.delta"
| "response.reasoning.delta"
| "reasoning.delta" => {
if let Some(delta) = string_field(value, &["delta", "text"]) {
push_reasoning(state, tx, "reasoning_summary", delta);
}
}
"response.function_call_arguments.delta" | "function_call_arguments.delta" => {
let key = event_key(value);
let partial = state.partials.entry(key).or_default();
if let Some(delta) = string_field(value, &["delta", "arguments_delta"]) {
partial.arguments.push_str(delta);
}
}
"response.function_call_arguments.done" | "function_call_arguments.done" => {
let key = event_key(value);
let partial = state.partials.entry(key).or_default();
if let Some(arguments) = string_field(value, &["arguments"]) {
partial.arguments = arguments.to_string();
}
if let Some(call_id) = string_field(value, &["call_id", "id"]) {
partial.call_id = Some(call_id.to_string());
}
if let Some(name) = string_field(value, &["name"]) {
partial.name = Some(name.to_string());
}
}
"response.output_item.added"
| "response.output_item.done"
| "output_item.added"
| "output_item.done" => {
if let Some(item) = value.get("item") {
handle_item(item, state, tx, event_type.ends_with("done"));
}
}
"response.completed" | "response.done" => {
if state.content.is_empty() {
if let Some(response) = value.get("response") {
extract_final_response(response, state, tx);
}
}
}
_ => {
if let Some(item) = value.get("item") {
handle_item(item, state, tx, false);
} else if let Some(delta) = value
.get("delta")
.and_then(Value::as_str)
.filter(|_| event_type.contains("output_text"))
{
push_content(state, tx, delta);
}
}
}
Ok(())
}
fn handle_item(
item: &Value,
state: &mut StreamState,
tx: &mpsc::UnboundedSender<AgentEvent>,
final_item: bool,
) {
match item.get("type").and_then(Value::as_str).unwrap_or_default() {
"message" => {
if final_item && state.content.is_empty() {
for content in item
.get("content")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
if matches!(
content.get("type").and_then(Value::as_str),
Some("output_text")
) {
if let Some(text) = content.get("text").and_then(Value::as_str) {
push_content(state, tx, text);
}
}
}
}
}
"reasoning" => {
for summary in item
.get("summary")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
if let Some(text) = summary.get("text").and_then(Value::as_str) {
push_reasoning(state, tx, "reasoning_summary", text);
}
}
}
"function_call" => {
let key = item
.get("call_id")
.or_else(|| item.get("id"))
.or_else(|| item.get("item_id"))
.and_then(Value::as_str)
.unwrap_or("call")
.to_string();
let partial = state.partials.entry(key.clone()).or_default();
if let Some(call_id) = item
.get("call_id")
.or_else(|| item.get("id"))
.and_then(Value::as_str)
{
partial.call_id = Some(call_id.to_string());
}
if let Some(name) = item.get("name").and_then(Value::as_str) {
partial.name = Some(name.to_string());
}
if let Some(arguments) = item.get("arguments").and_then(Value::as_str) {
partial.arguments = arguments.to_string();
}
}
_ => {}
}
}
fn extract_final_response(
response: &Value,
state: &mut StreamState,
tx: &mpsc::UnboundedSender<AgentEvent>,
) {
for item in response
.get("output")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
handle_item(item, state, tx, true);
}
}
fn push_content(state: &mut StreamState, tx: &mpsc::UnboundedSender<AgentEvent>, text: &str) {
state.content.push_str(text);
let _ = tx.send(AgentEvent::AssistantChunk(text.to_string()));
}
fn push_reasoning(
state: &mut StreamState,
tx: &mpsc::UnboundedSender<AgentEvent>,
field: &'static str,
text: &str,
) {
state
.reasoning_field
.get_or_insert_with(|| field.to_string());
state.reasoning.push_str(text);
let _ = tx.send(AgentEvent::ReasoningChunk(text.to_string()));
}
fn string_field<'a>(value: &'a Value, fields: &[&str]) -> Option<&'a str> {
fields.iter().find_map(|field| value.get(*field)?.as_str())
}
fn event_key(value: &Value) -> String {
string_field(
value,
&["call_id", "item_id", "output_item_id", "id", "output_index"],
)
.map(str::to_string)
.or_else(|| {
value
.get("output_index")
.and_then(Value::as_u64)
.map(|n| n.to_string())
})
.unwrap_or_else(|| "call".to_string())
}
fn normalize_endpoint(endpoint: &str) -> String {
let endpoint = endpoint.trim();
if endpoint.is_empty() {
CHATGPT_CODEX_RESPONSES_URL.to_string()
} else {
endpoint.to_string()
}
}
fn redact_secret(text: &str, secret: &str) -> String {
if secret.is_empty() {
text.to_string()
} else {
text.replace(secret, "<redacted>")
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
#[test]
fn responses_body_uses_function_call_items() {
let body = responses_body(
"gpt-test",
vec![
ModelMessage::System {
content: "system".into(),
},
ModelMessage::User {
content: "hello".into(),
},
ModelMessage::Assistant {
content: String::new(),
reasoning: String::new(),
reasoning_field: None,
tool_calls: vec![StoredToolCall {
id: "call_1".into(),
name: "read".into(),
arguments: json!({"path":"README.md"}),
}],
},
ModelMessage::Tool {
tool_call_id: "call_1".into(),
name: "read".into(),
content: "ok".into(),
},
],
Vec::new(),
ReasoningEffort::Off,
false,
);
assert_eq!(body["model"], "gpt-test");
assert_eq!(body["instructions"], "system");
assert!(body["input"].as_array().unwrap().iter().any(|item| {
item.get("type").and_then(Value::as_str) == Some("function_call_output")
}));
}
#[test]
fn responses_body_uses_minimal_reasoning_for_fast_mode() {
let body = responses_body(
"gpt-test",
vec![ModelMessage::User {
content: "hello".into(),
}],
Vec::new(),
ReasoningEffort::High,
true,
);
assert_eq!(
body["reasoning"],
json!({"effort": "minimal", "summary": "auto"})
);
}
#[test]
fn responses_body_sends_none_effort_when_reasoning_is_off() {
let body = responses_body(
"gpt-test",
vec![ModelMessage::User {
content: "hello".into(),
}],
Vec::new(),
ReasoningEffort::Off,
false,
);
assert_eq!(
body["reasoning"],
json!({"effort": "none", "summary": "auto"})
);
}
#[test]
fn stream_parser_collects_text_and_function_call() {
let (tx, _rx) = mpsc::unbounded_channel();
let mut state = StreamState::default();
process_frame(
"data: {\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}\n\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"README.md\\\"}\"}}\n\n",
&mut state,
&tx,
)
.unwrap();
let result = state.finish();
assert_eq!(result.content, "hi");
assert_eq!(result.tool_calls.len(), 1);
assert_eq!(result.tool_calls[0].id, "call_1");
assert_eq!(result.tool_calls[0].name, "read");
}
}
+70
View File
@@ -1,2 +1,72 @@
pub mod chatgpt_codex;
pub mod openai_compatible; pub mod openai_compatible;
pub mod types; pub mod types;
use crate::agent::AgentEvent;
use crate::config::{Config, ReasoningEffort, CHATGPT_CODEX_PROVIDER_KIND, DEFAULT_PROVIDER_KIND};
use crate::providers::chatgpt_codex::{ChatGptCodexProvider, ChatGptCodexSettings};
use crate::providers::openai_compatible::{OpenAiCompatibleProvider, OpenAiCompatibleSettings};
use crate::providers::types::{CompletionResult, ModelMessage};
use crate::tools::ToolSpec;
use anyhow::{bail, Result};
use tokio::sync::mpsc;
#[derive(Debug, Clone)]
pub enum ProviderClient {
OpenAiCompatible(OpenAiCompatibleProvider),
ChatGptCodex(ChatGptCodexProvider),
}
#[derive(Debug, Clone, Copy)]
pub struct ProviderRuntimeOptions {
pub reasoning_effort: ReasoningEffort,
pub fast_mode: bool,
}
impl ProviderClient {
pub fn from_config(config: &Config, options: ProviderRuntimeOptions) -> Result<Self> {
match config.active_provider.kind.as_str() {
DEFAULT_PROVIDER_KIND => {
let api_key = config.resolved_api_key()?;
let model_metadata = config.model_metadata.as_ref();
let reasoning_request_format = model_metadata
.map(|model| model.reasoning.request_format)
.unwrap_or_default();
let reasoning_supported = model_metadata
.map(|model| model.reasoning.supported)
.unwrap_or(false);
Ok(Self::OpenAiCompatible(OpenAiCompatibleProvider::new(
OpenAiCompatibleSettings {
model: config.model.clone(),
base_url: config.active_provider.base_url.clone(),
api_key,
reasoning_effort: options.reasoning_effort,
reasoning_request_format,
reasoning_supported,
},
)))
}
CHATGPT_CODEX_PROVIDER_KIND => Ok(Self::ChatGptCodex(ChatGptCodexProvider::new(
ChatGptCodexSettings {
model: config.model.clone(),
endpoint: config.active_provider.base_url.clone(),
reasoning_effort: options.reasoning_effort,
fast_mode: options.fast_mode,
},
))),
kind => bail!("unsupported provider kind `{kind}`"),
}
}
pub async fn complete(
&self,
messages: Vec<ModelMessage>,
tools: Vec<ToolSpec>,
tx: &mpsc::UnboundedSender<AgentEvent>,
) -> Result<CompletionResult> {
match self {
Self::OpenAiCompatible(provider) => provider.complete(messages, tools, tx).await,
Self::ChatGptCodex(provider) => provider.complete(messages, tools, tx).await,
}
}
}
+72 -3
View File
@@ -18,6 +18,7 @@ pub struct OpenAiCompatibleProvider {
api_key: String, api_key: String,
reasoning_effort: ReasoningEffort, reasoning_effort: ReasoningEffort,
reasoning_request_format: ReasoningRequestFormat, reasoning_request_format: ReasoningRequestFormat,
reasoning_supported: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -27,6 +28,7 @@ pub struct OpenAiCompatibleSettings {
pub api_key: String, pub api_key: String,
pub reasoning_effort: ReasoningEffort, pub reasoning_effort: ReasoningEffort,
pub reasoning_request_format: ReasoningRequestFormat, pub reasoning_request_format: ReasoningRequestFormat,
pub reasoning_supported: bool,
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -45,6 +47,7 @@ impl OpenAiCompatibleProvider {
api_key: settings.api_key, api_key: settings.api_key,
reasoning_effort: settings.reasoning_effort, reasoning_effort: settings.reasoning_effort,
reasoning_request_format: settings.reasoning_request_format, reasoning_request_format: settings.reasoning_request_format,
reasoning_supported: settings.reasoning_supported,
} }
} }
@@ -65,6 +68,7 @@ impl OpenAiCompatibleProvider {
&mut body, &mut body,
self.reasoning_effort, self.reasoning_effort,
self.reasoning_request_format, self.reasoning_request_format,
self.reasoning_supported,
); );
let resp = self let resp = self
.client .client
@@ -219,9 +223,17 @@ fn apply_reasoning_request(
body: &mut Value, body: &mut Value,
effort: ReasoningEffort, effort: ReasoningEffort,
format: ReasoningRequestFormat, format: ReasoningRequestFormat,
supported: bool,
) { ) {
let Some(effort) = effort.request_value() else { if !supported {
return; return;
}
let effort_str = match effort {
ReasoningEffort::Off => "none",
_ => match effort.request_value() {
Some(value) => value,
None => return,
},
}; };
let Value::Object(obj) = body else { let Value::Object(obj) = body else {
return; return;
@@ -230,11 +242,11 @@ fn apply_reasoning_request(
ReasoningRequestFormat::ReasoningEffort => { ReasoningRequestFormat::ReasoningEffort => {
obj.insert( obj.insert(
"reasoning_effort".to_string(), "reasoning_effort".to_string(),
Value::String(effort.to_string()), Value::String(effort_str.to_string()),
); );
} }
ReasoningRequestFormat::ReasoningObject => { ReasoningRequestFormat::ReasoningObject => {
obj.insert("reasoning".to_string(), json!({ "effort": effort })); obj.insert("reasoning".to_string(), json!({ "effort": effort_str }));
} }
} }
} }
@@ -316,3 +328,60 @@ fn chat_url(base: &str) -> String {
format!("{}/chat/completions", base.trim_end_matches('/')) format!("{}/chat/completions", base.trim_end_matches('/'))
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reasoning_effort_format_sends_none_when_off_and_supported() {
let mut body = json!({"model": "test"});
apply_reasoning_request(
&mut body,
ReasoningEffort::Off,
ReasoningRequestFormat::ReasoningEffort,
true,
);
assert_eq!(
body["reasoning_effort"],
Value::String("none".to_string())
);
}
#[test]
fn reasoning_object_format_sends_none_when_off_and_supported() {
let mut body = json!({"model": "test"});
apply_reasoning_request(
&mut body,
ReasoningEffort::Off,
ReasoningRequestFormat::ReasoningObject,
true,
);
assert_eq!(body["reasoning"], json!({ "effort": "none" }));
}
#[test]
fn reasoning_sends_nothing_when_unsupported_even_if_off() {
let mut body = json!({"model": "test"});
apply_reasoning_request(
&mut body,
ReasoningEffort::Off,
ReasoningRequestFormat::ReasoningEffort,
false,
);
assert!(body.get("reasoning_effort").is_none());
assert!(body.get("reasoning").is_none());
}
#[test]
fn reasoning_sends_nothing_when_unsupported_even_if_high() {
let mut body = json!({"model": "test"});
apply_reasoning_request(
&mut body,
ReasoningEffort::High,
ReasoningRequestFormat::ReasoningObject,
false,
);
assert!(body.get("reasoning").is_none());
}
}
+394 -28
View File
@@ -1,8 +1,11 @@
use crate::check; use crate::check;
use crate::cli::Cli; use crate::cli::Cli;
use crate::codex_auth;
use crate::config::{ use crate::config::{
self, ConfigFile, ModelDefinition, ModelsFile, ProviderDefinition, ProvidersFile, self, ConfigFile, FastModeMetadata, ModelDefinition, ModelsFile, ProviderDefinition,
ReasoningEffort, ReasoningMetadata, ReasoningRequestFormat, DEFAULT_PROVIDER_KIND, ProvidersFile, ReasoningEffort, ReasoningMetadata, ReasoningRequestFormat,
CHATGPT_CODEX_DEFAULT_MODEL, CHATGPT_CODEX_PROVIDER_ID, CHATGPT_CODEX_PROVIDER_KIND,
CHATGPT_CODEX_PROVIDER_NAME, CHATGPT_CODEX_RESPONSES_URL, DEFAULT_PROVIDER_KIND,
}; };
use crate::menu::{Menu, MenuItem, TextPrompt}; use crate::menu::{Menu, MenuItem, TextPrompt};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
@@ -18,6 +21,7 @@ use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetupMode { pub enum SetupMode {
Explicit, Explicit,
Login,
Auto, Auto,
} }
@@ -45,6 +49,23 @@ pub struct SetupSelection {
pub supports_reasoning: bool, pub supports_reasoning: bool,
} }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderLogoutCandidate {
pub id: String,
pub name: Option<String>,
pub default_model: Option<String>,
pub model_count: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogoutResult {
pub removed_provider_ids: Vec<String>,
pub removed_model_count: usize,
pub remaining_provider_count: usize,
pub active_provider: Option<String>,
pub active_model: Option<String>,
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct ModelsResponse { struct ModelsResponse {
data: Vec<ModelItem>, data: Vec<ModelItem>,
@@ -57,7 +78,12 @@ struct ModelItem {
fn print_banner() { fn print_banner() {
println!("Cassady setup"); println!("Cassady setup");
println!("Configure an OpenAI-compatible provider, API key environment variable, and model."); println!("Configure a provider, authentication source, and model.");
}
fn print_login_banner() {
println!("Cassady login");
println!("Add or update a provider, authentication source, and model.");
} }
fn section(title: &str) { fn section(title: &str) {
@@ -125,6 +151,12 @@ pub fn provider_catalog() -> Vec<ProviderCatalogEntry> {
base_url: "https://api.openai.com/v1", base_url: "https://api.openai.com/v1",
api_key_env: "OPENAI_API_KEY", api_key_env: "OPENAI_API_KEY",
}, },
ProviderCatalogEntry {
name: CHATGPT_CODEX_PROVIDER_NAME,
id: CHATGPT_CODEX_PROVIDER_ID,
base_url: CHATGPT_CODEX_RESPONSES_URL,
api_key_env: "",
},
ProviderCatalogEntry { ProviderCatalogEntry {
name: "xAI", name: "xAI",
id: "xai", id: "xai",
@@ -187,10 +219,16 @@ pub async fn run(cli: &Cli, mode: SetupMode) -> Result<SetupOutcome> {
fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?;
if !io::stdin().is_terminal() { if !io::stdin().is_terminal() {
bail!("setup is interactive; run `cass setup` in a terminal"); match mode {
SetupMode::Login => bail!("login is interactive; run `cass login` in a terminal"),
_ => bail!("setup is interactive; run `cass setup` in a terminal"),
}
} }
print_banner(); match mode {
SetupMode::Login => print_login_banner(),
_ => print_banner(),
}
match mode { match mode {
SetupMode::Explicit => { SetupMode::Explicit => {
@@ -206,6 +244,7 @@ pub async fn run(cli: &Cli, mode: SetupMode) -> Result<SetupOutcome> {
}); });
} }
} }
SetupMode::Login => {}
SetupMode::Auto => { SetupMode::Auto => {
println!(); println!();
hint("Cassady needs this before starting your first chat."); hint("Cassady needs this before starting your first chat.");
@@ -233,29 +272,129 @@ pub async fn run(cli: &Cli, mode: SetupMode) -> Result<SetupOutcome> {
let report = check::run(cli)?; let report = check::run(cli)?;
if report.has_errors() { if report.has_errors() {
if std::env::var(&active_api_key_env).is_err() { if !active_api_key_env.is_empty() && std::env::var(&active_api_key_env).is_err() {
section("Setup saved"); section(match mode {
SetupMode::Login => "Login saved",
_ => "Setup saved",
});
warn("Your active provider API key is not available in this shell."); warn("Your active provider API key is not available in this shell.");
hint(format!("Set it with: export {active_api_key_env}=...")); hint(format!("Set it with: export {active_api_key_env}=..."));
hint("Then run: cass"); hint("Then run: cass");
} else { } else {
section("Setup saved with issues"); section(match mode {
SetupMode::Login => "Login saved with issues",
_ => "Setup saved with issues",
});
print!("{}", report.render()); print!("{}", report.render());
hint("Run `cass setup` to try again or edit ~/.cass/config.json manually."); hint(match mode {
SetupMode::Login => {
"Run `cass login` to try again or edit ~/.cass/config.json manually."
}
_ => "Run `cass setup` to try again or edit ~/.cass/config.json manually.",
});
} }
return Ok(SetupOutcome { return Ok(SetupOutcome {
start_session: false, start_session: false,
}); });
} }
section("Setup complete"); section(match mode {
SetupMode::Login => "Login complete",
_ => "Setup complete",
});
success("Configuration saved and validated"); success("Configuration saved and validated");
info("Starting your first Cassady session…"); match mode {
SetupMode::Login => info("Provider configuration is ready."),
_ => info("Starting your first Cassady session…"),
}
Ok(SetupOutcome { Ok(SetupOutcome {
start_session: true, start_session: true,
}) })
} }
pub fn logout(root: &Path) -> Result<LogoutResult> {
fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
if !io::stdin().is_terminal() {
bail!("logout is interactive; run `cass logout` in a terminal");
}
let candidates = configured_providers(root)?;
if candidates.is_empty() {
bail!("no providers are configured; run `cass login` to add one");
}
section("Cassady logout");
warn("This removes provider entries from Cassady config only. It does not delete environment variables or provider accounts.");
let items = candidates
.iter()
.map(|candidate| {
let label = candidate.name.as_deref().unwrap_or(&candidate.id);
let model = candidate
.default_model
.as_deref()
.unwrap_or("no default model");
MenuItem::with_detail(
label.to_string(),
format!(
"{} · {} · {} model{}",
candidate.id,
model,
candidate.model_count,
if candidate.model_count == 1 { "" } else { "s" }
),
)
})
.collect();
let selected =
Menu::new("Remove saved providers", items).select_many(&BTreeSet::new(), true)?;
let provider_ids = selected
.into_iter()
.map(|idx| candidates[idx].id.clone())
.collect::<Vec<_>>();
let label = provider_ids.join(", ");
if !ask_yes_no(
&format!("Remove {label} and associated model entries?"),
false,
)? {
println!("Logout cancelled.");
return Ok(LogoutResult {
removed_provider_ids: Vec::new(),
removed_model_count: 0,
remaining_provider_count: candidates.len(),
active_provider: None,
active_model: None,
});
}
let result = remove_providers(root, &provider_ids)?;
if result.removed_provider_ids.is_empty() {
println!("No providers removed.");
} else {
success(format!(
"Removed {} provider{} and {} model entr{}",
result.removed_provider_ids.len(),
if result.removed_provider_ids.len() == 1 {
""
} else {
"s"
},
result.removed_model_count,
if result.removed_model_count == 1 {
"y"
} else {
"ies"
}
));
if let Some(provider) = &result.active_provider {
let model = result.active_model.as_deref().unwrap_or("no default model");
info(format!("Active provider is now {provider} ({model})"));
} else {
warn("No providers remain. Run `cass login` before starting a chat.");
}
}
Ok(result)
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct ChosenProvider { struct ChosenProvider {
name: String, name: String,
@@ -344,24 +483,39 @@ async fn configure_provider(
key_value("id", &provider.id); key_value("id", &provider.id);
key_value("endpoint", &provider.base_url); key_value("endpoint", &provider.base_url);
let api_key_env = ask_default("API key environment variable", &provider.api_key_env)?; let (api_key_env, api_key) = if is_chatgpt_codex_provider(&provider.id) {
if !looks_like_env_var(&api_key_env) { info(
warn(format!( "ChatGPT Codex uses your local Codex login instead of an API-key environment variable.",
"`{api_key_env}` is an unusual environment variable name. Continuing." );
)); let status = codex_auth::check_codex_auth();
} if status.is_usable() {
let api_key = match std::env::var(&api_key_env) { success(format!("Codex auth: {}", status.summary()));
Ok(value) if !value.is_empty() => { } else {
success(format!("{api_key_env} is set")); warn(format!("Codex auth: {}", status.summary()));
Some(value) hint(status.recovery_hint());
} }
_ => { (String::new(), None)
} else {
let api_key_env = ask_default("API key environment variable", &provider.api_key_env)?;
if !looks_like_env_var(&api_key_env) {
warn(format!( warn(format!(
"{api_key_env} is not set in this shell. Setup can still be saved." "`{api_key_env}` is an unusual environment variable name. Continuing."
)); ));
hint(format!("Later, run: export {api_key_env}=..."));
None
} }
let api_key = match std::env::var(&api_key_env) {
Ok(value) if !value.is_empty() => {
success(format!("{api_key_env} is set"));
Some(value)
}
_ => {
warn(format!(
"{api_key_env} is not set in this shell. Setup can still be saved."
));
hint(format!("Later, run: export {api_key_env}=..."));
None
}
};
(api_key_env, api_key)
}; };
let model_id = choose_model(&provider, api_key.as_deref()).await?; let model_id = choose_model(&provider, api_key.as_deref()).await?;
@@ -424,6 +578,15 @@ fn choose_active_provider(selections: &[SetupSelection]) -> Result<usize> {
async fn choose_model(provider: &ChosenProvider, api_key: Option<&str>) -> Result<String> { async fn choose_model(provider: &ChosenProvider, api_key: Option<&str>) -> Result<String> {
section("Model"); section("Model");
if is_chatgpt_codex_provider(&provider.id) {
if let Some(model) = codex_auth::read_codex_default_model() {
success(format!("Found Codex default model: {model}"));
return ask_default("Model id", &model);
}
warn("Could not find a model in local Codex config. Using a safe default; edit it if needed.");
return ask_default("Model id", CHATGPT_CODEX_DEFAULT_MODEL);
}
let Some(api_key) = api_key else { let Some(api_key) = api_key else {
warn("Model discovery was skipped because the API key is not available in this shell."); warn("Model discovery was skipped because the API key is not available in this shell.");
hint("Enter the model id manually now; Cassady will use it after the key is exported."); hint("Enter the model id manually now; Cassady will use it after the key is exported.");
@@ -538,7 +701,9 @@ pub fn apply_setups(root: &Path, selections: &[SetupSelection], active_index: us
for selection in selections { for selection in selections {
validate_provider_id(&selection.provider_id)?; validate_provider_id(&selection.provider_id)?;
validate_base_url(&selection.base_url)?; validate_base_url(&selection.base_url)?;
if selection.api_key_env.trim().is_empty() { if !is_chatgpt_codex_provider(&selection.provider_id)
&& selection.api_key_env.trim().is_empty()
{
bail!("API key environment variable must not be empty"); bail!("API key environment variable must not be empty");
} }
if selection.model_id.trim().is_empty() { if selection.model_id.trim().is_empty() {
@@ -565,13 +730,207 @@ pub fn apply_setups(root: &Path, selections: &[SetupSelection], active_index: us
Ok(()) Ok(())
} }
pub fn configured_providers(root: &Path) -> Result<Vec<ProviderLogoutCandidate>> {
let providers = load_providers_or_empty(root)?;
let models = load_models_or_empty(root)?;
Ok(providers
.providers
.into_iter()
.map(|provider| {
let model_count = models
.models
.iter()
.filter(|model| model.provider == provider.id)
.count();
ProviderLogoutCandidate {
id: provider.id,
name: provider.name,
default_model: provider.default_model,
model_count,
}
})
.collect())
}
pub fn remove_providers(root: &Path, provider_ids: &[String]) -> Result<LogoutResult> {
if provider_ids.is_empty() {
bail!("select at least one provider to remove");
}
let selected: BTreeSet<String> = provider_ids
.iter()
.map(|id| id.trim().to_string())
.collect();
if selected.iter().any(|id| id.is_empty()) {
bail!("provider id must not be empty");
}
fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
let mut config_file = load_config_or_default(root)?;
let mut providers = load_providers_or_empty(root)?;
let mut models = load_models_or_empty(root)?;
let existing: BTreeSet<String> = providers
.providers
.iter()
.map(|provider| provider.id.clone())
.collect();
for id in &selected {
if !existing.contains(id) {
bail!("provider `{id}` is not configured");
}
}
let removed_provider_ids = providers
.providers
.iter()
.filter(|provider| selected.contains(&provider.id))
.map(|provider| provider.id.clone())
.collect::<Vec<_>>();
providers
.providers
.retain(|provider| !selected.contains(&provider.id));
let before_models = models.models.len();
models
.models
.retain(|model| !selected.contains(&model.provider));
let removed_model_count = before_models - models.models.len();
repair_active_defaults(&mut config_file, &providers, &models);
write_json_pretty(&config::providers_path(root), &providers)?;
write_json_pretty(&config::models_path(root), &models)?;
write_json_pretty(&config::config_path(root), &config_file)?;
Ok(LogoutResult {
removed_provider_ids,
removed_model_count,
remaining_provider_count: providers.providers.len(),
active_provider: config_file.default_provider,
active_model: config_file.default_model,
})
}
fn repair_active_defaults(
config_file: &mut ConfigFile,
providers: &ProvidersFile,
models: &ModelsFile,
) {
if providers.providers.is_empty() {
config_file.default_provider = None;
config_file.default_model = None;
config_file.default_reasoning_effort = None;
return;
}
let current_provider = config_file
.default_provider
.as_ref()
.filter(|id| {
providers
.providers
.iter()
.any(|provider| provider.id == **id)
})
.cloned();
let provider_id =
current_provider.unwrap_or_else(|| choose_provider_with_model(providers, models));
let model = config_file
.default_model
.as_ref()
.filter(|model| model_belongs_to_provider(models, &provider_id, model))
.cloned()
.or_else(|| default_model_for_provider(providers, models, &provider_id));
config_file.default_provider = Some(provider_id);
config_file.default_model = model;
if let Some(effort) = config_file.default_reasoning_effort {
if let Some(model_id) = config_file.default_model.as_deref() {
let model = models.models.iter().find(|model| {
model.provider == config_file.default_provider.as_deref().unwrap_or_default()
&& model.id == model_id
});
config_file.default_reasoning_effort = Some(effort.clamp_for_model(model));
}
}
}
fn choose_provider_with_model(providers: &ProvidersFile, models: &ModelsFile) -> String {
providers
.providers
.iter()
.find(|provider| {
provider
.default_model
.as_ref()
.is_some_and(|model| model_belongs_to_provider(models, &provider.id, model))
|| provider
.models
.iter()
.any(|model| model_belongs_to_provider(models, &provider.id, model))
|| models
.models
.iter()
.any(|model| model.provider == provider.id)
})
.or_else(|| providers.providers.first())
.map(|provider| provider.id.clone())
.unwrap_or_default()
}
fn default_model_for_provider(
providers: &ProvidersFile,
models: &ModelsFile,
provider_id: &str,
) -> Option<String> {
let provider = providers
.providers
.iter()
.find(|provider| provider.id == provider_id)?;
provider
.default_model
.as_ref()
.filter(|model| model_belongs_to_provider(models, provider_id, model))
.cloned()
.or_else(|| {
provider
.models
.iter()
.find(|model| model_belongs_to_provider(models, provider_id, model))
.cloned()
})
.or_else(|| {
models
.models
.iter()
.find(|model| model.provider == provider_id)
.map(|model| model.id.clone())
})
}
fn model_belongs_to_provider(models: &ModelsFile, provider_id: &str, model_id: &str) -> bool {
models
.models
.iter()
.any(|model| model.provider == provider_id && model.id == model_id)
}
fn upsert_provider(providers: &mut ProvidersFile, selection: &SetupSelection) { fn upsert_provider(providers: &mut ProvidersFile, selection: &SetupSelection) {
let is_codex = is_chatgpt_codex_provider(&selection.provider_id);
let new_entry = ProviderDefinition { let new_entry = ProviderDefinition {
id: selection.provider_id.clone(), id: selection.provider_id.clone(),
name: Some(selection.provider_name.clone()), name: Some(selection.provider_name.clone()),
kind: DEFAULT_PROVIDER_KIND.to_string(), kind: if is_codex {
CHATGPT_CODEX_PROVIDER_KIND.to_string()
} else {
DEFAULT_PROVIDER_KIND.to_string()
},
base_url: selection.base_url.clone(), base_url: selection.base_url.clone(),
api_key: format!("${}", selection.api_key_env), api_key: if is_codex {
String::new()
} else {
format!("${}", selection.api_key_env)
},
default_model: Some(selection.model_id.clone()), default_model: Some(selection.model_id.clone()),
models: vec![selection.model_id.clone()], models: vec![selection.model_id.clone()],
}; };
@@ -611,6 +970,9 @@ fn upsert_model(models: &mut ModelsFile, selection: &SetupSelection) {
}, },
request_format: ReasoningRequestFormat::ReasoningEffort, request_format: ReasoningRequestFormat::ReasoningEffort,
}, },
fast_mode: FastModeMetadata {
supported: is_chatgpt_codex_provider(&selection.provider_id),
},
}; };
if let Some(existing) = models.models.iter_mut().find(|existing| { if let Some(existing) = models.models.iter_mut().find(|existing| {
@@ -664,6 +1026,10 @@ fn validate_base_url(base_url: &str) -> Result<()> {
} }
} }
fn is_chatgpt_codex_provider(id: &str) -> bool {
id == CHATGPT_CODEX_PROVIDER_ID
}
fn looks_like_env_var(value: &str) -> bool { fn looks_like_env_var(value: &str) -> bool {
let mut chars = value.chars(); let mut chars = value.chars();
let Some(first) = chars.next() else { let Some(first) = chars.next() else {
+84 -5
View File
@@ -5,7 +5,7 @@ use crate::ui::theme;
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag, TagEnd}; use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag, TagEnd};
use ratatui::layout::{Constraint, Direction, Layout}; use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::prelude::*; use ratatui::prelude::*;
use ratatui::widgets::{Paragraph, Wrap}; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use std::path::Path; use std::path::Path;
use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthChar;
@@ -26,7 +26,20 @@ pub struct TranscriptBlock {
pub content: String, pub content: String,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct OverlayView {
pub title: String,
pub help: String,
pub items: Vec<OverlayItem>,
pub selected: usize,
}
#[derive(Debug, Clone)]
pub struct OverlayItem {
pub label: String,
pub detail: String,
}
pub struct RenderState<'a> { pub struct RenderState<'a> {
pub app_name: &'a str, pub app_name: &'a str,
pub chat_id: &'a str, pub chat_id: &'a str,
@@ -40,8 +53,10 @@ pub struct RenderState<'a> {
pub show_full_tools: bool, pub show_full_tools: bool,
pub show_reasoning: bool, pub show_reasoning: bool,
pub reasoning_effort: ReasoningEffort, pub reasoning_effort: ReasoningEffort,
pub fast_mode_active: bool,
pub scroll: u16, pub scroll: u16,
pub autofill: Option<&'a AutoFillMenu>, pub autofill: Option<&'a AutoFillMenu>,
pub overlay: Option<&'a OverlayView>,
} }
pub fn render(f: &mut Frame<'_>, state: &RenderState<'_>) { pub fn render(f: &mut Frame<'_>, state: &RenderState<'_>) {
@@ -74,6 +89,10 @@ pub fn render(f: &mut Frame<'_>, state: &RenderState<'_>) {
let footer = truncate_end(&footer_text(state), chunks[3].width as usize); let footer = truncate_end(&footer_text(state), chunks[3].width as usize);
f.render_widget(Paragraph::new(footer).style(theme::footer()), chunks[3]); f.render_widget(Paragraph::new(footer).style(theme::footer()), chunks[3]);
if let Some(overlay) = state.overlay {
render_overlay(f, f.area(), overlay);
}
} }
pub fn transcript_area(area: Rect, input: &str) -> Rect { pub fn transcript_area(area: Rect, input: &str) -> Rect {
@@ -116,6 +135,61 @@ fn autofill_height(menu: Option<&AutoFillMenu>) -> u16 {
menu.map(|menu| menu.items.len().min(6) as u16).unwrap_or(0) menu.map(|menu| menu.items.len().min(6) as u16).unwrap_or(0)
} }
fn render_overlay(f: &mut Frame<'_>, area: Rect, overlay: &OverlayView) {
let max_width = area.width.max(1);
let preferred_width = area.width.saturating_mul(4).saturating_div(5).max(40);
let width = preferred_width.min(max_width);
let max_height = area.height.saturating_sub(2).max(1);
let preferred_height = (overlay.items.len() as u16 + 5).max(8);
let height = preferred_height.min(max_height);
let x = area.x + area.width.saturating_sub(width) / 2;
let y = area.y + area.height.saturating_sub(height) / 2;
let rect = Rect::new(x, y, width, height);
f.render_widget(Clear, rect);
let block = Block::default()
.title(overlay.title.clone())
.borders(Borders::ALL)
.style(theme::menu());
let inner = block.inner(rect);
f.render_widget(block, rect);
let visible = inner.height.saturating_sub(2) as usize;
let selected = overlay.selected.min(overlay.items.len().saturating_sub(1));
let start = if selected >= visible && visible > 0 {
selected + 1 - visible
} else {
0
};
let end = (start + visible).min(overlay.items.len());
let mut lines = Vec::new();
lines.push(Line::styled(
truncate_end(&overlay.help, inner.width as usize),
Style::default().fg(Color::DarkGray),
));
for idx in start..end {
let item = &overlay.items[idx];
let marker = if idx == selected { "›" } else { " " };
let mut text = format!("{marker} {}", item.label);
if !item.detail.is_empty() {
text.push_str(" ");
text.push_str(&item.detail);
}
let style = if idx == selected {
theme::selection()
} else {
theme::menu()
};
lines.push(Line::styled(
truncate_end(&text, inner.width as usize),
style,
));
}
f.render_widget(
Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false }),
inner,
);
}
fn render_autofill_menu(f: &mut Frame<'_>, area: Rect, menu: &AutoFillMenu) { fn render_autofill_menu(f: &mut Frame<'_>, area: Rect, menu: &AutoFillMenu) {
if area.height == 0 || menu.items.is_empty() { if area.height == 0 || menu.items.is_empty() {
return; return;
@@ -527,9 +601,6 @@ fn ratatui_wrapped_row_count(line: &str, content_width: usize) -> usize {
non_whitespace_previous = !is_whitespace; non_whitespace_previous = !is_whitespace;
} }
if !pending_line_has_symbols && word_symbols == 0 && whitespace_symbols > 0 {
rows = rows.saturating_add(1);
}
if whitespace_symbols > 0 || word_symbols > 0 { if whitespace_symbols > 0 || word_symbols > 0 {
pending_line_has_symbols = true; pending_line_has_symbols = true;
} }
@@ -654,6 +725,9 @@ fn footer_text(state: &RenderState<'_>) -> String {
parts.push("tools:full".into()); parts.push("tools:full".into());
} }
parts.push(format!("reasoning:{}", state.reasoning_effort)); parts.push(format!("reasoning:{}", state.reasoning_effort));
if state.fast_mode_active {
parts.push("fast".into());
}
if state.show_reasoning { if state.show_reasoning {
parts.push("reasoning:visible".into()); parts.push("reasoning:visible".into());
} }
@@ -920,6 +994,11 @@ mod tests {
assert_eq!(max_transcript_scroll(&transcript, false, false, area), 0); assert_eq!(max_transcript_scroll(&transcript, false, false, area), 0);
} }
#[test]
fn whitespace_only_line_counts_as_one_wrapped_row() {
assert_eq!(ratatui_wrapped_row_count(" ", 80), 1);
}
#[test] #[test]
fn input_height_wraps_long_line() { fn input_height_wraps_long_line() {
// A single long line with no newlines should occupy more than 1 row // A single long line with no newlines should occupy more than 1 row
+23
View File
@@ -27,3 +27,26 @@ pub fn leave(mut terminal: CassTerminal) -> Result<()> {
terminal.show_cursor()?; terminal.show_cursor()?;
Ok(()) Ok(())
} }
pub fn suspend(terminal: &mut CassTerminal) -> Result<()> {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
}
pub fn resume(terminal: &mut CassTerminal) -> Result<()> {
enable_raw_mode()?;
execute!(
terminal.backend_mut(),
EnterAlternateScreen,
EnableMouseCapture
)?;
terminal.clear()?;
terminal.hide_cursor()?;
Ok(())
}
+1255
View File
File diff suppressed because it is too large Load Diff
+56
View File
@@ -123,6 +123,62 @@ async fn reasoning_effort_supports_reasoning_object_format() {
.unwrap(); .unwrap();
} }
#[tokio::test]
async fn fast_mode_preference_does_not_change_openai_compatible_request() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.respond_with(sse(
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Done.\"}}]}\r\n\r\ndata: [DONE]\r\n\r\n",
))
.expect(1)
.mount(&server)
.await;
let root = tempdir().unwrap();
let cwd = tempdir().unwrap();
let docs = tempdir().unwrap();
let config = Config {
root: root.path().to_path_buf(),
docs_dir: docs.path().to_path_buf(),
model: "test-model".into(),
default_fast_mode: true,
active_provider: cassady::config::ResolvedProviderConfig {
base_url: server.uri(),
api_key: "test-key".into(),
..Config::default().active_provider
},
..Config::default()
};
let conversation = Conversation::create(
&config.conversations_dir(),
&config.model,
cwd.path(),
"base prompt".into(),
)
.unwrap();
let (tx, _rx) = mpsc::unbounded_channel::<AgentEvent>();
run_turn(
conversation,
"stay compatible".into(),
AgentSettings {
config,
cwd: cwd.path().to_path_buf(),
mode: AccessMode::ReadOnly,
reasoning_effort: ReasoningEffort::Off,
},
tx,
)
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
let body = String::from_utf8_lossy(&requests[0].body);
assert!(!body.contains("\"effort\":\"minimal\""));
assert!(!body.contains("\"fast_mode\""));
}
#[tokio::test] #[tokio::test]
async fn reasoning_is_streamed_persisted_and_sent_back() { async fn reasoning_is_streamed_persisted_and_sent_back() {
let server = MockServer::start().await; let server = MockServer::start().await;
+201
View File
@@ -47,6 +47,7 @@ fn default_provider_and_model_files_are_created() {
.unwrap(); .unwrap();
assert_eq!(models.models[0].provider, "fireworks"); assert_eq!(models.models[0].provider, "fireworks");
assert!(models.models[0].reasoning.supported); assert!(models.models[0].reasoning.supported);
assert!(!models.models[0].fast_mode.supported);
assert_eq!( assert_eq!(
models.models[0].reasoning.default_effort, models.models[0].reasoning.default_effort,
ReasoningEffort::Medium ReasoningEffort::Medium
@@ -127,6 +128,206 @@ fn reasoning_defaults_to_supported_medium_for_model_metadata() {
); );
} }
#[test]
fn fast_mode_defaults_to_off_and_unsupported() {
let model: config::ModelDefinition = serde_json::from_str(
r#"{
"id": "test-model",
"provider": "test-provider"
}
"#,
)
.unwrap();
assert!(!model.fast_mode.supported);
let root = tempdir().unwrap();
let cfg = Config::load_from_root_with_docs(
root.path().to_path_buf(),
root.path().join("docs"),
&cli(),
)
.unwrap();
let state = cfg.fast_mode_state();
assert!(!state.preferred);
assert!(!state.supported);
assert!(!state.active);
}
#[test]
fn fast_mode_preference_persists_without_losing_config_fields() {
let root = tempdir().unwrap();
std::fs::write(
root.path().join("config.json"),
r#"{
"default_access_mode": "workspace-edit",
"show_reasoning": true
}
"#,
)
.unwrap();
config::save_fast_mode_preference(root.path(), true).unwrap();
let cfg = Config::load_from_root_with_docs(
root.path().to_path_buf(),
root.path().join("docs"),
&cli(),
)
.unwrap();
assert!(cfg.default_fast_mode);
assert!(cfg.show_reasoning);
assert_eq!(cfg.default_access_mode.to_string(), "workspace-edit");
}
#[test]
fn fast_mode_state_is_active_for_supported_codex_model() {
let root = tempdir().unwrap();
std::fs::write(
root.path().join("providers.json"),
r#"{
"providers": [
{
"id": "chatgpt-codex",
"name": "ChatGPT Codex",
"kind": "chatgpt-codex",
"base_url": "https://chatgpt.com/backend-api/codex/responses",
"api_key": "",
"default_model": "gpt-5.5",
"models": ["gpt-5.5"]
}
]
}
"#,
)
.unwrap();
std::fs::write(
root.path().join("models.json"),
r#"{
"models": [
{
"id": "gpt-5.5",
"provider": "chatgpt-codex",
"fast_mode": { "supported": true }
}
]
}
"#,
)
.unwrap();
std::fs::write(
root.path().join("config.json"),
r#"{
"default_provider": "chatgpt-codex",
"default_model": "gpt-5.5",
"default_fast_mode": true
}
"#,
)
.unwrap();
let cfg = Config::load_from_root_with_docs(
root.path().to_path_buf(),
root.path().join("docs"),
&cli(),
)
.unwrap();
let state = cfg.fast_mode_state();
assert!(state.preferred);
assert!(state.supported);
assert!(state.active);
}
#[test]
fn fast_mode_state_is_active_for_chatgpt_codex_even_with_legacy_metadata() {
let root = tempdir().unwrap();
std::fs::write(
root.path().join("providers.json"),
r#"{
"providers": [
{
"id": "chatgpt-codex",
"name": "ChatGPT Codex",
"kind": "chatgpt-codex",
"base_url": "https://chatgpt.com/backend-api/codex/responses",
"api_key": "",
"default_model": "gpt-5.5",
"models": ["gpt-5.5"]
}
]
}
"#,
)
.unwrap();
std::fs::write(
root.path().join("models.json"),
r#"{
"models": [
{
"id": "gpt-5.5",
"provider": "chatgpt-codex",
"fast_mode": { "supported": false }
}
]
}
"#,
)
.unwrap();
std::fs::write(
root.path().join("config.json"),
r#"{
"default_provider": "chatgpt-codex",
"default_model": "gpt-5.5",
"default_fast_mode": true
}
"#,
)
.unwrap();
let cfg = Config::load_from_root_with_docs(
root.path().to_path_buf(),
root.path().join("docs"),
&cli(),
)
.unwrap();
let state = cfg.fast_mode_state();
assert!(state.preferred);
assert!(state.supported);
assert!(state.active);
}
#[test]
fn validation_accepts_chatgpt_codex_without_api_key() {
let providers = ProvidersFile {
providers: vec![ProviderDefinition {
id: config::CHATGPT_CODEX_PROVIDER_ID.into(),
name: Some(config::CHATGPT_CODEX_PROVIDER_NAME.into()),
kind: config::CHATGPT_CODEX_PROVIDER_KIND.into(),
base_url: config::CHATGPT_CODEX_RESPONSES_URL.into(),
api_key: String::new(),
default_model: Some(config::CHATGPT_CODEX_DEFAULT_MODEL.into()),
models: vec![config::CHATGPT_CODEX_DEFAULT_MODEL.into()],
}],
};
let models = ModelsFile {
models: vec![config::ModelDefinition {
id: config::CHATGPT_CODEX_DEFAULT_MODEL.into(),
provider: config::CHATGPT_CODEX_PROVIDER_ID.into(),
display_name: None,
context_length: None,
max_output_tokens: None,
supports_tools: true,
supports_streaming: true,
reasoning: Default::default(),
fast_mode: Default::default(),
}],
};
let summary = config::validate_registries(None, &providers, &models);
assert!(summary.errors.is_empty(), "{:?}", summary.errors);
}
#[test] #[test]
fn validation_rejects_duplicate_provider_ids() { fn validation_rejects_duplicate_provider_ids() {
let providers = ProvidersFile { let providers = ProvidersFile {
+19
View File
@@ -23,3 +23,22 @@ fn conversation_appends_loads_and_lists_by_cwd() {
assert_eq!(chats[0].id, convo.id); assert_eq!(chats[0].id, convo.id);
assert_eq!(chats[0].first_user_preview, "hello world"); assert_eq!(chats[0].first_user_preview, "hello world");
} }
#[test]
fn legacy_meta_without_branch_fields_still_loads() {
let root = tempdir().unwrap();
let id = "legacy";
std::fs::write(
root.path().join(format!("{id}.jsonl")),
r#"{"type":"meta","chat_id":"legacy","created_at":"now","model":"m","cwd":"/tmp"}
{"type":"system","content":"base"}
"#,
)
.unwrap();
let (loaded, warning) = Conversation::load(root.path(), id).unwrap();
assert!(warning.is_none());
let meta = loaded.meta().unwrap();
assert_eq!(meta.parent_chat_id, None);
assert_eq!(meta.branch_from, None);
}
+1
View File
@@ -59,6 +59,7 @@ fn expected_bundled_docs_exist() {
"configuration.md", "configuration.md",
"providers.md", "providers.md",
"access-modes.md", "access-modes.md",
"embedding.md",
"workflows.md", "workflows.md",
"troubleshooting.md", "troubleshooting.md",
"platforms.md", "platforms.md",
+315
View File
@@ -0,0 +1,315 @@
use cassady::access::AccessMode;
use cassady::config::ReasoningEffort;
use cassady::conversation::Record;
use cassady::embedding::{Event, SessionBuilder};
use serde_json::json;
use tempfile::tempdir;
use wiremock::matchers::{body_string_contains, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn sse(body: &str) -> ResponseTemplate {
ResponseTemplate::new(200).set_body_raw(body.as_bytes().to_vec(), "text/event-stream")
}
fn content_sse(content: &str) -> ResponseTemplate {
sse(&format!(
"data: {{\"choices\":[{{\"index\":0,\"delta\":{{\"content\":{}}}}}]}}\r\n\r\ndata: [DONE]\r\n\r\n",
serde_json::to_string(content).unwrap()
))
}
fn tool_call_sse(id: &str, name: &str, arguments: &str) -> ResponseTemplate {
sse(&format!(
"data: {{\"choices\":[{{\"index\":0,\"delta\":{{\"tool_calls\":[{{\"index\":0,\"id\":\"{id}\",\"type\":\"function\",\"function\":{{\"name\":\"{name}\",\"arguments\":{}}}}}]}}}}]}}\r\n\r\ndata: [DONE]\r\n\r\n",
serde_json::to_string(arguments).unwrap()
))
}
fn write_test_config(root: &std::path::Path, base_url: &str) {
std::fs::write(
root.join("providers.json"),
serde_json::to_string_pretty(&json!({
"providers": [{
"id": "test-provider",
"kind": "openai-compatible",
"base_url": base_url,
"api_key": "test-key",
"default_model": "test-model",
"models": ["test-model"]
}]
}))
.unwrap(),
)
.unwrap();
std::fs::write(
root.join("models.json"),
serde_json::to_string_pretty(&json!({
"models": [{
"id": "test-model",
"provider": "test-provider",
"context_length": 128,
"max_output_tokens": 64,
"reasoning": {
"supported": true,
"required": false,
"default_effort": "off",
"request_format": "reasoning_effort"
}
}]
}))
.unwrap(),
)
.unwrap();
std::fs::write(
root.join("config.json"),
serde_json::to_string_pretty(&json!({
"default_provider": "test-provider",
"default_model": "test-model",
"default_reasoning_effort": "off"
}))
.unwrap(),
)
.unwrap();
}
#[tokio::test]
async fn embedded_session_runs_turn_and_streams_events() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.respond_with(content_sse("Hello from embedded Cassady."))
.expect(1)
.mount(&server)
.await;
let root = tempdir().unwrap();
let cwd = tempdir().unwrap();
write_test_config(root.path(), &server.uri());
let session = SessionBuilder::new()
.config_root(root.path())
.cwd(cwd.path())
.access_mode(AccessMode::ReadOnly)
.reasoning_effort(ReasoningEffort::Off)
.build()
.await
.unwrap();
assert_eq!(session.model(), "test-model");
assert_eq!(session.access_mode(), AccessMode::ReadOnly);
let mut turn = session.start_turn("say hi").await.unwrap();
let mut streamed = String::new();
while let Some(event) = turn.next_event().await.unwrap() {
match event {
Event::AssistantChunk(chunk) => streamed.push_str(&chunk),
Event::Finished => break,
_ => {}
}
}
let session = turn.finish().await.unwrap();
assert_eq!(streamed, "Hello from embedded Cassady.");
assert!(session.records().iter().any(|record| matches!(
record,
Record::Assistant { content, .. } if content == "Hello from embedded Cassady."
)));
assert!(session.conversation_path().is_file());
}
#[tokio::test]
async fn builder_overrides_config_for_model_endpoint_key_mode_and_reasoning() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.and(body_string_contains("\"model\":\"test-model\""))
.and(body_string_contains("\"reasoning_effort\":\"low\""))
.respond_with(content_sse("Overrides worked."))
.expect(1)
.mount(&server)
.await;
let root = tempdir().unwrap();
let cwd = tempdir().unwrap();
write_test_config(root.path(), "https://wrong.example/v1");
let env_name = "CASSADY_EMBEDDING_TEST_KEY";
let old = std::env::var(env_name).ok();
std::env::set_var(env_name, "test-key-from-env");
let session = SessionBuilder::new()
.config_root(root.path())
.cwd(cwd.path())
.access_mode(AccessMode::WorkspaceEdit)
.model("test-model")
.base_url(server.uri())
.api_key_env(env_name)
.reasoning_effort(ReasoningEffort::Low)
.build()
.await
.unwrap();
assert_eq!(session.access_mode(), AccessMode::WorkspaceEdit);
assert_eq!(session.reasoning_effort(), ReasoningEffort::Low);
let mut turn = session.start_turn("check overrides").await.unwrap();
while let Some(event) = turn.next_event().await.unwrap() {
if matches!(event, Event::Finished) {
break;
}
}
let _session = turn.finish().await.unwrap();
if let Some(old) = old {
std::env::set_var(env_name, old);
} else {
std::env::remove_var(env_name);
}
}
#[tokio::test]
async fn embedded_session_can_resume_existing_conversation() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.respond_with(content_sse("First turn."))
.expect(1)
.mount(&server)
.await;
let root = tempdir().unwrap();
let cwd = tempdir().unwrap();
write_test_config(root.path(), &server.uri());
let session = SessionBuilder::new()
.config_root(root.path())
.cwd(cwd.path())
.access_mode(AccessMode::ReadOnly)
.build()
.await
.unwrap();
let mut turn = session.start_turn("first").await.unwrap();
while let Some(event) = turn.next_event().await.unwrap() {
if matches!(event, Event::Finished) {
break;
}
}
let session = turn.finish().await.unwrap();
let id = session.id().to_string();
let record_count = session.records().len();
let resumed = SessionBuilder::new()
.config_root(root.path())
.cwd(cwd.path())
.resume(&id)
.await
.unwrap();
assert_eq!(resumed.id(), id);
assert_eq!(resumed.records().len(), record_count);
assert!(resumed.resume_warning().is_none());
}
#[tokio::test]
async fn embedded_approval_flow_can_approve_shell() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.and(body_string_contains("exit code: 0"))
.respond_with(content_sse("Approved shell."))
.with_priority(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.respond_with(tool_call_sse(
"call_shell",
"shell",
r#"{"command":"touch marker"}"#,
))
.with_priority(10)
.expect(1)
.mount(&server)
.await;
let root = tempdir().unwrap();
let cwd = tempdir().unwrap();
write_test_config(root.path(), &server.uri());
let marker = cwd.path().join("marker");
let session = SessionBuilder::new()
.config_root(root.path())
.cwd(cwd.path())
.access_mode(AccessMode::WorkspaceEdit)
.build()
.await
.unwrap();
let mut turn = session.start_turn("run shell").await.unwrap();
let mut saw_request = false;
let mut saw_resolved = false;
while let Some(event) = turn.next_event().await.unwrap() {
match event {
Event::ApprovalRequested(request) => {
saw_request = true;
assert_eq!(request.name, "shell");
assert!(!marker.exists());
turn.approve(&request.request_id).unwrap();
}
Event::ApprovalResolved { approved, .. } => {
saw_resolved = approved;
}
Event::Finished => break,
_ => {}
}
}
let session = turn.finish().await.unwrap();
assert!(saw_request);
assert!(saw_resolved);
assert!(marker.exists());
assert!(session.records().iter().any(|record| matches!(
record,
Record::Tool { name, ok, content, .. }
if name == "shell" && *ok && content.contains("exit code: 0")
)));
}
#[tokio::test]
async fn read_only_embedding_does_not_advertise_mutating_tools() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/chat/completions"))
.respond_with(content_sse("Readonly."))
.expect(1)
.mount(&server)
.await;
let root = tempdir().unwrap();
let cwd = tempdir().unwrap();
write_test_config(root.path(), &server.uri());
let session = SessionBuilder::new()
.config_root(root.path())
.cwd(cwd.path())
.access_mode(AccessMode::ReadOnly)
.build()
.await
.unwrap();
let mut turn = session.start_turn("inspect only").await.unwrap();
while let Some(event) = turn.next_event().await.unwrap() {
if matches!(event, Event::Finished) {
break;
}
}
let _session = turn.finish().await.unwrap();
let requests = server.received_requests().await.unwrap();
let body = String::from_utf8_lossy(&requests[0].body);
assert!(body.contains("\"name\":\"ls\""));
assert!(body.contains("\"name\":\"read\""));
assert!(body.contains("\"name\":\"grep\""));
assert!(!body.contains("\"name\":\"write\""));
assert!(!body.contains("\"name\":\"edit\""));
assert!(!body.contains("\"name\":\"shell\""));
}
+174 -1
View File
@@ -5,7 +5,7 @@ use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate}; use wiremock::{Mock, MockServer, ResponseTemplate};
#[test] #[test]
fn provider_catalog_contains_expected_openai_compatible_providers() { fn provider_catalog_contains_expected_providers() {
let catalog = setup::provider_catalog(); let catalog = setup::provider_catalog();
let ids: Vec<_> = catalog.iter().map(|entry| entry.id).collect(); let ids: Vec<_> = catalog.iter().map(|entry| entry.id).collect();
@@ -13,6 +13,7 @@ fn provider_catalog_contains_expected_openai_compatible_providers() {
ids, ids,
vec![ vec![
"openai", "openai",
"chatgpt-codex",
"xai", "xai",
"fireworks", "fireworks",
"groq", "groq",
@@ -148,6 +149,38 @@ fn apply_setup_upserts_selected_provider_model_and_preserves_unrelated_entries()
); );
} }
#[test]
fn apply_setup_writes_chatgpt_codex_without_api_key() {
let root = tempdir().unwrap();
setup::apply_setup(
root.path(),
&SetupSelection {
provider_id: config::CHATGPT_CODEX_PROVIDER_ID.into(),
provider_name: config::CHATGPT_CODEX_PROVIDER_NAME.into(),
base_url: config::CHATGPT_CODEX_RESPONSES_URL.into(),
api_key_env: String::new(),
model_id: config::CHATGPT_CODEX_DEFAULT_MODEL.into(),
supports_tools: true,
supports_reasoning: true,
},
)
.unwrap();
let providers: ProvidersFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("providers.json")).unwrap())
.unwrap();
let provider = &providers.providers[0];
assert_eq!(provider.id, config::CHATGPT_CODEX_PROVIDER_ID);
assert_eq!(provider.kind, config::CHATGPT_CODEX_PROVIDER_KIND);
assert!(provider.api_key.is_empty());
let models: ModelsFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("models.json")).unwrap())
.unwrap();
assert!(models.models[0].fast_mode.supported);
}
#[test] #[test]
fn apply_setups_writes_multiple_providers_and_active_choice() { fn apply_setups_writes_multiple_providers_and_active_choice() {
let root = tempdir().unwrap(); let root = tempdir().unwrap();
@@ -197,6 +230,146 @@ fn apply_setups_writes_multiple_providers_and_active_choice() {
); );
} }
#[test]
fn remove_providers_removes_models_and_preserves_active_provider() {
let root = tempdir().unwrap();
let selections = vec![
SetupSelection {
provider_id: "openai".into(),
provider_name: "OpenAI".into(),
base_url: "https://api.openai.com/v1".into(),
api_key_env: "OPENAI_API_KEY".into(),
model_id: "gpt-4.1".into(),
supports_tools: true,
supports_reasoning: true,
},
SetupSelection {
provider_id: "groq".into(),
provider_name: "Groq".into(),
base_url: "https://api.groq.com/openai/v1".into(),
api_key_env: "GROQ_API_KEY".into(),
model_id: "llama-3.3-70b-versatile".into(),
supports_tools: true,
supports_reasoning: false,
},
];
setup::apply_setups(root.path(), &selections, 0).unwrap();
let result = setup::remove_providers(root.path(), &["groq".to_string()]).unwrap();
assert_eq!(result.removed_provider_ids, vec!["groq"]);
assert_eq!(result.removed_model_count, 1);
assert_eq!(result.remaining_provider_count, 1);
assert_eq!(result.active_provider.as_deref(), Some("openai"));
assert_eq!(result.active_model.as_deref(), Some("gpt-4.1"));
let providers: ProvidersFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("providers.json")).unwrap())
.unwrap();
assert_eq!(providers.providers.len(), 1);
assert_eq!(providers.providers[0].id, "openai");
let models: ModelsFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("models.json")).unwrap())
.unwrap();
assert_eq!(models.models.len(), 1);
assert_eq!(models.models[0].provider, "openai");
}
#[test]
fn remove_active_provider_selects_remaining_provider_and_model() {
let root = tempdir().unwrap();
let selections = vec![
SetupSelection {
provider_id: "openai".into(),
provider_name: "OpenAI".into(),
base_url: "https://api.openai.com/v1".into(),
api_key_env: "OPENAI_API_KEY".into(),
model_id: "gpt-4.1".into(),
supports_tools: true,
supports_reasoning: true,
},
SetupSelection {
provider_id: "groq".into(),
provider_name: "Groq".into(),
base_url: "https://api.groq.com/openai/v1".into(),
api_key_env: "GROQ_API_KEY".into(),
model_id: "llama-3.3-70b-versatile".into(),
supports_tools: true,
supports_reasoning: false,
},
];
setup::apply_setups(root.path(), &selections, 1).unwrap();
let result = setup::remove_providers(root.path(), &["groq".to_string()]).unwrap();
assert_eq!(result.active_provider.as_deref(), Some("openai"));
assert_eq!(result.active_model.as_deref(), Some("gpt-4.1"));
let config: ConfigFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("config.json")).unwrap())
.unwrap();
assert_eq!(config.default_provider.as_deref(), Some("openai"));
assert_eq!(config.default_model.as_deref(), Some("gpt-4.1"));
}
#[test]
fn remove_all_providers_clears_active_defaults() {
let root = tempdir().unwrap();
setup::apply_setup(
root.path(),
&SetupSelection {
provider_id: "openai".into(),
provider_name: "OpenAI".into(),
base_url: "https://api.openai.com/v1".into(),
api_key_env: "OPENAI_API_KEY".into(),
model_id: "gpt-4.1".into(),
supports_tools: true,
supports_reasoning: true,
},
)
.unwrap();
let result = setup::remove_providers(root.path(), &["openai".to_string()]).unwrap();
assert_eq!(result.remaining_provider_count, 0);
assert!(result.active_provider.is_none());
assert!(result.active_model.is_none());
let config: ConfigFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("config.json")).unwrap())
.unwrap();
assert!(config.default_provider.is_none());
assert!(config.default_model.is_none());
let models: ModelsFile =
serde_json::from_str(&std::fs::read_to_string(root.path().join("models.json")).unwrap())
.unwrap();
assert!(models.models.is_empty());
}
#[test]
fn remove_unknown_provider_fails() {
let root = tempdir().unwrap();
setup::apply_setup(
root.path(),
&SetupSelection {
provider_id: "openai".into(),
provider_name: "OpenAI".into(),
base_url: "https://api.openai.com/v1".into(),
api_key_env: "OPENAI_API_KEY".into(),
model_id: "gpt-4.1".into(),
supports_tools: true,
supports_reasoning: true,
},
)
.unwrap();
let err = setup::remove_providers(root.path(), &["missing".to_string()]).unwrap_err();
assert!(err
.to_string()
.contains("provider `missing` is not configured"));
}
#[test] #[test]
fn needs_initial_setup_detects_empty_and_default_only_roots() { fn needs_initial_setup_detects_empty_and_default_only_roots() {
let root = tempdir().unwrap(); let root = tempdir().unwrap();